gt
stringclasses
1 value
context
stringlengths
2.49k
119k
def module_exists(module_name): try: __import__(module_name) except ImportError: return False else: return True import codecs import datetime import doctest import ftplib import glob import os import sqlite3 import sys import xml.etree.ElementTree as ET import zipfile from datetime import datetime from subprocess import call if(module_exists('lib.blink1')): from lib.blink1 import blink1 if(module_exists('RPi.GPIO')): import RPi.GPIO as GPIO if(module_exists('smtplib')): import smtplib from email.mime.text import MIMEText class weather(object): __configPath = 'config' def __init__(self): config = __import__(self.__configPath) self.__ftp_user = config.ftp_user self.__ftp_password = config.ftp_password self.__ftp_server = config.ftp_server self.__location_id = config.location_id self.__download_dir = config.download_dir self.__database_path = config.database_path self.__notifications = config.notifications self.__db = sqlite3.connect(self.__database_path+'weather.db') self.__db.row_factory = sqlite3.Row def updateWeatherWarnings(self): self.__connectFtp() self.__downloadWeatherWarnings() self.__importWeatherWarnings() cursor = self.__db.cursor() sql_command = """UPDATE checks SET created_at = {created_at}""" sql_command = sql_command.format(created_at="(datetime('now','localtime'))") cursor.execute(sql_command) self.__db.commit() def __connectFtp(self): """ Connect to FTP Server >>> x = weather() >>> x.downloadNewFiles() True True """ self.__dwd_ftp = ftplib.FTP(self.__ftp_server) self.__dwd_ftp.login(self.__ftp_user, self.__ftp_password) return True def __downloadWeatherWarnings(self): """ load all weatherwarnings from today TODO load all weatherwarnings since last download """ directory = '/gds/gds/specials/alerts/cap/GER/status/' self.__dwd_ftp.cwd(directory) cursor = self.__db.cursor() sql_command = """SELECT created_at FROM checks ORDER BY created_at DESC LIMIT 1""" cursor.execute(sql_command) res = cursor.fetchone() if(res is None): print('No date found... starting download from today 00 o\'Clock.') sql_command = """INSERT INTO checks(created_at) VALUES ({created_at})""" sql_command = sql_command.format(created_at="(datetime('now','localtime'))") cursor.execute(sql_command) self.__db.commit() current_time = datetime.today() current_time = current_time.replace(hour=0, minute=0, second=0, microsecond=0) else: current_time = datetime.strptime(res[0],'%Y-%m-%d %H:%M:%S') tag = current_time.day if(tag < 10): tag = '0' + str(tag) stunde = current_time.hour if(stunde < 10): stunde = '0' + str(stunde) minute = current_time.minute if(minute < 10): minute = '0' + str(minute) current_day = str(current_time.year) + str(current_time.month) + str(tag) + str(stunde) + str(minute) filenames = self.__dwd_ftp.nlst() filenames.sort(reverse=True) for filename in filenames: current_file_time = datetime.strptime(filename[13:25],'%Y%m%d%H%M%S') if(current_file_time <= current_time): continue print('"'+filename+ '" downloaded.') file = open(self.__download_dir + filename, 'wb') self.__dwd_ftp.retrbinary('RETR ' + filename, file.write) file.close() with zipfile.ZipFile(self.__download_dir + filename) as zf: zf.extractall(self.__download_dir) os.remove(self.__download_dir + filename) self.__dwd_ftp.close() return True def __importWeatherWarnings(self): os.chdir(self.__download_dir) files = glob.glob("*.xml") files.sort() cursor = self.__db.cursor() for file in files: fileObject = open(file).read() has_location_id = False # TODO Make it better! for current_location_id in self.__location_id: if current_location_id in fileObject: has_location_id = True if not has_location_id: os.remove(file) continue alert = ET.parse(file) root = alert.getroot() msgType = root.find('{urn:oasis:names:tc:emergency:cap:1.2}msgType').text info = root.find('{urn:oasis:names:tc:emergency:cap:1.2}info') weather_group = '' area_color = '' for child in info.findall('{urn:oasis:names:tc:emergency:cap:1.2}eventCode'): if(child.find('{urn:oasis:names:tc:emergency:cap:1.2}valueName').text == 'GROUP'): weather_group = child.find('{urn:oasis:names:tc:emergency:cap:1.2}value').text if(child.find('{urn:oasis:names:tc:emergency:cap:1.2}valueName').text == 'AREA_COLOR'): area_color = child.find('{urn:oasis:names:tc:emergency:cap:1.2}value').text event = info.find('{urn:oasis:names:tc:emergency:cap:1.2}event').text expires = datetime.strptime(info.find('{urn:oasis:names:tc:emergency:cap:1.2}expires').text,'%Y-%m-%dT%H:%M:%S+00:00') onset = datetime.strptime(info.find('{urn:oasis:names:tc:emergency:cap:1.2}onset').text,'%Y-%m-%dT%H:%M:%S+00:00') headline = info.find('{urn:oasis:names:tc:emergency:cap:1.2}headline').text description = info.find('{urn:oasis:names:tc:emergency:cap:1.2}description').text sql_command = """INSERT OR IGNORE INTO weather_warnings (msgType, event, weather_group, color, headline, description, created_at, valid_from, valid_till) VALUES ('{msgType}', '{event}', '{weather_group}', '{color}', '{headline}', '{description}', {created_at}, "{valid_from}", "{valid_till}")""" sql_command = sql_command.format(msgType=msgType,event=event, weather_group=weather_group,color=area_color,headline=headline, description=description, created_at="(datetime('now','localtime'))", valid_from=onset, valid_till=expires) cursor.execute(sql_command) self.__db.commit() os.remove(file) return True def __getLocationIds(self): os.chdir(self.__download_dir) files = glob.glob("*.xml") files.sort() cursor = self.__db.cursor() areas = {} for file in files: alert = ET.parse(file) root = alert.getroot() info = root.find('{urn:oasis:names:tc:emergency:cap:1.2}info') if info is None: continue for child in info.findall('{urn:oasis:names:tc:emergency:cap:1.2}area'): for child2 in child.findall('{urn:oasis:names:tc:emergency:cap:1.2}geocode'): if(child2.find('{urn:oasis:names:tc:emergency:cap:1.2}valueName').text == 'WARNCELLID'): cellid = child2.find('{urn:oasis:names:tc:emergency:cap:1.2}value').text areaDesc = child.find('{urn:oasis:names:tc:emergency:cap:1.2}areaDesc').text areas[cellid] = areaDesc os.remove(file) return areas def activateNotification(self, res): """ Activate the notification. Configuration for notifications is in the config.py. >>> x = weather() >>> x.activateNotification() True """ newRgb = '' for current_color in res[0]["color"].split(): temp = hex(int(current_color)) temp = str(temp)[-2:] if(temp == 'x0'): temp = '00' newRgb += temp try: if(self.__notifications['blink1']['status'] == 'on'): signal = blink1() signal.setRgbColor(newRgb) except: print('Error for blink(1)') try: if(self.__notifications['raspberry']['status'] == 'on'): GPIO.cleanup() GPIO.setmode(GPIO.BOARD) GPIO.setup(self.__notification['raspberry']['gpiopin'], GPIO.OUT) GPIO.output(self.__notification['raspberry']['gpiopin'], True) except: print('Error for raspberry') try: if(self.__notifications['telegram']['status'] == 'on'): self.__sendTelegram(res) except: print('Error for telegram') try: if(self.__notifications['mail']['status'] == 'on'): self.__sendMail(res) except: print('Error for E-Mail') return True def __sendTelegram(self,res): for currentRes in res: msg = self.__notifications['telegram']['msg'] msg = msg.format(headline=currentRes['headline'],description=currentRes['description'],valid_till=currentRes['valid_till']) cmd = self.__notifications['telegram']['telegram_send_script_path'] +' "'+self.__notifications['telegram']['contactname']+'"' + ' "'+msg+'"' os.system(cmd) if(self.__notifications['mail']['automaticcheck']): self.setStatusChecked(res) return True def __sendMail(self,res): msg = '' for currentRes in res: msgPart = self.__notifications['mail']['msg'] msgPart = msgPart.format(headline=currentRes['headline'],description=currentRes['description'],valid_till=currentRes['valid_till'],valid_from=currentRes['valid_from'], color=currentRes['color'], weather_group=currentRes['weather_group'], event=currentRes['event'], msgType=currentRes['msgType']) msg = msg + msgPart msg = MIMEText(msg) # me == the sender's email address # you == the recipient's email address msg['Subject'] = self.__notifications['mail']['subject'] msg['From'] = self.__notifications['mail']['mail'] msg['To'] = self.__notifications['mail']['mail'] # Send the message via our own SMTP server. s = smtplib.SMTP(self.__notifications['mail']['smtp_mail_server'], self.__notifications['mail']['smtp_port']) s.ehlo() s.starttls() s.login(self.__notifications['mail']['smtp_login'],self.__notifications['mail']['smtp_password']) s.send_message(msg) s.close() if(self.__notifications['mail']['automaticcheck']): self.setStatusChecked(res) return True def deactivateNotification(self): """ TODO Deactivate signal. >>> x = weather() >>> x.deactivateNotification() True """ return True def checkWeatherWarnings(self): """ search for not checked warnings and activate notification. >>> weather.setStatusChecked() True """ cursor = self.__db.cursor() sql_command = """SELECT rowid,* FROM weather_warnings WHERE valid_till >= (datetime('now','localtime')) AND is_checked = 'False' ORDER BY msgType""" cursor.execute(sql_command) res = cursor.fetchall() if(len(res) == 0): return False self.activateNotification(res) return True def setStatusChecked(self,res = None): """ Set current warning on checked >>> weather.setStatusChecked() True """ cursor = self.__db.cursor() if(res is not None): ids = [] for currentRes in res: ids.append(str(currentRes['rowid'])) sql_command = """UPDATE weather_warnings SET is_checked = 'True' WHERE is_checked = 'False' AND rowid IN ({id})""" sql_command = sql_command.format(id=','.join(ids)) cursor.execute(sql_command) self.__db.commit() return True sql_command = """SELECT rowid FROM weather_warnings WHERE valid_till >= (datetime('now','localtime')) AND is_checked = 'False' ORDER BY msgType""" cursor.execute(sql_command) res = cursor.fetchone() if(res is None): return False sql_command = """UPDATE weather_warnings SET is_checked = 'True' WHERE is_checked = 'False' AND rowid = {id}""" sql_command = sql_command.format(id=res['rowid']) cursor.execute(sql_command) self.__db.commit() return True def printCurrentIds(self): self.__connectFtp() self.__downloadWeatherWarnings() areas = self.__getLocationIds() for cellid, areaDesc in areas.items(): print(str(cellid) + ': ' + areaDesc) if __name__ == "__main__": doctest.testmod()
from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.screenmanager import ScreenManager, Screen from kivy.properties import ObjectProperty from kivy.core.window import Window from kivy.graphics import Color from kivy.uix.widget import Widget from kivy.clock import Clock from kivy.core.text import LabelBase import time import os import threading import rospy from std_msgs.msg import String import threading import json from random import shuffle, sample import sys import datetime num_of_matrix=8 the_matrices = range(0, num_of_matrix) exp_flow = [ #step 0 { 'behavior_before': None, 'time': 60.0, 'behavior_after': 'physical_curiosity/stand_init', 'tasks':False }, #step 1 { 'behavior_before': 'physical_curiosity/m/opening', 'time': -1, 'behavior_after': 'physical_curiosity/stand_init', 'tasks':True, 'use_matrix':0 }, #step 2 { 'behavior_before': 'physical_curiosity/m/confused1', 'time': 60.0, 'behavior_after': 'physical_curiosity/stand_init', 'tasks': True }, #step 3 { 'behavior_before': 'physical_curiosity/m/break1', 'time': -1, 'behavior_after': None, 'tasks': False, 'use_matrix': False }, #step 4 { 'behavior_before': 'physical_curiosity/m/confused2', 'time': 60.0, 'behavior_after': 'physical_curiosity/stand_init', 'tasks': True }, #step 5 { 'behavior_before': 'physical_curiosity/m/confused3', 'time': 60.0, 'behavior_after': 'physical_curiosity/stand_init', 'tasks': True }, #step 6 { 'behavior_before': 'physical_curiosity/m/break2.1', 'time': 120.0, 'behavior_after': 'physical_curiosity/m/break2.2', 'tasks': False, 'use_matrix': False }, #step 7 { 'behavior_before': 'physical_curiosity/m/confused2', 'time': 60.0, 'behavior_after': 'physical_curiosity/stand_init', 'tasks': True }, #step 8 { 'behavior_before': 'physical_curiosity/m/confused3', 'time': 60.0, 'behavior_after': 'physical_curiosity/stand_init', 'tasks': True }, #step 9 { 'behavior_before': 'physical_curiosity/m/break3', 'time': -1, 'behavior_after': None, 'tasks': False, 'use_matrix': False }, #step 10 { 'behavior_before': 'physical_curiosity/m/confused2', 'time': 60.0, 'behavior_after': 'physical_curiosity/stand_init', 'tasks': True }, #step 11 { 'behavior_before': 'physical_curiosity/m/confused3', 'time': 60.0, 'behavior_after': 'physical_curiosity/stand_init', 'tasks': True }, #step 12 { 'behavior_before': 'physical_curiosity/m/end_task', 'time': 120.0, 'behavior_after': 'physical_curiosity/stand_init', 'tasks': False }, #step 13 { 'behavior_before': 'physical_curiosity/m/end_part_a', 'time': -1, 'behavior_after': None, 'tasks': False, 'use_matrix': False }, ] tasks = [ { 'behavior_before': 'physical_curiosity/tasks/m/two_hands_up', 'time': 15.0, 'behavior_after': 'physical_curiosity/tasks/well_done' }, { 'behavior_before': 'physical_curiosity/tasks/m/two_hands_forward', 'time': 15.0, 'behavior_after': 'physical_curiosity/tasks/nice' }, { 'behavior_before': 'physical_curiosity/tasks/m/two_hands_down', 'time': 15.0, 'behavior_after': 'physical_curiosity/tasks/wow' }, { 'behavior_before': 'physical_curiosity/tasks/m/two_hands_to_the_side', 'time': 15.0, 'behavior_after': 'physical_curiosity/stand_init' }, { 'behavior_before': 'physical_curiosity/tasks/m/right_hand_up_left_hand_down', 'time': 15.0, 'behavior_after': 'physical_curiosity/stand_init' }, { 'behavior_before': 'physical_curiosity/tasks/m/right_hand_up_left_hand_forward', 'time': 15.0, 'behavior_after': 'physical_curiosity/stand_init' }, { 'behavior_before': 'physical_curiosity/tasks/m/right_hand_up_left_hand_to_the_side', 'time': 15.0, 'behavior_after': 'physical_curiosity/tasks/well_done' }, { 'behavior_before': 'physical_curiosity/tasks/m/right_hand_forward_left_hand_down', 'time': 15.0, 'behavior_after': 'physical_curiosity/nice' }, { 'behavior_before': 'physical_curiosity/tasks/m/right_hand_forward_left_hand_side', 'time': 15.0, 'behavior_after': 'physical_curiosity/tasks/wow' }, { 'behavior_before': 'physical_curiosity/tasks/m/right_hand_to_the_side_left_hand_down', 'time': 15.0, 'behavior_after': 'physical_curiosity/stand_init' }, { 'behavior_before': 'physical_curiosity/tasks/m/right_hand_to_the_side_left_hand_forward', 'time': 15.0, 'behavior_after': 'physical_curiosity/stand_init' }, { 'behavior_before': 'physical_curiosity/tasks/m/right_hand_down_left_hand_to_the_side', 'time': 15.0, 'behavior_after': 'physical_curiosity/stand_init' }, { 'behavior_before': 'physical_curiosity/tasks/m/right_hand_down_left_hand_forward', 'time': 15.0, 'behavior_after': 'physical_curiosity/tasks/well_done' }, { 'behavior_before': 'physical_curiosity/tasks/m/left_hand_up_right_hand_down', 'time': 15.0, 'behavior_after': 'physical_curiosity/tasks/nice' }, { 'behavior_before': 'physical_curiosity/tasks/m/left_hand_up_right_hand_forward', 'time': 15.0, 'behavior_after': 'physical_curiosity/tasks/wow' }, { 'behavior_before': 'physical_curiosity/tasks/m/left_hand_up_right_hand_to_the_side', 'time': 15.0, 'behavior_after': 'physical_curiosity/stand_init' } ] # declaration of forms # connection to .kv file class Config(BoxLayout): pass # nao_ip = ObjectProperty() # subject_id= ObjectProperty() class Experiment_screen(BoxLayout): kinect_status_id = ObjectProperty() state_text_input = ObjectProperty() next_button = ObjectProperty() timer=ObjectProperty() stop_button = ObjectProperty() # the app definition class ExperimentApp(App): subject_id = 0 nao_ip = '192.168.0.103' state = 0 proceed = False def build(self): # connect internal instances of form classes self.config = Config() self.experiment_screen = Experiment_screen() # defines the screen manager, moves between forms self.sm = ScreenManager() # connects each form to a screen screen = Screen(name='config') screen.add_widget(self.config) Window.clearcolor = (1, 1, 1, 1) self.sm.add_widget(screen) screen = Screen(name='experiment_screen') screen.add_widget(self.experiment_screen) Window.clearcolor = (1, 1, 1, 1) self.sm.add_widget(screen) return self.sm def update_tracking(self, data): self.experiment_screen.ids['kinect_status_id'].text = data.data def goto_experiment_screen(self,subject_id,nao_ip):#go to experiment screen self.experiment_screen.ids['stop_button'].disabled = True print subject_id print nao_ip self.subject_id = subject_id self.nao_ip = nao_ip t1 = threading.Thread(target=self.run_main) t1.start() threading._sleep(1.0) rospy.init_node('ui_node') rospy.Subscriber("tracking", String, self.update_tracking) self.flow = rospy.Publisher ('the_flow', String, queue_size=10) self.nao = rospy.Publisher('to_nao', String, queue_size=10) self.log = rospy.Publisher("experiment_log", String, queue_size=10) rospy.Subscriber("nao_state", String, self.parse_nao_state) threading._sleep(3.0) self.nao.publish('{\"action\": \"run_behavior\", \"parameters\": [\"dialog_posture/bhv_stand_up\"]}') threading._sleep(1.0) # set the current_subject matrices self.matrices = the_matrices shuffle(self.matrices) self.matrix_for_state = {} current_index=0 for stage_no in range(len(exp_flow)): if "use_matrix" in exp_flow[stage_no] and exp_flow[stage_no]["use_matrix"]is False: print stage_no self.matrix_for_state[stage_no]=None elif "use_matrix" in exp_flow[stage_no] and type(exp_flow[stage_no]["use_matrix"]) is int: self.matrix_for_state[stage_no]=self.matrices[exp_flow[stage_no]["use_matrix"]] else: if current_index < len(self.matrices): self.matrix_for_state[stage_no] =self.matrices[current_index] current_index+=1 else: self.matrix_for_state[stage_no] = current_index print self.matrix_for_state self.sm.current="experiment_screen" def run_main(self): os.system('python main_nao.py ' + self.subject_id + ' ' + self.nao_ip) def parse_nao_state(self, data): try: message = json.loads(data.data) if 'name' in message: self.proceed = True except: print('nao_state not a json: ', data.data) def epoch(self, behavior_before=None, time=-1, matrix=None, behavior_after=None, tasks=None): # task: {'behavior_before', 'time'} # learning round print('-- learning round: ', behavior_before, time, matrix, behavior_after) self.log.publish("state %d, learning_round" % self.state) self.round(behavior_before=behavior_before, time=time, matrix=matrix, behavior_after=behavior_after) print "------tasks---------" if tasks: for i, task in enumerate(tasks): print('-- task round: ', behavior_before, time, matrix, behavior_after) self.log.publish("state %d, task: %d, %s" % (self.state, i, task['behavior_before'])) self.round(behavior_before=task['behavior_before'], time=task['time'], matrix=matrix, behavior_after=task['behavior_after']) def round(self, behavior_before=None, time=-1, matrix=None, behavior_after=None): self.proceed = True if behavior_before: # publish directly to nao_ros robot_str = '{\"name\": \"behavior_before\", \"action\" : \"run_behavior\", \"parameters\" : [\"' + behavior_before + '\", \"wait\"]}' self.nao.publish(robot_str) self.proceed = False while not self.proceed: pass if time >= 0 and matrix is not None: # run epoch with matrix self.delta = datetime.datetime.now()+datetime.timedelta(0, time) Clock.schedule_interval(self.update_timer, 0.05) self.exp_start() self.flow.publish(str(matrix)) threading._sleep(time) Clock.unschedule(self.update_timer) self.experiment_screen.ids['timer'].text = str("00:00") self.exp_stop() if time >= 0 and matrix is None: self.delta = datetime.datetime.now()+datetime.timedelta(0, time) Clock.schedule_interval(self.update_timer, 0.05) self.experiment_screen.ids['timer'].text = str(time) threading._sleep(time) Clock.unschedule(self.update_timer) self.experiment_screen.ids['timer'].text = str("00:00") if behavior_after: # publish directly to nao_ros robot_str = '{\"name\": \"behavior_after\", \"action\" : \"run_behavior\", \"parameters\" : [\"' + behavior_after + '\", \"wait\"]}' self.nao.publish(robot_str) self.proceed = False while not self.proceed: pass def exp_start(self): self.flow.publish('start') self.proceed = False def exp_stop(self): print('---stop---') self.flow.publish('stop') self.proceed = True def the_end(self): self.exp_stop() self.flow.publish('the end') def next_epoch(self): self.experiment_screen.ids['next_button'].disabled = True threading.Thread(target=self.epoch_thread).start() def epoch_thread(self): self.state = int(self.experiment_screen.ids['state_text_input'].text) self.log.publish("current_state: %d" % self.state) if self.state ==len(exp_flow)-2: self.run_end_task() else: if exp_flow[self.state]['tasks']: current_tasks = sample(tasks, 3) else: current_tasks = None self.epoch(behavior_before=exp_flow[self.state]['behavior_before'], time=exp_flow[self.state]['time'], matrix=self.matrix_for_state[self.state], behavior_after=exp_flow[self.state]['behavior_after'], tasks=current_tasks ) self.state += 1 self.experiment_screen.ids['state_text_input'].text = str(self.state) self.experiment_screen.ids['next_button'].disabled = False def btn_released(self,btn,func,param1=None,param2=None):#button configuration btn.background_coler=(1,1,1,1) if param1 is not None: func_param1=param1.text if param2 is not None: func_param2 = param2.text func(func_param1,func_param2) else: func(func_param1) else: func() def exit_experiment(self): self.nao.publish('{\"action\" : \"rest\"}') def update_timer(self, kt): delta = self.delta - datetime.datetime.now() minutes, seconds = str(delta).split(":")[1:] seconds = seconds[:5] self.experiment_screen.ids['timer'].text = str(minutes+':'+seconds) def rest(self): self.nao.publish('{\"action\": \"rest\"}') def stand_up(self): self.nao.publish('{\"action\": \"wake_up\"}') threading._sleep(0.1) self.nao.publish('{\"action\": \"run_behavior\", \"parameters\": [\"dialog_posture/bhv_stand_up\"]}') def run_end_task(self): self.proceed = True # publish directly to nao_ros behavior_before = exp_flow[self.state]['behavior_before'] robot_str = '{\"name\": \"behavior_before\", \"action\" : \"run_behavior\", \"parameters\" : [\"' + behavior_before + '\", \"wait\"]}' self.nao.publish(robot_str) self.proceed = False while not self.proceed: pass time=exp_flow[self.state]['time'] self.delta = datetime.datetime.now()+datetime.timedelta(0, time) Clock.schedule_interval(self.update_timer, 0.05) Clock.schedule_once(self.end_end_task, time) self.experiment_screen.ids['stop_button'].disabled = False self.exp_start() self.flow.publish(str(self.matrix_for_state[self.state])) def end_end_task(self, tk=None): self.experiment_screen.ids['stop_button'].disabled = True Clock.unschedule(self.end_end_task) Clock.unschedule(self.update_timer) self.experiment_screen.ids['timer'].text = str("00:00") self.exp_stop() self.state += 1 self.experiment_screen.ids['state_text_input'].text = str(self.state) self.experiment_screen.ids['next_button'].disabled = False if __name__ == '__main__': ExperimentApp().run()
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 OpenStack Foundation # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.conf import settings from django.contrib.auth.models import User # noqa from django.core.exceptions import ImproperlyConfigured # noqa from django.core import urlresolvers from django.utils.importlib import import_module # noqa import horizon from horizon import base from horizon import conf from horizon.test import helpers as test from horizon.test.test_dashboards.cats.dashboard import Cats # noqa from horizon.test.test_dashboards.cats.kittens.panel import Kittens # noqa from horizon.test.test_dashboards.cats.tigers.panel import Tigers # noqa from horizon.test.test_dashboards.dogs.dashboard import Dogs # noqa from horizon.test.test_dashboards.dogs.puppies.panel import Puppies # noqa class MyDash(horizon.Dashboard): name = "My Dashboard" slug = "mydash" default_panel = "myslug" class MyPanel(horizon.Panel): name = "My Panel" slug = "myslug" urls = 'horizon.test.test_dashboards.cats.kittens.urls' class AdminPanel(horizon.Panel): name = "Admin Panel" slug = "admin_panel" permissions = ("horizon.test",) urls = 'horizon.test.test_dashboards.cats.kittens.urls' class BaseHorizonTests(test.TestCase): def setUp(self): super(BaseHorizonTests, self).setUp() # Adjust our horizon config and register our custom dashboards/panels. self.old_default_dash = settings.HORIZON_CONFIG['default_dashboard'] settings.HORIZON_CONFIG['default_dashboard'] = 'cats' self.old_dashboards = settings.HORIZON_CONFIG['dashboards'] settings.HORIZON_CONFIG['dashboards'] = ('cats', 'dogs') base.Horizon.register(Cats) base.Horizon.register(Dogs) Cats.register(Kittens) Cats.register(Tigers) Dogs.register(Puppies) # Trigger discovery, registration, and URLconf generation if it # hasn't happened yet. base.Horizon._urls() # Store our original dashboards self._discovered_dashboards = base.Horizon._registry.keys() # Gather up and store our original panels for each dashboard self._discovered_panels = {} for dash in self._discovered_dashboards: panels = base.Horizon._registry[dash]._registry.keys() self._discovered_panels[dash] = panels def tearDown(self): super(BaseHorizonTests, self).tearDown() # Restore our settings settings.HORIZON_CONFIG['default_dashboard'] = self.old_default_dash settings.HORIZON_CONFIG['dashboards'] = self.old_dashboards # Destroy our singleton and re-create it. base.HorizonSite._instance = None del base.Horizon base.Horizon = base.HorizonSite() # Reload the convenience references to Horizon stored in __init__ reload(import_module("horizon")) # Re-register our original dashboards and panels. # This is necessary because autodiscovery only works on the first # import, and calling reload introduces innumerable additional # problems. Manual re-registration is the only good way for testing. self._discovered_dashboards.remove(Cats) self._discovered_dashboards.remove(Dogs) for dash in self._discovered_dashboards: base.Horizon.register(dash) for panel in self._discovered_panels[dash]: dash.register(panel) def _reload_urls(self): """Clears out the URL caches, reloads the root urls module, and re-triggers the autodiscovery mechanism for Horizon. Allows URLs to be re-calculated after registering new dashboards. Useful only for testing and should never be used on a live site. """ urlresolvers.clear_url_caches() reload(import_module(settings.ROOT_URLCONF)) base.Horizon._urls() class HorizonTests(BaseHorizonTests): def test_registry(self): """Verify registration and autodiscovery work correctly. Please note that this implicitly tests that autodiscovery works by virtue of the fact that the dashboards listed in ``settings.INSTALLED_APPS`` are loaded from the start. """ # Registration self.assertEqual(len(base.Horizon._registry), 2) horizon.register(MyDash) self.assertEqual(len(base.Horizon._registry), 3) with self.assertRaises(ValueError): horizon.register(MyPanel) with self.assertRaises(ValueError): horizon.register("MyPanel") # Retrieval my_dash_instance_by_name = horizon.get_dashboard("mydash") self.assertIsInstance(my_dash_instance_by_name, MyDash) my_dash_instance_by_class = horizon.get_dashboard(MyDash) self.assertEqual(my_dash_instance_by_name, my_dash_instance_by_class) with self.assertRaises(base.NotRegistered): horizon.get_dashboard("fake") self.assertQuerysetEqual(horizon.get_dashboards(), ['<Dashboard: cats>', '<Dashboard: dogs>', '<Dashboard: mydash>']) # Removal self.assertEqual(len(base.Horizon._registry), 3) horizon.unregister(MyDash) self.assertEqual(len(base.Horizon._registry), 2) with self.assertRaises(base.NotRegistered): horizon.get_dashboard(MyDash) def test_site(self): self.assertEqual(unicode(base.Horizon), "Horizon") self.assertEqual(repr(base.Horizon), "<Site: horizon>") dash = base.Horizon.get_dashboard('cats') self.assertEqual(base.Horizon.get_default_dashboard(), dash) test_user = User() self.assertEqual(base.Horizon.get_user_home(test_user), dash.get_absolute_url()) def test_dashboard(self): cats = horizon.get_dashboard("cats") self.assertEqual(cats._registered_with, base.Horizon) self.assertQuerysetEqual(cats.get_panels(), ['<Panel: kittens>', '<Panel: tigers>']) self.assertEqual(cats.get_absolute_url(), "/cats/") self.assertEqual(cats.name, "Cats") # Test registering a module with a dashboard that defines panels # as a panel group. cats.register(MyPanel) self.assertQuerysetEqual(cats.get_panel_groups()['other'], ['<Panel: myslug>']) # Test that panels defined as a tuple still return a PanelGroup dogs = horizon.get_dashboard("dogs") self.assertQuerysetEqual(dogs.get_panel_groups().values(), ['<PanelGroup: default>']) # Test registering a module with a dashboard that defines panels # as a tuple. dogs = horizon.get_dashboard("dogs") dogs.register(MyPanel) self.assertQuerysetEqual(dogs.get_panels(), ['<Panel: puppies>', '<Panel: myslug>']) def test_panels(self): cats = horizon.get_dashboard("cats") tigers = cats.get_panel("tigers") self.assertEqual(tigers._registered_with, cats) self.assertEqual(tigers.get_absolute_url(), "/cats/tigers/") def test_panel_without_slug_fails(self): class InvalidPanel(horizon.Panel): name = 'Invalid' self.assertRaises(ImproperlyConfigured, InvalidPanel) def test_registry_without_registerable_class_attr_fails(self): class InvalidRegistry(base.Registry): pass self.assertRaises(ImproperlyConfigured, InvalidRegistry) def test_index_url_name(self): cats = horizon.get_dashboard("cats") tigers = cats.get_panel("tigers") tigers.index_url_name = "does_not_exist" with self.assertRaises(urlresolvers.NoReverseMatch): tigers.get_absolute_url() tigers.index_url_name = "index" self.assertEqual(tigers.get_absolute_url(), "/cats/tigers/") def test_lazy_urls(self): urlpatterns = horizon.urls[0] self.assertIsInstance(urlpatterns, base.LazyURLPattern) # The following two methods simply should not raise any exceptions iter(urlpatterns) reversed(urlpatterns) def test_horizon_test_isolation_1(self): """Isolation Test Part 1: sets a value.""" cats = horizon.get_dashboard("cats") cats.evil = True def test_horizon_test_isolation_2(self): """Isolation Test Part 2: The value set in part 1 should be gone.""" cats = horizon.get_dashboard("cats") self.assertFalse(hasattr(cats, "evil")) def test_public(self): dogs = horizon.get_dashboard("dogs") # Known to have no restrictions on it other than being logged in. puppies = dogs.get_panel("puppies") url = puppies.get_absolute_url() # Get a clean, logged out client instance. self.client.logout() resp = self.client.get(url) redirect_url = "?".join(['http://testserver' + settings.LOGIN_URL, "next=%s" % url]) self.assertRedirects(resp, redirect_url) # Simulate ajax call resp = self.client.get(url, HTTP_X_REQUESTED_WITH='XMLHttpRequest') # Response should be HTTP 401 with redirect header self.assertEqual(resp.status_code, 401) self.assertEqual(resp["X-Horizon-Location"], redirect_url) def test_required_permissions(self): dash = horizon.get_dashboard("cats") panel = dash.get_panel('tigers') # Non-admin user self.assertQuerysetEqual(self.user.get_all_permissions(), []) resp = self.client.get(panel.get_absolute_url()) self.assertEqual(resp.status_code, 302) resp = self.client.get(panel.get_absolute_url(), follow=False, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(resp.status_code, 401) # Test insufficient permissions for logged-in user resp = self.client.get(panel.get_absolute_url(), follow=True) self.assertEqual(resp.status_code, 200) self.assertTemplateUsed(resp, "auth/login.html") self.assertContains(resp, "Login as different user", 1, 200) # Set roles for admin user self.set_permissions(permissions=['test']) resp = self.client.get(panel.get_absolute_url()) self.assertEqual(resp.status_code, 200) # Test modal form resp = self.client.get(panel.get_absolute_url(), follow=False, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(resp.status_code, 200) def test_ssl_redirect_by_proxy(self): dogs = horizon.get_dashboard("dogs") puppies = dogs.get_panel("puppies") url = puppies.get_absolute_url() redirect_url = "?".join([settings.LOGIN_URL, "next=%s" % url]) self.client.logout() resp = self.client.get(url) self.assertRedirects(resp, redirect_url) # Set SSL settings for test server settings.SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https') resp = self.client.get(url, HTTP_X_FORWARDED_PROTOCOL="https") self.assertEqual(resp.status_code, 302) self.assertEqual(resp['location'], 'https://testserver:80%s' % redirect_url) # Restore settings settings.SECURE_PROXY_SSL_HEADER = None class GetUserHomeTests(BaseHorizonTests): """Test get_user_home parameters.""" def setUp(self): self.orig_user_home = settings.HORIZON_CONFIG['user_home'] super(BaseHorizonTests, self).setUp() self.original_username = "testname" self.test_user = User() self.test_user.username = self.original_username def tearDown(self): settings.HORIZON_CONFIG['user_home'] = self.orig_user_home conf.HORIZON_CONFIG._setup() def test_using_callable(self): def fancy_user_fnc(user): return user.username.upper() settings.HORIZON_CONFIG['user_home'] = fancy_user_fnc conf.HORIZON_CONFIG._setup() self.assertEqual(self.test_user.username.upper(), base.Horizon.get_user_home(self.test_user)) def test_using_module_function(self): module_func = 'django.utils.html.strip_tags' settings.HORIZON_CONFIG['user_home'] = module_func conf.HORIZON_CONFIG._setup() self.test_user.username = '<ignore>testname<ignore>' self.assertEqual(self.original_username, base.Horizon.get_user_home(self.test_user)) def test_using_url(self): fixed_url = "/url" settings.HORIZON_CONFIG['user_home'] = fixed_url conf.HORIZON_CONFIG._setup() self.assertEqual(fixed_url, base.Horizon.get_user_home(self.test_user)) class CustomPanelTests(BaseHorizonTests): """Test customization of dashboards and panels using 'customization_module' to HORIZON_CONFIG. """ def setUp(self): settings.HORIZON_CONFIG['customization_module'] = \ 'horizon.test.customization.cust_test1' # refresh config conf.HORIZON_CONFIG._setup() super(CustomPanelTests, self).setUp() def tearDown(self): # Restore dash cats = horizon.get_dashboard("cats") cats.name = "Cats" horizon.register(Dogs) self._discovered_dashboards.append(Dogs) Dogs.register(Puppies) Cats.register(Tigers) super(CustomPanelTests, self).tearDown() settings.HORIZON_CONFIG.pop('customization_module') # refresh config conf.HORIZON_CONFIG._setup() def test_customize_dashboard(self): cats = horizon.get_dashboard("cats") self.assertEqual(cats.name, "WildCats") self.assertQuerysetEqual(cats.get_panels(), ['<Panel: kittens>']) with self.assertRaises(base.NotRegistered): horizon.get_dashboard("dogs") class CustomPermissionsTests(BaseHorizonTests): """Test customization of permissions on panels using 'customization_module' to HORIZON_CONFIG. """ def setUp(self): settings.HORIZON_CONFIG['customization_module'] = \ 'horizon.test.customization.cust_test2' # refresh config conf.HORIZON_CONFIG._setup() super(CustomPermissionsTests, self).setUp() def tearDown(self): # Restore permissions dogs = horizon.get_dashboard("dogs") puppies = dogs.get_panel("puppies") puppies.permissions = tuple([]) super(CustomPermissionsTests, self).tearDown() settings.HORIZON_CONFIG.pop('customization_module') # refresh config conf.HORIZON_CONFIG._setup() def test_customized_permissions(self): dogs = horizon.get_dashboard("dogs") panel = dogs.get_panel('puppies') # Non-admin user self.assertQuerysetEqual(self.user.get_all_permissions(), []) resp = self.client.get(panel.get_absolute_url()) self.assertEqual(resp.status_code, 302) resp = self.client.get(panel.get_absolute_url(), follow=False, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(resp.status_code, 401) # Test customized permissions for logged-in user resp = self.client.get(panel.get_absolute_url(), follow=True) self.assertEqual(resp.status_code, 200) self.assertTemplateUsed(resp, "auth/login.html") self.assertContains(resp, "Login as different user", 1, 200) # Set roles for admin user self.set_permissions(permissions=['test']) resp = self.client.get(panel.get_absolute_url()) self.assertEqual(resp.status_code, 200) # Test modal form resp = self.client.get(panel.get_absolute_url(), follow=False, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(resp.status_code, 200)
"""Tests for text2html """ import unittest from django.test import TestCase from evennia.utils import ansi, text2html import mock class TestText2Html(TestCase): def test_re_color(self): parser = text2html.HTML_PARSER self.assertEqual("foo", parser.re_color("foo")) self.assertEqual( '<span class="color-001">red</span>foo', parser.re_color(ansi.ANSI_UNHILITE + ansi.ANSI_RED + "red" + ansi.ANSI_NORMAL + "foo"), ) self.assertEqual( '<span class="bgcolor-001">red</span>foo', parser.re_color(ansi.ANSI_BACK_RED + "red" + ansi.ANSI_NORMAL + "foo"), ) self.assertEqual( '<span class="bgcolor-001"><span class="color-002">red</span></span>foo', parser.re_color( ansi.ANSI_BACK_RED + ansi.ANSI_UNHILITE + ansi.ANSI_GREEN + "red" + ansi.ANSI_NORMAL + "foo" ), ) @unittest.skip("parser issues") def test_re_bold(self): parser = text2html.HTML_PARSER self.assertEqual("foo", parser.re_bold("foo")) self.assertEqual( # "a <strong>red</strong>foo", # TODO: why not? "a <strong>redfoo</strong>", parser.re_bold("a " + ansi.ANSI_HILITE + "red" + ansi.ANSI_UNHILITE + "foo"), ) @unittest.skip("parser issues") def test_re_underline(self): parser = text2html.HTML_PARSER self.assertEqual("foo", parser.re_underline("foo")) self.assertEqual( 'a <span class="underline">red</span>' + ansi.ANSI_NORMAL + "foo", parser.re_underline( "a " + ansi.ANSI_UNDERLINE + "red" + ansi.ANSI_NORMAL # TODO: why does it keep it? + "foo" ), ) @unittest.skip("parser issues") def test_re_blinking(self): parser = text2html.HTML_PARSER self.assertEqual("foo", parser.re_blinking("foo")) self.assertEqual( 'a <span class="blink">red</span>' + ansi.ANSI_NORMAL + "foo", parser.re_blinking( "a " + ansi.ANSI_BLINK + "red" + ansi.ANSI_NORMAL # TODO: why does it keep it? + "foo" ), ) @unittest.skip("parser issues") def test_re_inversing(self): parser = text2html.HTML_PARSER self.assertEqual("foo", parser.re_inversing("foo")) self.assertEqual( 'a <span class="inverse">red</span>' + ansi.ANSI_NORMAL + "foo", parser.re_inversing( "a " + ansi.ANSI_INVERSE + "red" + ansi.ANSI_NORMAL # TODO: why does it keep it? + "foo" ), ) @unittest.skip("parser issues") def test_remove_bells(self): parser = text2html.HTML_PARSER self.assertEqual("foo", parser.remove_bells("foo")) self.assertEqual( "a red" + ansi.ANSI_NORMAL + "foo", parser.remove_bells( "a " + ansi.ANSI_BEEP + "red" + ansi.ANSI_NORMAL # TODO: why does it keep it? + "foo" ), ) def test_remove_backspaces(self): parser = text2html.HTML_PARSER self.assertEqual("foo", parser.remove_backspaces("foo")) self.assertEqual("redfoo", parser.remove_backspaces("a\010redfoo")) def test_convert_linebreaks(self): parser = text2html.HTML_PARSER self.assertEqual("foo", parser.convert_linebreaks("foo")) self.assertEqual("a<br> redfoo<br>", parser.convert_linebreaks("a\n redfoo\n")) @unittest.skip("parser issues") def test_convert_urls(self): parser = text2html.HTML_PARSER self.assertEqual("foo", parser.convert_urls("foo")) self.assertEqual( 'a <a href="http://redfoo" target="_blank">http://redfoo</a> runs', parser.convert_urls("a http://redfoo runs"), ) # TODO: doesn't URL encode correctly def test_re_double_space(self): parser = text2html.HTML_PARSER self.assertEqual("foo", parser.re_double_space("foo")) self.assertEqual( "a &nbsp;red &nbsp;&nbsp;&nbsp;foo", parser.re_double_space("a red foo") ) def test_sub_mxp_links(self): parser = text2html.HTML_PARSER mocked_match = mock.Mock() mocked_match.groups.return_value = ["cmd", "text"] self.assertEqual( r"""<a id="mxplink" href="#" """ """onclick="Evennia.msg(&quot;text&quot;,[&quot;cmd&quot;],{});""" """return false;">text</a>""", parser.sub_mxp_links(mocked_match), ) def test_sub_text(self): parser = text2html.HTML_PARSER mocked_match = mock.Mock() mocked_match.groupdict.return_value = {"htmlchars": "foo"} self.assertEqual("foo", parser.sub_text(mocked_match)) mocked_match.groupdict.return_value = {"htmlchars": "", "lineend": "foo"} self.assertEqual("<br>", parser.sub_text(mocked_match)) parser.tabstop = 2 mocked_match.groupdict.return_value = { "htmlchars": "", "lineend": "", "tab": "\t", "space": "", } self.assertEqual(" &nbsp;", parser.sub_text(mocked_match)) mocked_match.groupdict.return_value = { "htmlchars": "", "lineend": "", "tab": "\t\t", "space": " ", "spacestart": " ", } self.assertEqual(" &nbsp; &nbsp;", parser.sub_text(mocked_match)) mocked_match.groupdict.return_value = { "htmlchars": "", "lineend": "", "tab": "", "space": "", "spacestart": "", } self.assertEqual(None, parser.sub_text(mocked_match)) def test_parse_tab_to_html(self): """Test entire parse mechanism""" parser = text2html.HTML_PARSER parser.tabstop = 4 # single tab self.assertEqual(parser.parse("foo|>foo"), "foo &nbsp;&nbsp;&nbsp;foo") # space and tab self.assertEqual(parser.parse("foo |>foo"), "foo &nbsp;&nbsp;&nbsp;&nbsp;foo") # space, tab, space self.assertEqual(parser.parse("foo |> foo"), "foo &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;foo") def test_parse_space_to_html(self): """test space parsing - a single space should be kept, two or more should get &nbsp;""" parser = text2html.HTML_PARSER # single space self.assertEqual(parser.parse("foo foo"), "foo foo") # double space self.assertEqual(parser.parse("foo foo"), "foo &nbsp;foo") # triple space self.assertEqual(parser.parse("foo foo"), "foo &nbsp;&nbsp;foo") def test_parse_html(self): self.assertEqual("foo", text2html.parse_html("foo")) self.maxDiff = None self.assertEqual( # TODO: note that the blink is currently *not* correctly aborted # with |n here! This is probably not possible to correctly handle # with regex - a stateful parser may be needed. # blink back-cyan normal underline red green yellow blue magenta cyan back-green text2html.parse_html("|^|[CHello|n|u|rW|go|yr|bl|md|c!|[G!"), '<span class="blink">' '<span class="bgcolor-006">Hello</span>' # noqa '<span class="underline">' '<span class="color-009">W</span>' # noqa '<span class="color-010">o</span>' '<span class="color-011">r</span>' '<span class="color-012">l</span>' '<span class="color-013">d</span>' '<span class="color-014">!' '<span class="bgcolor-002">!</span>' # noqa '</span>' '</span>' '</span>' )
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for Keras loss functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import shutil import numpy as np from tensorflow.python import keras from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops.losses import losses_impl from tensorflow.python.platform import test try: import h5py # pylint:disable=g-import-not-at-top except ImportError: h5py = None ALL_LOSSES = [keras.losses.mean_squared_error, keras.losses.mean_absolute_error, keras.losses.mean_absolute_percentage_error, keras.losses.mean_squared_logarithmic_error, keras.losses.squared_hinge, keras.losses.hinge, keras.losses.categorical_crossentropy, keras.losses.binary_crossentropy, keras.losses.kullback_leibler_divergence, keras.losses.poisson, keras.losses.cosine_proximity, keras.losses.logcosh, keras.losses.categorical_hinge] class _MSEMAELoss(object): """Loss function with internal state, for testing serialization code.""" def __init__(self, mse_fraction): self.mse_fraction = mse_fraction def __call__(self, y_true, y_pred): return (self.mse_fraction * keras.losses.mse(y_true, y_pred) + (1 - self.mse_fraction) * keras.losses.mae(y_true, y_pred)) def get_config(self): return {'mse_fraction': self.mse_fraction} class KerasLossesTest(test.TestCase): def test_objective_shapes_3d(self): with self.cached_session(): y_a = keras.backend.variable(np.random.random((5, 6, 7))) y_b = keras.backend.variable(np.random.random((5, 6, 7))) for obj in ALL_LOSSES: objective_output = obj(y_a, y_b) self.assertListEqual(objective_output.get_shape().as_list(), [5, 6]) def test_objective_shapes_2d(self): with self.cached_session(): y_a = keras.backend.variable(np.random.random((6, 7))) y_b = keras.backend.variable(np.random.random((6, 7))) for obj in ALL_LOSSES: objective_output = obj(y_a, y_b) self.assertListEqual(objective_output.get_shape().as_list(), [6,]) def test_cce_one_hot(self): with self.cached_session(): y_a = keras.backend.variable(np.random.randint(0, 7, (5, 6))) y_b = keras.backend.variable(np.random.random((5, 6, 7))) objective_output = keras.losses.sparse_categorical_crossentropy(y_a, y_b) assert keras.backend.eval(objective_output).shape == (5, 6) y_a = keras.backend.variable(np.random.randint(0, 7, (6,))) y_b = keras.backend.variable(np.random.random((6, 7))) objective_output = keras.losses.sparse_categorical_crossentropy(y_a, y_b) assert keras.backend.eval(objective_output).shape == (6,) def test_serialization(self): fn = keras.losses.get('mse') config = keras.losses.serialize(fn) new_fn = keras.losses.deserialize(config) self.assertEqual(fn, new_fn) def test_categorical_hinge(self): y_pred = keras.backend.variable(np.array([[0.3, 0.2, 0.1], [0.1, 0.2, 0.7]])) y_true = keras.backend.variable(np.array([[0, 1, 0], [1, 0, 0]])) expected_loss = ((0.3 - 0.2 + 1) + (0.7 - 0.1 + 1)) / 2.0 loss = keras.backend.eval(keras.losses.categorical_hinge(y_true, y_pred)) self.assertAllClose(expected_loss, np.mean(loss)) def test_serializing_loss_class(self): orig_loss_class = _MSEMAELoss(0.3) with keras.utils.custom_object_scope({'_MSEMAELoss': _MSEMAELoss}): serialized = keras.losses.serialize(orig_loss_class) with keras.utils.custom_object_scope({'_MSEMAELoss': _MSEMAELoss}): deserialized = keras.losses.deserialize(serialized) assert isinstance(deserialized, _MSEMAELoss) assert deserialized.mse_fraction == 0.3 def test_serializing_model_with_loss_class(self): tmpdir = self.get_temp_dir() self.addCleanup(shutil.rmtree, tmpdir) model_filename = os.path.join(tmpdir, 'custom_loss.h5') with self.cached_session(): with keras.utils.custom_object_scope({'_MSEMAELoss': _MSEMAELoss}): loss = _MSEMAELoss(0.3) inputs = keras.layers.Input((2,)) outputs = keras.layers.Dense(1, name='model_output')(inputs) model = keras.models.Model(inputs, outputs) model.compile(optimizer='sgd', loss={'model_output': loss}) model.fit(np.random.rand(256, 2), np.random.rand(256, 1)) if h5py is None: return model.save(model_filename) with keras.utils.custom_object_scope({'_MSEMAELoss': _MSEMAELoss}): loaded_model = keras.models.load_model(model_filename) loaded_model.predict(np.random.rand(128, 2)) @test_util.run_all_in_graph_and_eager_modes class MeanSquaredErrorTest(test.TestCase): def test_config(self): mse_obj = keras.losses.MeanSquaredError( reduction=losses_impl.ReductionV2.SUM, name='mse_1') self.assertEqual(mse_obj.name, 'mse_1') self.assertEqual(mse_obj.reduction, losses_impl.ReductionV2.SUM) def test_all_correct_unweighted(self): mse_obj = keras.losses.MeanSquaredError() y_true = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3)) loss = mse_obj(y_true, y_true) self.assertAlmostEqual(self.evaluate(loss), 0.0, 3) def test_unweighted(self): mse_obj = keras.losses.MeanSquaredError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) loss = mse_obj(y_true, y_pred) self.assertAlmostEqual(self.evaluate(loss), 49.5, 3) def test_scalar_weighted(self): mse_obj = keras.losses.MeanSquaredError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) loss = mse_obj(y_true, y_pred, sample_weight=2.3) self.assertAlmostEqual(self.evaluate(loss), 113.85, 3) def test_sample_weighted(self): mse_obj = keras.losses.MeanSquaredError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) sample_weight = constant_op.constant([1.2, 3.4], shape=(2, 1)) loss = mse_obj(y_true, y_pred, sample_weight=sample_weight) self.assertAlmostEqual(self.evaluate(loss), 767.8 / 6, 3) def test_timestep_weighted(self): mse_obj = keras.losses.MeanSquaredError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3, 1)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3, 1), dtype=dtypes.float32) sample_weight = constant_op.constant([3, 6, 5, 0, 4, 2], shape=(2, 3)) loss = mse_obj(y_true, y_pred, sample_weight=sample_weight) self.assertAlmostEqual(self.evaluate(loss), 587 / 6, 3) def test_zero_weighted(self): mse_obj = keras.losses.MeanSquaredError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) loss = mse_obj(y_true, y_pred, sample_weight=0) self.assertAlmostEqual(self.evaluate(loss), 0.0, 3) def test_invalid_sample_weight(self): mse_obj = keras.losses.MeanSquaredError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3, 1)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3, 1)) sample_weight = constant_op.constant([3, 6, 5, 0], shape=(2, 2)) with self.assertRaisesRegexp( ValueError, r'Shapes \(2, 2\) and \(2, 3\) are incompatible'): mse_obj(y_true, y_pred, sample_weight=sample_weight) def test_no_reduction(self): mse_obj = keras.losses.MeanSquaredError( reduction=losses_impl.ReductionV2.NONE) y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) loss = mse_obj(y_true, y_pred, sample_weight=2.3) loss = self.evaluate(loss) self.assertArrayNear(loss, [84.3333, 143.3666], 1e-3) def test_sum_reduction(self): mse_obj = keras.losses.MeanSquaredError( reduction=losses_impl.ReductionV2.SUM) y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) loss = mse_obj(y_true, y_pred, sample_weight=2.3) self.assertAlmostEqual(self.evaluate(loss), 227.69998, 3) @test_util.run_all_in_graph_and_eager_modes class MeanAbsoluteErrorTest(test.TestCase): def test_config(self): mae_obj = keras.losses.MeanAbsoluteError( reduction=losses_impl.ReductionV2.SUM, name='mae_1') self.assertEqual(mae_obj.name, 'mae_1') self.assertEqual(mae_obj.reduction, losses_impl.ReductionV2.SUM) def test_all_correct_unweighted(self): mae_obj = keras.losses.MeanAbsoluteError() y_true = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3)) loss = mae_obj(y_true, y_true) self.assertAlmostEqual(self.evaluate(loss), 0.0, 3) def test_unweighted(self): mae_obj = keras.losses.MeanAbsoluteError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) loss = mae_obj(y_true, y_pred) self.assertAlmostEqual(self.evaluate(loss), 5.5, 3) def test_scalar_weighted(self): mae_obj = keras.losses.MeanAbsoluteError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) loss = mae_obj(y_true, y_pred, sample_weight=2.3) self.assertAlmostEqual(self.evaluate(loss), 12.65, 3) def test_sample_weighted(self): mae_obj = keras.losses.MeanAbsoluteError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) sample_weight = constant_op.constant([1.2, 3.4], shape=(2, 1)) loss = mae_obj(y_true, y_pred, sample_weight=sample_weight) self.assertAlmostEqual(self.evaluate(loss), 81.4 / 6, 3) def test_timestep_weighted(self): mae_obj = keras.losses.MeanAbsoluteError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3, 1)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3, 1), dtype=dtypes.float32) sample_weight = constant_op.constant([3, 6, 5, 0, 4, 2], shape=(2, 3)) loss = mae_obj(y_true, y_pred, sample_weight=sample_weight) self.assertAlmostEqual(self.evaluate(loss), 83 / 6, 3) def test_zero_weighted(self): mae_obj = keras.losses.MeanAbsoluteError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) loss = mae_obj(y_true, y_pred, sample_weight=0) self.assertAlmostEqual(self.evaluate(loss), 0.0, 3) def test_invalid_sample_weight(self): mae_obj = keras.losses.MeanAbsoluteError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3, 1)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3, 1)) sample_weight = constant_op.constant([3, 6, 5, 0], shape=(2, 2)) with self.assertRaisesRegexp( ValueError, r'Shapes \(2, 2\) and \(2, 3\) are incompatible'): mae_obj(y_true, y_pred, sample_weight=sample_weight) def test_no_reduction(self): mae_obj = keras.losses.MeanAbsoluteError( reduction=losses_impl.ReductionV2.NONE) y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) loss = mae_obj(y_true, y_pred, sample_weight=2.3) loss = self.evaluate(loss) self.assertArrayNear(loss, [10.7333, 14.5666], 1e-3) def test_sum_reduction(self): mae_obj = keras.losses.MeanAbsoluteError( reduction=losses_impl.ReductionV2.SUM) y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) loss = mae_obj(y_true, y_pred, sample_weight=2.3) self.assertAlmostEqual(self.evaluate(loss), 25.29999, 3) @test_util.run_all_in_graph_and_eager_modes class MeanAbsolutePercentageErrorTest(test.TestCase): def test_config(self): mape_obj = keras.losses.MeanAbsolutePercentageError( reduction=losses_impl.ReductionV2.SUM, name='mape_1') self.assertEqual(mape_obj.name, 'mape_1') self.assertEqual(mape_obj.reduction, losses_impl.ReductionV2.SUM) def test_unweighted(self): mape_obj = keras.losses.MeanAbsolutePercentageError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) loss = mape_obj(y_true, y_pred) self.assertAlmostEqual(self.evaluate(loss), 211.8518, 3) def test_scalar_weighted(self): mape_obj = keras.losses.MeanAbsolutePercentageError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) loss = mape_obj(y_true, y_pred, sample_weight=2.3) self.assertAlmostEqual(self.evaluate(loss), 487.259, 3) def test_sample_weighted(self): mape_obj = keras.losses.MeanAbsolutePercentageError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) sample_weight = constant_op.constant([1.2, 3.4], shape=(2, 1)) loss = mape_obj(y_true, y_pred, sample_weight=sample_weight) self.assertAlmostEqual(self.evaluate(loss), 422.8888, 3) def test_timestep_weighted(self): mape_obj = keras.losses.MeanAbsolutePercentageError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3, 1)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3, 1), dtype=dtypes.float32) sample_weight = constant_op.constant([3, 6, 5, 0, 4, 2], shape=(2, 3)) loss = mape_obj(y_true, y_pred, sample_weight=sample_weight) self.assertAlmostEqual(self.evaluate(loss), 694.4445, 3) def test_zero_weighted(self): mape_obj = keras.losses.MeanAbsolutePercentageError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) loss = mape_obj(y_true, y_pred, sample_weight=0) self.assertAlmostEqual(self.evaluate(loss), 0.0, 3) @test_util.run_all_in_graph_and_eager_modes class MeanSquaredLogarithmicErrorTest(test.TestCase): def test_config(self): msle_obj = keras.losses.MeanSquaredLogarithmicError( reduction=losses_impl.ReductionV2.SUM, name='mape_1') self.assertEqual(msle_obj.name, 'mape_1') self.assertEqual(msle_obj.reduction, losses_impl.ReductionV2.SUM) def test_unweighted(self): msle_obj = keras.losses.MeanSquaredLogarithmicError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) loss = msle_obj(y_true, y_pred) self.assertAlmostEqual(self.evaluate(loss), 1.4370, 3) def test_scalar_weighted(self): msle_obj = keras.losses.MeanSquaredLogarithmicError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) loss = msle_obj(y_true, y_pred, sample_weight=2.3) self.assertAlmostEqual(self.evaluate(loss), 3.3051, 3) def test_sample_weighted(self): msle_obj = keras.losses.MeanSquaredLogarithmicError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) sample_weight = constant_op.constant([1.2, 3.4], shape=(2, 1)) loss = msle_obj(y_true, y_pred, sample_weight=sample_weight) self.assertAlmostEqual(self.evaluate(loss), 3.7856, 3) def test_timestep_weighted(self): msle_obj = keras.losses.MeanSquaredLogarithmicError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3, 1)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3, 1), dtype=dtypes.float32) sample_weight = constant_op.constant([3, 6, 5, 0, 4, 2], shape=(2, 3)) loss = msle_obj(y_true, y_pred, sample_weight=sample_weight) self.assertAlmostEqual(self.evaluate(loss), 2.6473, 3) def test_zero_weighted(self): msle_obj = keras.losses.MeanSquaredLogarithmicError() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) loss = msle_obj(y_true, y_pred, sample_weight=0) self.assertAlmostEqual(self.evaluate(loss), 0.0, 3) @test_util.run_all_in_graph_and_eager_modes class CosineProximityTest(test.TestCase): def test_config(self): cosine_obj = keras.losses.CosineProximity( reduction=losses_impl.ReductionV2.SUM, name='cosine_loss') self.assertEqual(cosine_obj.name, 'cosine_loss') self.assertEqual(cosine_obj.reduction, losses_impl.ReductionV2.SUM) def test_unweighted(self): cosine_obj = keras.losses.CosineProximity() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) loss = cosine_obj(y_true, y_pred) self.assertAlmostEqual(self.evaluate(loss), -0.18722, 3) def test_scalar_weighted(self): cosine_obj = keras.losses.CosineProximity() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) loss = cosine_obj(y_true, y_pred, sample_weight=2.3) self.assertAlmostEqual(self.evaluate(loss), -0.43060, 3) def test_sample_weighted(self): cosine_obj = keras.losses.CosineProximity() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) sample_weight = constant_op.constant([1.2, 3.4], shape=(2, 1)) loss = cosine_obj(y_true, y_pred, sample_weight=sample_weight) self.assertAlmostEqual(self.evaluate(loss), 0.15599, 3) def test_timestep_weighted(self): cosine_obj = keras.losses.CosineProximity() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3, 1)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3, 1), dtype=dtypes.float32) sample_weight = constant_op.constant([3, 6, 5, 0, 4, 2], shape=(2, 3)) loss = cosine_obj(y_true, y_pred, sample_weight=sample_weight) self.assertAlmostEqual(self.evaluate(loss), -2.0000, 3) def test_zero_weighted(self): cosine_obj = keras.losses.CosineProximity() y_true = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3)) y_pred = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3), dtype=dtypes.float32) loss = cosine_obj(y_true, y_pred, sample_weight=0) self.assertAlmostEqual(self.evaluate(loss), 0., 3) @test_util.run_all_in_graph_and_eager_modes class BinaryCrossentropyTest(test.TestCase): def test_config(self): bce_obj = keras.losses.BinaryCrossentropy( reduction=losses_impl.ReductionV2.SUM, name='bce_1') self.assertEqual(bce_obj.name, 'bce_1') self.assertEqual(bce_obj.reduction, losses_impl.ReductionV2.SUM) def test_all_correct_unweighted(self): y_true = constant_op.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=dtypes.float32) bce_obj = keras.losses.BinaryCrossentropy() loss = bce_obj(y_true, y_true) self.assertAlmostEqual(self.evaluate(loss), 0.0, 3) # Test with logits. logits = constant_op.constant([[100.0, -100.0, -100.0], [-100.0, 100.0, -100.0], [-100.0, -100.0, 100.0]]) bce_obj = keras.losses.BinaryCrossentropy(from_logits=True) loss = bce_obj(y_true, logits) self.assertAlmostEqual(self.evaluate(loss), 0.0, 3) def test_unweighted(self): bce_obj = keras.losses.BinaryCrossentropy() y_true = constant_op.constant([1, 0, 1, 0, 0, 1], shape=(2, 3)) y_pred = constant_op.constant([1, 1, 1, 0, 1, 0], shape=(2, 3), dtype=dtypes.float32) loss = bce_obj(y_true, y_pred) self.assertAlmostEqual(self.evaluate(loss), 8.0004, 3) # Test with logits. logits = constant_op.constant([10., 10., 10., -10., 10, -10], shape=(2, 3), dtype=dtypes.float32) bce_obj = keras.losses.BinaryCrossentropy(from_logits=True) loss = bce_obj(y_true, logits) self.assertAlmostEqual(self.evaluate(loss), 5., 3) def test_scalar_weighted(self): bce_obj = keras.losses.BinaryCrossentropy() y_true = constant_op.constant([1, 0, 1, 0, 0, 1], shape=(2, 3)) y_pred = constant_op.constant([1, 1, 1, 0, 1, 0], shape=(2, 3), dtype=dtypes.float32) loss = bce_obj(y_true, y_pred, sample_weight=2.3) self.assertAlmostEqual(self.evaluate(loss), 18.4010, 3) # Test with logits. y_true = array_ops.ones((32, 1)) logits = array_ops.ones((32, 1), dtype=dtypes.float32) bce_obj = keras.losses.BinaryCrossentropy(from_logits=True) loss = bce_obj(y_true, logits, sample_weight=2.3) self.assertAlmostEqual(self.evaluate(loss), 0.7205, 3) def test_sample_weighted(self): bce_obj = keras.losses.BinaryCrossentropy() y_true = constant_op.constant([1, 0, 1, 0, 0, 1], shape=(2, 3)) y_pred = constant_op.constant([1, 1, 1, 0, 1, 0], shape=(2, 3), dtype=dtypes.float64) sample_weight = constant_op.constant([1.2, 3.4], shape=(2, 1)) loss = bce_obj(y_true, y_pred, sample_weight=sample_weight) self.assertAlmostEqual(self.evaluate(loss), 21.4907, 3) # Test with logits. y_true = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]]) logits = constant_op.constant( [[100.0, -100.0, -100.0], [-100.0, 100.0, -100.0], [-100.0, -100.0, 100.0]], dtype=dtypes.float64) weights = constant_op.constant([3, 2, 8]) bce_obj = keras.losses.BinaryCrossentropy(from_logits=True) loss = bce_obj(y_true, logits, sample_weight=weights) self.assertAlmostEqual(self.evaluate(loss), 288.8888, 3) def test_no_reduction(self): y_true = constant_op.constant(((1, 0, 1), (1, 1, 0), (0, 1, 1))) logits = constant_op.constant(((100.0, -100.0, 100.0), (100.0, -100.0, 100.0), (100.0, 100.0, -100.0))) bce_obj = keras.losses.BinaryCrossentropy( from_logits=True, reduction=losses_impl.ReductionV2.NONE) loss = bce_obj(y_true, logits) self.assertAllClose((0., 66.6666, 66.6666), self.evaluate(loss), 3) def test_label_smoothing(self): logits = constant_op.constant([[100.0, -100.0, -100.0]]) y_true = constant_op.constant([[1, 0, 1]]) label_smoothing = 0.1 # Loss: max(x, 0) - x * z + log(1 + exp(-abs(x))) # Label smoothing: z' = z * (1 - L) + 0.5L # 1 = 1 - 0.5L # 0 = 0.5L # Applying the above two fns to the given input: # (100 - 100 * (1 - 0.5 L) + 0 + # 0 + 100 * (0.5 L) + 0 + # 0 + 100 * (1 - 0.5 L) + 0) * (1/3) # = (100 + 50L) * 1/3 bce_obj = keras.losses.BinaryCrossentropy( from_logits=True, label_smoothing=label_smoothing) loss = bce_obj(y_true, logits) expected_value = (100.0 + 50.0 * label_smoothing) / 3.0 self.assertAlmostEqual(self.evaluate(loss), expected_value, 3) @test_util.run_all_in_graph_and_eager_modes class CategoricalCrossentropyTest(test.TestCase): def test_config(self): cce_obj = keras.losses.CategoricalCrossentropy( reduction=losses_impl.ReductionV2.SUM, name='bce_1') self.assertEqual(cce_obj.name, 'bce_1') self.assertEqual(cce_obj.reduction, losses_impl.ReductionV2.SUM) def test_all_correct_unweighted(self): y_true = constant_op.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=dtypes.int64) y_pred = constant_op.constant([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]], dtype=dtypes.float32) cce_obj = keras.losses.CategoricalCrossentropy() loss = cce_obj(y_true, y_pred) self.assertAlmostEqual(self.evaluate(loss), 0.0, 3) # Test with logits. logits = constant_op.constant([[10., 0., 0.], [0., 10., 0.], [0., 0., 10.]]) cce_obj = keras.losses.CategoricalCrossentropy(from_logits=True) loss = cce_obj(y_true, logits) self.assertAlmostEqual(self.evaluate(loss), 0.0, 3) def test_unweighted(self): cce_obj = keras.losses.CategoricalCrossentropy() y_true = constant_op.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) y_pred = constant_op.constant( [[.9, .05, .05], [.5, .89, .6], [.05, .01, .94]], dtype=dtypes.float32) loss = cce_obj(y_true, y_pred) self.assertAlmostEqual(self.evaluate(loss), .3239, 3) # Test with logits. logits = constant_op.constant([[8., 1., 1.], [0., 9., 1.], [2., 3., 5.]]) cce_obj = keras.losses.CategoricalCrossentropy(from_logits=True) loss = cce_obj(y_true, logits) self.assertAlmostEqual(self.evaluate(loss), .0573, 3) def test_scalar_weighted(self): cce_obj = keras.losses.CategoricalCrossentropy() y_true = constant_op.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) y_pred = constant_op.constant( [[.9, .05, .05], [.5, .89, .6], [.05, .01, .94]], dtype=dtypes.float32) loss = cce_obj(y_true, y_pred, sample_weight=2.3) self.assertAlmostEqual(self.evaluate(loss), .7449, 3) # Test with logits. logits = constant_op.constant([[8., 1., 1.], [0., 9., 1.], [2., 3., 5.]]) cce_obj = keras.losses.CategoricalCrossentropy(from_logits=True) loss = cce_obj(y_true, logits, sample_weight=2.3) self.assertAlmostEqual(self.evaluate(loss), .1317, 3) def test_sample_weighted(self): cce_obj = keras.losses.CategoricalCrossentropy() y_true = constant_op.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) y_pred = constant_op.constant( [[.9, .05, .05], [.5, .89, .6], [.05, .01, .94]], dtype=dtypes.float32) sample_weight = constant_op.constant([[1.2], [3.4], [5.6]], shape=(3, 1)) loss = cce_obj(y_true, y_pred, sample_weight=sample_weight) self.assertAlmostEqual(self.evaluate(loss), 1.0696, 3) # Test with logits. logits = constant_op.constant([[8., 1., 1.], [0., 9., 1.], [2., 3., 5.]]) cce_obj = keras.losses.CategoricalCrossentropy(from_logits=True) loss = cce_obj(y_true, logits, sample_weight=sample_weight) self.assertAlmostEqual(self.evaluate(loss), 0.31829, 3) def test_no_reduction(self): y_true = constant_op.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) logits = constant_op.constant([[8., 1., 1.], [0., 9., 1.], [2., 3., 5.]]) cce_obj = keras.losses.CategoricalCrossentropy( from_logits=True, reduction=losses_impl.ReductionV2.NONE) loss = cce_obj(y_true, logits) self.assertAllClose((0.001822, 0.000459, 0.169846), self.evaluate(loss), 3) def test_label_smoothing(self): logits = constant_op.constant([[100.0, -100.0, -100.0]]) y_true = constant_op.constant([[1, 0, 0]]) label_smoothing = 0.1 # Softmax Cross Entropy Loss: -\sum_i p_i \log q_i # where for a softmax activation # \log q_i = x_i - \log \sum_j \exp x_j # = x_i - x_max - \log \sum_j \exp (x_j - x_max) # For our activations, [100, -100, -100] # \log ( exp(0) + exp(-200) + exp(-200) ) = 0 # so our log softmaxes become: [0, -200, -200] # Label smoothing: z' = z * (1 - L) + L/n # 1 = 1 - L + L/n # 0 = L/n # Applying the above two fns to the given input: # -0 * (1 - L + L/n) + 200 * L/n + 200 * L/n = 400 L/n cce_obj = keras.losses.CategoricalCrossentropy( from_logits=True, label_smoothing=label_smoothing) loss = cce_obj(y_true, logits) expected_value = 400.0 * label_smoothing / 3.0 self.assertAlmostEqual(self.evaluate(loss), expected_value, 3) def test_all_correct_unweighted_sparse(self): y_true = constant_op.constant([[0], [1], [2]], dtype=dtypes.int64) y_pred = constant_op.constant([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]], dtype=dtypes.float32) cce_obj = keras.losses.CategoricalCrossentropy() loss = cce_obj(y_true, y_pred) self.assertAlmostEqual(self.evaluate(loss), 0.0, 3) # Test with logits. logits = constant_op.constant([[10., 0., 0.], [0., 10., 0.], [0., 0., 10.]]) cce_obj = keras.losses.CategoricalCrossentropy(from_logits=True) loss = cce_obj(y_true, logits) self.assertAlmostEqual(self.evaluate(loss), 0.0, 3) def test_unweighted_sparse(self): cce_obj = keras.losses.CategoricalCrossentropy() y_true = constant_op.constant([0, 1, 2]) y_pred = constant_op.constant( [[.9, .05, .05], [.5, .89, .6], [.05, .01, .94]], dtype=dtypes.float32) loss = cce_obj(y_true, y_pred) self.assertAlmostEqual(self.evaluate(loss), .3239, 3) # Test with logits. logits = constant_op.constant([[8., 1., 1.], [0., 9., 1.], [2., 3., 5.]]) cce_obj = keras.losses.CategoricalCrossentropy(from_logits=True) loss = cce_obj(y_true, logits) self.assertAlmostEqual(self.evaluate(loss), .0573, 3) def test_scalar_weighted_sparse(self): cce_obj = keras.losses.CategoricalCrossentropy() y_true = constant_op.constant([[0], [1], [2]]) y_pred = constant_op.constant( [[.9, .05, .05], [.5, .89, .6], [.05, .01, .94]], dtype=dtypes.float32) loss = cce_obj(y_true, y_pred, sample_weight=2.3) self.assertAlmostEqual(self.evaluate(loss), .7449, 3) # Test with logits. logits = constant_op.constant([[8., 1., 1.], [0., 9., 1.], [2., 3., 5.]]) cce_obj = keras.losses.CategoricalCrossentropy(from_logits=True) loss = cce_obj(y_true, logits, sample_weight=2.3) self.assertAlmostEqual(self.evaluate(loss), .1317, 3) def test_sample_weighted_sparse(self): cce_obj = keras.losses.CategoricalCrossentropy() y_true = constant_op.constant([[0], [1], [2]]) y_pred = constant_op.constant( [[.9, .05, .05], [.5, .89, .6], [.05, .01, .94]], dtype=dtypes.float32) sample_weight = constant_op.constant([[1.2], [3.4], [5.6]], shape=(3, 1)) loss = cce_obj(y_true, y_pred, sample_weight=sample_weight) self.assertAlmostEqual(self.evaluate(loss), 1.0696, 3) # Test with logits. logits = constant_op.constant([[8., 1., 1.], [0., 9., 1.], [2., 3., 5.]]) cce_obj = keras.losses.CategoricalCrossentropy(from_logits=True) loss = cce_obj(y_true, logits, sample_weight=sample_weight) self.assertAlmostEqual(self.evaluate(loss), 0.31829, 3) def test_no_reduction_sparse(self): y_true = constant_op.constant([[0], [1], [2]]) logits = constant_op.constant([[8., 1., 1.], [0., 9., 1.], [2., 3., 5.]]) cce_obj = keras.losses.CategoricalCrossentropy( from_logits=True, reduction=losses_impl.ReductionV2.NONE) loss = cce_obj(y_true, logits) self.assertAllClose((0.001822, 0.000459, 0.169846), self.evaluate(loss), 3) if __name__ == '__main__': test.main()
import os import sys from typing import List, Optional import log from datafiles import datafile, field from .. import common, exceptions, shell from ..decorators import preserve_cwd from .group import Group from .source import Source, create_sym_link # TODO remove the next pylint statement and adapt code # disable because of the dynamics setattr in __post_init__ to avoid # that datafile persist this values -> is there another way to tell # datafiles to ignore specified fiels # pylint: disable=attribute-defined-outside-init, access-member-before-definition # due to the protected access of _get_sources -> make them public in the next step # pylint: disable=protected-access @datafile("{self.root}/{self.filename}", defaults=True, manual=True) class Config: RESOLVER_RECURSIVE_NESTED = "recursive-nested" RESOLVER_RECURSIVE_FLAT = "recursive-flat" RESOLVER_RECURSIVE_FLAT_NESTED_LINKS = "recursive-flat-nested-links" RESOLVER_FLAT = "flat" """Specifies all dependencies for a project.""" root: Optional[str] = None filename: str = "gitman.yml" location: str = "gitman_sources" resolver: str = RESOLVER_RECURSIVE_NESTED sources: List[Source] = field(default_factory=list) sources_locked: List[Source] = field(default_factory=list) default_group: str = field(default_factory=str) groups: List[Group] = field(default_factory=list) def __post_init__(self): if self.root is None: self.root = os.getcwd() # used only internally and should not be serialized location_path = os.path.normpath(os.path.join(self.root, self.location)) setattr(self, 'location_path', location_path) processed_sources: List[Source] = [] setattr(self, 'processed_sources', processed_sources) registered_sources: List[Source] = [] setattr(self, 'registered_sources', registered_sources) # check if any of the valid resolver values is set # if not then set RESOLVER_RECURSIVE_NESTED as default if ( self.resolver != Config.RESOLVER_RECURSIVE_NESTED and self.resolver != Config.RESOLVER_RECURSIVE_FLAT and self.resolver != Config.RESOLVER_RECURSIVE_FLAT_NESTED_LINKS and self.resolver != Config.RESOLVER_FLAT ): msg = "Unknown resolver name \"{}\"".format(self.resolver) raise exceptions.InvalidConfig(msg) def __post_load__(self): # update location path because default location may different then loaded value self.location_path = os.path.normpath( os.path.join(self.root, self.location) # type: ignore[arg-type] ) @property def config_path(self) -> str: """Get the full path to the config file.""" assert self.root return os.path.normpath( os.path.join(self.root, self.filename) # type: ignore[arg-type] ) path = config_path @property def log_path(self) -> str: """Get the full path to the log file.""" return os.path.normpath(os.path.join(self.location_path, "gitman.log")) def validate(self): """Check for conflicts between source names and group names.""" for source in self.sources: for group in self.groups: if source.name == group.name: msg = ( "Name conflict detected between source name and " "group name \"{}\"" ).format(source.name) raise exceptions.InvalidConfig(msg) def get_path(self, name=None): """Get the full path to a dependency or internal file.""" base = self.location_path if name == '__config__': return self.path if name == '__log__': return self.log_path if name: return os.path.normpath(os.path.join(base, name)) return base def install_dependencies( self, *names, depth=None, update=True, recurse=False, force=False, force_interactive=False, fetch=False, clean=True, skip_changes=False, skip_default_group=False, ): # pylint: disable=too-many-locals, too-many-statements """Download or update the specified dependencies.""" if depth == 0: log.info("Skipped directory: %s", self.location_path) return 0 sources = None sources_filter = None if ( # pylint: disable=too-many-nested-blocks self.resolver == Config.RESOLVER_RECURSIVE_FLAT or self.resolver == Config.RESOLVER_RECURSIVE_FLAT_NESTED_LINKS ): sources = self._get_sources( use_locked=False if update else None, use_extra=False ) sources_filter = self._get_sources_filter( *names, sources=sources, skip_default_group=skip_default_group ) # gather flat sources and check for rev conflicts new_sources: List[Source] = [] for source in sources: add_source: bool = True for registered_source in self.registered_sources: # type: ignore if ( source.name == registered_source.name ): # check if current source was already processed if ( source.rev != registered_source.rev or source.repo != registered_source.repo ): # we skip the detected recursed branch rev if we install # locked sources always the toplevel rev is leading and # to ensure creation order we process the locked version # next instead of the noted rev if not update: # check if we have already processed the matched source # pylint: disable=line-too-long if not registered_source in self.processed_sources: # type: ignore new_sources.append(registered_source) else: # already processed therefore we don't care anymore sources_filter.remove(source.name) add_source = False continue error_msg = ( "Repo/rev conflict encountered in " "flat hierarchy while updating {}\n" "Details: {} conflict with {}" ).format(self.root, str(registered_source), str(source)) raise exceptions.InvalidConfig(error_msg) # new source name detected -> store new source name # to list (cache) used to check for rev conflicts if add_source: self.registered_sources.append(source) # type: ignore new_sources.append(source) # assign filtered and collected sources sources = new_sources else: sources = self._get_sources(use_locked=False if update else None) sources_filter = self._get_sources_filter( *names, sources=sources, skip_default_group=skip_default_group ) for source in sources: for registered_source in self.registered_sources: # type: ignore if ( source.name == registered_source.name ): # check if current source was already processed error_msg = ( "Repo conflict encountered " "while updating {}\n" "Details: {} conflict with {}" ).format(self.root, str(registered_source), str(source)) raise exceptions.InvalidConfig(error_msg) self.registered_sources.append(source) # type: ignore if not os.path.isdir(self.location_path): shell.mkdir(self.location_path) shell.cd(self.location_path) common.newline() common.indent() count = 0 for source in sources: if source.name in sources_filter: sources_filter.remove(source.name) else: log.info("Skipped dependency: %s", source.name) continue # check if source has not already been processed if source in self.processed_sources: # type: ignore continue source.update_files( force=force, force_interactive=force_interactive, fetch=fetch, clean=clean, skip_changes=skip_changes, ) source.create_links(self.root, force=force) # store processed source self.processed_sources.append(source) # type: ignore common.newline() count += 1 if self.resolver == Config.RESOLVER_FLAT: # don't process nested configs if flat resolver is active continue config = load_config(search=False) if config: common.indent() if ( self.resolver == Config.RESOLVER_RECURSIVE_FLAT or self.resolver == Config.RESOLVER_RECURSIVE_FLAT_NESTED_LINKS ): # Top level preference for flat hierarchy should # forward / propagate resolver settings config.resolver = self.resolver # forward / override default location -> always use root location # to install dependencies all into the same folder org_location_path = config.location_path config.location_path = self.location_path # forward registered and processed sources list to # check for global conflicts config.registered_sources = self.registered_sources # type: ignore config.processed_sources = self.processed_sources # type: ignore count += config.install_dependencies( depth=None if depth is None else max(0, depth - 1), update=update and recurse, recurse=recurse, force=force, fetch=fetch, clean=clean, skip_changes=skip_changes, skip_default_group=skip_default_group, ) # create nested symlinks if self.resolver == Config.RESOLVER_RECURSIVE_FLAT_NESTED_LINKS: for src in config.sources: link_src = os.path.join(self.location_path, src.name) link_target = os.path.join(org_location_path, src.name) create_sym_link(link_src, link_target, True) common.dedent() shell.cd(self.location_path, _show=False) common.dedent() if sources_filter: log.error("No such dependency: %s", ' '.join(sources_filter)) return 0 return count @preserve_cwd def run_scripts(self, *names, depth=None, force=False, show_shell_stdout=False): """Run scripts for the specified dependencies.""" if depth == 0: log.info("Skipped directory: %s", self.location_path) return 0 sources = self._get_sources() sources_filter = self._get_sources_filter( *names, sources=sources, skip_default_group=False ) shell.cd(self.location_path) common.newline() common.indent() count = 0 for source in sources: if source.name in sources_filter: shell.cd(source.name) if self.resolver == Config.RESOLVER_FLAT: # don't process nested configs if flat resolver is active continue config = load_config(search=False) if config: common.indent() remaining_depth = None if depth is None else max(0, depth - 1) if remaining_depth: common.newline() if ( self.resolver == Config.RESOLVER_RECURSIVE_FLAT or self.resolver == Config.RESOLVER_RECURSIVE_FLAT_NESTED_LINKS ): # Top level preference for flat hierarchy should # always propagate resolver settings config.resolver = self.resolver # override default location -> always use root location # to install dependencies all into the same folder config.location_path = self.location_path # forward processed sources list to check for global conflicts # pylint: disable=line-too-long config.processed_sources = self.processed_sources # type: ignore count += config.run_scripts(depth=remaining_depth, force=force) common.dedent() source.run_scripts(force=force, show_shell_stdout=show_shell_stdout) count += 1 shell.cd(self.location_path, _show=False) common.dedent() return count def lock_dependencies(self, *names, obey_existing=True, skip_changes=False): """Lock down the immediate dependency versions.""" recursive = ( self.resolver == Config.RESOLVER_RECURSIVE_FLAT or self.resolver == Config.RESOLVER_RECURSIVE_FLAT_NESTED_LINKS ) sources = self._get_sources( use_locked=obey_existing, recursive=recursive ).copy() sources_filter = self._get_sources_filter( *names, sources=sources, skip_default_group=False ) if not os.path.isdir(self.location_path): raise exceptions.InvalidRepository("No dependencies resolved") shell.cd(self.location_path) common.newline() common.indent() count = 0 for source in sources: if source.name not in sources_filter: log.info("Skipped dependency: %s", source.name) continue source_locked = source.lock(skip_changes=skip_changes) if source_locked is not None: try: index = self.sources_locked.index(source) except ValueError: self.sources_locked.append(source_locked) else: self.sources_locked[index] = source_locked count += 1 shell.cd(self.location_path, _show=False) if count: self.datafile.save() common.dedent() return count def uninstall_dependencies(self): """Delete the dependency storage location.""" shell.cd(self.root) shell.rm(self.location_path) common.newline() def clean_dependencies(self): """Delete the dependency storage location.""" for path in self.get_top_level_dependencies(): if path == self.location_path: log.info("Skipped dependency: %s", path) else: shell.rm(path) common.newline() shell.rm(self.log_path) def get_top_level_dependencies(self): """Yield the path, repository, and hash of top-level dependencies.""" if not os.path.exists(self.location_path): return shell.cd(self.location_path) common.newline() common.indent() for source in self.sources: assert source.name yield os.path.join(self.location_path, source.name) shell.cd(self.location_path, _show=False) common.dedent() def get_dependencies(self, depth=None, allow_dirty=True): """Yield the path, repository, and hash of each dependency.""" if not os.path.exists(self.location_path): return shell.cd(self.location_path) common.newline() common.indent() for source in self.sources: if depth == 0: log.info("Skipped dependency: %s", source.name) continue yield source.identify(allow_dirty=allow_dirty) config = load_config(search=False) if config: common.indent() yield from config.get_dependencies( depth=None if depth is None else max(0, depth - 1), allow_dirty=allow_dirty, ) common.dedent() shell.cd(self.location_path, _show=False) common.dedent() def log(self, message="", *args): """Append a message to the log file.""" os.makedirs(self.location_path, exist_ok=True) with open(self.log_path, 'a') as outfile: outfile.write(message.format(*args) + '\n') def _get_sources(self, *, use_locked=None, use_extra=True, recursive=False): """Merge source lists using the requested section as the base.""" if use_locked is True: if self.sources_locked: return self.sources_locked log.info("No locked sources, defaulting to none...") return [] sources: List[Source] = [] if use_locked is False: sources = self.sources else: if self.sources_locked: log.info("Defaulting to locked sources...") sources = self.sources_locked else: log.info("No locked sources, using latest...") sources = self.sources extras = [] if recursive: recursive_sources = sources for source in sources: config_path = os.path.join( self.location_path, source.name # type: ignore[arg-type] ) config = load_config(start=config_path, search=False) if config: recursive_sources = recursive_sources + config._get_sources( use_locked=use_locked, use_extra=False, recursive=True ) for source in recursive_sources: if source not in sources: extras.append(source) if use_extra: all_sources = self.sources + self.sources_locked for source in all_sources: if source not in sources: log.info("Source %r missing from selected section", source.name) extras.append(source) return sources + extras def _get_sources_filter(self, *names, sources, skip_default_group): """Get filtered sublist of sources.""" names_list = list(names) if not names_list and not skip_default_group: names_list.append(self.default_group) # Add sources from groups groups_filter = [group for group in self.groups if group.name in names_list] sources_filter = [member for group in groups_filter for member in group.members] # Add independent sources sources_filter.extend( [source.name for source in sources if source.name in names_list] ) if not sources_filter: sources_filter = [source.name for source in sources] return list(set(sources_filter)) def load_config(start=None, *, search=True): """Load the config for the current project.""" start = os.path.abspath(start) if start else _resolve_current_directory() if search: log.debug("Searching for config...") path = start while path != os.path.dirname(path): log.debug("Looking for config in: %s", path) for filename in os.listdir(path): if _valid_filename(filename): config = Config(path, filename) config.__post_load__() config.validate() log.debug("Found config: %s", config.path) return config if search: path = os.path.dirname(path) else: break if search: log.debug("No config found starting from: %s", start) else: log.debug("No config found in: %s", start) return None def _resolve_current_directory(): start = os.getcwd() if sys.version_info < (3, 8) and os.name == "nt": log.warn("Python 3.8+ is required to resolve virtual drives on Windows") else: start = os.path.realpath(start) os.chdir(start) return start def _valid_filename(filename): name, ext = os.path.splitext(filename.lower()) if name.startswith('.'): name = name[1:] return name in {'gitman', 'gdm'} and ext in {'.yml', '.yaml'}
# Copyright 2011 OpenStack LLC. # 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 dealing with HTTP rate-limiting. """ import httplib import json import StringIO import unittest from xml.dom import minidom from lxml import etree import stubout import webob from nova.api.openstack.compute import limits from nova.api.openstack.compute import views from nova.api.openstack import wsgi from nova.api.openstack import xmlutil import nova.context from nova import test TEST_LIMITS = [ limits.Limit("GET", "/delayed", "^/delayed", 1, limits.PER_MINUTE), limits.Limit("POST", "*", ".*", 7, limits.PER_MINUTE), limits.Limit("POST", "/servers", "^/servers", 3, limits.PER_MINUTE), limits.Limit("PUT", "*", "", 10, limits.PER_MINUTE), limits.Limit("PUT", "/servers", "^/servers", 5, limits.PER_MINUTE), ] NS = { 'atom': 'http://www.w3.org/2005/Atom', 'ns': 'http://docs.openstack.org/common/api/v1.0' } class BaseLimitTestSuite(test.TestCase): """Base test suite which provides relevant stubs and time abstraction.""" def setUp(self): super(BaseLimitTestSuite, self).setUp() self.time = 0.0 self.stubs.Set(limits.Limit, "_get_time", self._get_time) self.absolute_limits = {} def stub_get_project_quotas(context, project_id): return self.absolute_limits self.stubs.Set(nova.quota, "get_project_quotas", stub_get_project_quotas) def _get_time(self): """Return the "time" according to this test suite.""" return self.time class LimitsControllerTest(BaseLimitTestSuite): """ Tests for `limits.LimitsController` class. """ def setUp(self): """Run before each test.""" super(LimitsControllerTest, self).setUp() self.controller = limits.create_resource() def _get_index_request(self, accept_header="application/json"): """Helper to set routing arguments.""" request = webob.Request.blank("/") request.accept = accept_header request.environ["wsgiorg.routing_args"] = (None, { "action": "index", "controller": "", }) context = nova.context.RequestContext('testuser', 'testproject') request.environ["nova.context"] = context return request def _populate_limits(self, request): """Put limit info into a request.""" _limits = [ limits.Limit("GET", "*", ".*", 10, 60).display(), limits.Limit("POST", "*", ".*", 5, 60 * 60).display(), limits.Limit("GET", "changes-since*", "changes-since", 5, 60).display(), ] request.environ["nova.limits"] = _limits return request def test_empty_index_json(self): """Test getting empty limit details in JSON.""" request = self._get_index_request() response = request.get_response(self.controller) expected = { "limits": { "rate": [], "absolute": {}, }, } body = json.loads(response.body) self.assertEqual(expected, body) def test_index_json(self): """Test getting limit details in JSON.""" request = self._get_index_request() request = self._populate_limits(request) self.absolute_limits = { 'ram': 512, 'instances': 5, 'cores': 21, } response = request.get_response(self.controller) expected = { "limits": { "rate": [ { "regex": ".*", "uri": "*", "limit": [ { "verb": "GET", "next-available": "1970-01-01T00:00:00Z", "unit": "MINUTE", "value": 10, "remaining": 10, }, { "verb": "POST", "next-available": "1970-01-01T00:00:00Z", "unit": "HOUR", "value": 5, "remaining": 5, }, ], }, { "regex": "changes-since", "uri": "changes-since*", "limit": [ { "verb": "GET", "next-available": "1970-01-01T00:00:00Z", "unit": "MINUTE", "value": 5, "remaining": 5, }, ], }, ], "absolute": { "maxTotalRAMSize": 512, "maxTotalInstances": 5, "maxTotalCores": 21, }, }, } body = json.loads(response.body) self.assertEqual(expected, body) def _populate_limits_diff_regex(self, request): """Put limit info into a request.""" _limits = [ limits.Limit("GET", "*", ".*", 10, 60).display(), limits.Limit("GET", "*", "*.*", 10, 60).display(), ] request.environ["nova.limits"] = _limits return request def test_index_diff_regex(self): """Test getting limit details in JSON.""" request = self._get_index_request() request = self._populate_limits_diff_regex(request) response = request.get_response(self.controller) expected = { "limits": { "rate": [ { "regex": ".*", "uri": "*", "limit": [ { "verb": "GET", "next-available": "1970-01-01T00:00:00Z", "unit": "MINUTE", "value": 10, "remaining": 10, }, ], }, { "regex": "*.*", "uri": "*", "limit": [ { "verb": "GET", "next-available": "1970-01-01T00:00:00Z", "unit": "MINUTE", "value": 10, "remaining": 10, }, ], }, ], "absolute": {}, }, } body = json.loads(response.body) self.assertEqual(expected, body) def _test_index_absolute_limits_json(self, expected): request = self._get_index_request() response = request.get_response(self.controller) body = json.loads(response.body) self.assertEqual(expected, body['limits']['absolute']) def test_index_ignores_extra_absolute_limits_json(self): self.absolute_limits = {'unknown_limit': 9001} self._test_index_absolute_limits_json({}) def test_index_absolute_ram_json(self): self.absolute_limits = {'ram': 1024} self._test_index_absolute_limits_json({'maxTotalRAMSize': 1024}) def test_index_absolute_cores_json(self): self.absolute_limits = {'cores': 17} self._test_index_absolute_limits_json({'maxTotalCores': 17}) def test_index_absolute_instances_json(self): self.absolute_limits = {'instances': 19} self._test_index_absolute_limits_json({'maxTotalInstances': 19}) def test_index_absolute_metadata_json(self): # NOTE: both server metadata and image metadata are overloaded # into metadata_items self.absolute_limits = {'metadata_items': 23} expected = { 'maxServerMeta': 23, 'maxImageMeta': 23, } self._test_index_absolute_limits_json(expected) def test_index_absolute_injected_files(self): self.absolute_limits = { 'injected_files': 17, 'injected_file_content_bytes': 86753, } expected = { 'maxPersonality': 17, 'maxPersonalitySize': 86753, } self._test_index_absolute_limits_json(expected) class TestLimiter(limits.Limiter): pass class LimitMiddlewareTest(BaseLimitTestSuite): """ Tests for the `limits.RateLimitingMiddleware` class. """ @webob.dec.wsgify def _empty_app(self, request): """Do-nothing WSGI app.""" pass def setUp(self): """Prepare middleware for use through fake WSGI app.""" super(LimitMiddlewareTest, self).setUp() _limits = '(GET, *, .*, 1, MINUTE)' self.app = limits.RateLimitingMiddleware(self._empty_app, _limits, "%s.TestLimiter" % self.__class__.__module__) def test_limit_class(self): """Test that middleware selected correct limiter class.""" assert isinstance(self.app._limiter, TestLimiter) def test_good_request(self): """Test successful GET request through middleware.""" request = webob.Request.blank("/") response = request.get_response(self.app) self.assertEqual(200, response.status_int) def test_limited_request_json(self): """Test a rate-limited (413) GET request through middleware.""" request = webob.Request.blank("/") response = request.get_response(self.app) self.assertEqual(200, response.status_int) request = webob.Request.blank("/") response = request.get_response(self.app) self.assertEqual(response.status_int, 413) self.assertTrue('Retry-After' in response.headers) retry_after = int(response.headers['Retry-After']) self.assertAlmostEqual(retry_after, 60, 1) body = json.loads(response.body) expected = "Only 1 GET request(s) can be made to * every minute." value = body["overLimitFault"]["details"].strip() self.assertEqual(value, expected) def test_limited_request_xml(self): """Test a rate-limited (413) response as XML""" request = webob.Request.blank("/") response = request.get_response(self.app) self.assertEqual(200, response.status_int) request = webob.Request.blank("/") request.accept = "application/xml" response = request.get_response(self.app) self.assertEqual(response.status_int, 413) root = minidom.parseString(response.body).childNodes[0] expected = "Only 1 GET request(s) can be made to * every minute." details = root.getElementsByTagName("details") self.assertEqual(details.length, 1) value = details.item(0).firstChild.data.strip() self.assertEqual(value, expected) class LimitTest(BaseLimitTestSuite): """ Tests for the `limits.Limit` class. """ def test_GET_no_delay(self): """Test a limit handles 1 GET per second.""" limit = limits.Limit("GET", "*", ".*", 1, 1) delay = limit("GET", "/anything") self.assertEqual(None, delay) self.assertEqual(0, limit.next_request) self.assertEqual(0, limit.last_request) def test_GET_delay(self): """Test two calls to 1 GET per second limit.""" limit = limits.Limit("GET", "*", ".*", 1, 1) delay = limit("GET", "/anything") self.assertEqual(None, delay) delay = limit("GET", "/anything") self.assertEqual(1, delay) self.assertEqual(1, limit.next_request) self.assertEqual(0, limit.last_request) self.time += 4 delay = limit("GET", "/anything") self.assertEqual(None, delay) self.assertEqual(4, limit.next_request) self.assertEqual(4, limit.last_request) class ParseLimitsTest(BaseLimitTestSuite): """ Tests for the default limits parser in the in-memory `limits.Limiter` class. """ def test_invalid(self): """Test that parse_limits() handles invalid input correctly.""" self.assertRaises(ValueError, limits.Limiter.parse_limits, ';;;;;') def test_bad_rule(self): """Test that parse_limits() handles bad rules correctly.""" self.assertRaises(ValueError, limits.Limiter.parse_limits, 'GET, *, .*, 20, minute') def test_missing_arg(self): """Test that parse_limits() handles missing args correctly.""" self.assertRaises(ValueError, limits.Limiter.parse_limits, '(GET, *, .*, 20)') def test_bad_value(self): """Test that parse_limits() handles bad values correctly.""" self.assertRaises(ValueError, limits.Limiter.parse_limits, '(GET, *, .*, foo, minute)') def test_bad_unit(self): """Test that parse_limits() handles bad units correctly.""" self.assertRaises(ValueError, limits.Limiter.parse_limits, '(GET, *, .*, 20, lightyears)') def test_multiple_rules(self): """Test that parse_limits() handles multiple rules correctly.""" try: l = limits.Limiter.parse_limits('(get, *, .*, 20, minute);' '(PUT, /foo*, /foo.*, 10, hour);' '(POST, /bar*, /bar.*, 5, second);' '(Say, /derp*, /derp.*, 1, day)') except ValueError, e: assert False, str(e) # Make sure the number of returned limits are correct self.assertEqual(len(l), 4) # Check all the verbs... expected = ['GET', 'PUT', 'POST', 'SAY'] self.assertEqual([t.verb for t in l], expected) # ...the URIs... expected = ['*', '/foo*', '/bar*', '/derp*'] self.assertEqual([t.uri for t in l], expected) # ...the regexes... expected = ['.*', '/foo.*', '/bar.*', '/derp.*'] self.assertEqual([t.regex for t in l], expected) # ...the values... expected = [20, 10, 5, 1] self.assertEqual([t.value for t in l], expected) # ...and the units... expected = [limits.PER_MINUTE, limits.PER_HOUR, limits.PER_SECOND, limits.PER_DAY] self.assertEqual([t.unit for t in l], expected) class LimiterTest(BaseLimitTestSuite): """ Tests for the in-memory `limits.Limiter` class. """ def setUp(self): """Run before each test.""" super(LimiterTest, self).setUp() userlimits = {'user:user3': ''} self.limiter = limits.Limiter(TEST_LIMITS, **userlimits) def _check(self, num, verb, url, username=None): """Check and yield results from checks.""" for x in xrange(num): yield self.limiter.check_for_delay(verb, url, username)[0] def _check_sum(self, num, verb, url, username=None): """Check and sum results from checks.""" results = self._check(num, verb, url, username) return sum(item for item in results if item) def test_no_delay_GET(self): """ Simple test to ensure no delay on a single call for a limit verb we didn"t set. """ delay = self.limiter.check_for_delay("GET", "/anything") self.assertEqual(delay, (None, None)) def test_no_delay_PUT(self): """ Simple test to ensure no delay on a single call for a known limit. """ delay = self.limiter.check_for_delay("PUT", "/anything") self.assertEqual(delay, (None, None)) def test_delay_PUT(self): """ Ensure the 11th PUT will result in a delay of 6.0 seconds until the next request will be granced. """ expected = [None] * 10 + [6.0] results = list(self._check(11, "PUT", "/anything")) self.assertEqual(expected, results) def test_delay_POST(self): """ Ensure the 8th POST will result in a delay of 6.0 seconds until the next request will be granced. """ expected = [None] * 7 results = list(self._check(7, "POST", "/anything")) self.assertEqual(expected, results) expected = 60.0 / 7.0 results = self._check_sum(1, "POST", "/anything") self.failUnlessAlmostEqual(expected, results, 8) def test_delay_GET(self): """ Ensure the 11th GET will result in NO delay. """ expected = [None] * 11 results = list(self._check(11, "GET", "/anything")) self.assertEqual(expected, results) def test_delay_PUT_servers(self): """ Ensure PUT on /servers limits at 5 requests, and PUT elsewhere is still OK after 5 requests...but then after 11 total requests, PUT limiting kicks in. """ # First 6 requests on PUT /servers expected = [None] * 5 + [12.0] results = list(self._check(6, "PUT", "/servers")) self.assertEqual(expected, results) # Next 5 request on PUT /anything expected = [None] * 4 + [6.0] results = list(self._check(5, "PUT", "/anything")) self.assertEqual(expected, results) def test_delay_PUT_wait(self): """ Ensure after hitting the limit and then waiting for the correct amount of time, the limit will be lifted. """ expected = [None] * 10 + [6.0] results = list(self._check(11, "PUT", "/anything")) self.assertEqual(expected, results) # Advance time self.time += 6.0 expected = [None, 6.0] results = list(self._check(2, "PUT", "/anything")) self.assertEqual(expected, results) def test_multiple_delays(self): """ Ensure multiple requests still get a delay. """ expected = [None] * 10 + [6.0] * 10 results = list(self._check(20, "PUT", "/anything")) self.assertEqual(expected, results) self.time += 1.0 expected = [5.0] * 10 results = list(self._check(10, "PUT", "/anything")) self.assertEqual(expected, results) def test_user_limit(self): """ Test user-specific limits. """ self.assertEqual(self.limiter.levels['user3'], []) def test_multiple_users(self): """ Tests involving multiple users. """ # User1 expected = [None] * 10 + [6.0] * 10 results = list(self._check(20, "PUT", "/anything", "user1")) self.assertEqual(expected, results) # User2 expected = [None] * 10 + [6.0] * 5 results = list(self._check(15, "PUT", "/anything", "user2")) self.assertEqual(expected, results) # User3 expected = [None] * 20 results = list(self._check(20, "PUT", "/anything", "user3")) self.assertEqual(expected, results) self.time += 1.0 # User1 again expected = [5.0] * 10 results = list(self._check(10, "PUT", "/anything", "user1")) self.assertEqual(expected, results) self.time += 1.0 # User1 again expected = [4.0] * 5 results = list(self._check(5, "PUT", "/anything", "user2")) self.assertEqual(expected, results) class WsgiLimiterTest(BaseLimitTestSuite): """ Tests for `limits.WsgiLimiter` class. """ def setUp(self): """Run before each test.""" super(WsgiLimiterTest, self).setUp() self.app = limits.WsgiLimiter(TEST_LIMITS) def _request_data(self, verb, path): """Get data decribing a limit request verb/path.""" return json.dumps({"verb": verb, "path": path}) def _request(self, verb, url, username=None): """Make sure that POSTing to the given url causes the given username to perform the given action. Make the internal rate limiter return delay and make sure that the WSGI app returns the correct response. """ if username: request = webob.Request.blank("/%s" % username) else: request = webob.Request.blank("/") request.method = "POST" request.body = self._request_data(verb, url) response = request.get_response(self.app) if "X-Wait-Seconds" in response.headers: self.assertEqual(response.status_int, 403) return response.headers["X-Wait-Seconds"] self.assertEqual(response.status_int, 204) def test_invalid_methods(self): """Only POSTs should work.""" requests = [] for method in ["GET", "PUT", "DELETE", "HEAD", "OPTIONS"]: request = webob.Request.blank("/", method=method) response = request.get_response(self.app) self.assertEqual(response.status_int, 405) def test_good_url(self): delay = self._request("GET", "/something") self.assertEqual(delay, None) def test_escaping(self): delay = self._request("GET", "/something/jump%20up") self.assertEqual(delay, None) def test_response_to_delays(self): delay = self._request("GET", "/delayed") self.assertEqual(delay, None) delay = self._request("GET", "/delayed") self.assertEqual(delay, '60.00') def test_response_to_delays_usernames(self): delay = self._request("GET", "/delayed", "user1") self.assertEqual(delay, None) delay = self._request("GET", "/delayed", "user2") self.assertEqual(delay, None) delay = self._request("GET", "/delayed", "user1") self.assertEqual(delay, '60.00') delay = self._request("GET", "/delayed", "user2") self.assertEqual(delay, '60.00') class FakeHttplibSocket(object): """ Fake `httplib.HTTPResponse` replacement. """ def __init__(self, response_string): """Initialize new `FakeHttplibSocket`.""" self._buffer = StringIO.StringIO(response_string) def makefile(self, _mode, _other): """Returns the socket's internal buffer.""" return self._buffer class FakeHttplibConnection(object): """ Fake `httplib.HTTPConnection`. """ def __init__(self, app, host): """ Initialize `FakeHttplibConnection`. """ self.app = app self.host = host def request(self, method, path, body="", headers=None): """ Requests made via this connection actually get translated and routed into our WSGI app, we then wait for the response and turn it back into an `httplib.HTTPResponse`. """ if not headers: headers = {} req = webob.Request.blank(path) req.method = method req.headers = headers req.host = self.host req.body = body resp = str(req.get_response(self.app)) resp = "HTTP/1.0 %s" % resp sock = FakeHttplibSocket(resp) self.http_response = httplib.HTTPResponse(sock) self.http_response.begin() def getresponse(self): """Return our generated response from the request.""" return self.http_response def wire_HTTPConnection_to_WSGI(host, app): """Monkeypatches HTTPConnection so that if you try to connect to host, you are instead routed straight to the given WSGI app. After calling this method, when any code calls httplib.HTTPConnection(host) the connection object will be a fake. Its requests will be sent directly to the given WSGI app rather than through a socket. Code connecting to hosts other than host will not be affected. This method may be called multiple times to map different hosts to different apps. """ class HTTPConnectionDecorator(object): """Wraps the real HTTPConnection class so that when you instantiate the class you might instead get a fake instance.""" def __init__(self, wrapped): self.wrapped = wrapped def __call__(self, connection_host, *args, **kwargs): if connection_host == host: return FakeHttplibConnection(app, host) else: return self.wrapped(connection_host, *args, **kwargs) httplib.HTTPConnection = HTTPConnectionDecorator(httplib.HTTPConnection) class WsgiLimiterProxyTest(BaseLimitTestSuite): """ Tests for the `limits.WsgiLimiterProxy` class. """ def setUp(self): """ Do some nifty HTTP/WSGI magic which allows for WSGI to be called directly by something like the `httplib` library. """ super(WsgiLimiterProxyTest, self).setUp() self.app = limits.WsgiLimiter(TEST_LIMITS) wire_HTTPConnection_to_WSGI("169.254.0.1:80", self.app) self.proxy = limits.WsgiLimiterProxy("169.254.0.1:80") def test_200(self): """Successful request test.""" delay = self.proxy.check_for_delay("GET", "/anything") self.assertEqual(delay, (None, None)) def test_403(self): """Forbidden request test.""" delay = self.proxy.check_for_delay("GET", "/delayed") self.assertEqual(delay, (None, None)) delay, error = self.proxy.check_for_delay("GET", "/delayed") error = error.strip() expected = ("60.00", "403 Forbidden\n\nOnly 1 GET request(s) can be " "made to /delayed every minute.") self.assertEqual((delay, error), expected) class LimitsViewBuilderTest(test.TestCase): def setUp(self): super(LimitsViewBuilderTest, self).setUp() self.view_builder = views.limits.ViewBuilder() self.rate_limits = [{"URI": "*", "regex": ".*", "value": 10, "verb": "POST", "remaining": 2, "unit": "MINUTE", "resetTime": 1311272226}, {"URI": "*/servers", "regex": "^/servers", "value": 50, "verb": "POST", "remaining": 10, "unit": "DAY", "resetTime": 1311272226}] self.absolute_limits = {"metadata_items": 1, "injected_files": 5, "injected_file_content_bytes": 5} def test_build_limits(self): expected_limits = {"limits": { "rate": [{ "uri": "*", "regex": ".*", "limit": [{"value": 10, "verb": "POST", "remaining": 2, "unit": "MINUTE", "next-available": "2011-07-21T18:17:06Z"}]}, {"uri": "*/servers", "regex": "^/servers", "limit": [{"value": 50, "verb": "POST", "remaining": 10, "unit": "DAY", "next-available": "2011-07-21T18:17:06Z"}]}], "absolute": {"maxServerMeta": 1, "maxImageMeta": 1, "maxPersonality": 5, "maxPersonalitySize": 5}}} output = self.view_builder.build(self.rate_limits, self.absolute_limits) self.assertDictMatch(output, expected_limits) def test_build_limits_empty_limits(self): expected_limits = {"limits": {"rate": [], "absolute": {}}} abs_limits = {} rate_limits = [] output = self.view_builder.build(rate_limits, abs_limits) self.assertDictMatch(output, expected_limits) class LimitsXMLSerializationTest(test.TestCase): def test_xml_declaration(self): serializer = limits.LimitsTemplate() fixture = {"limits": { "rate": [], "absolute": {}}} output = serializer.serialize(fixture) print output has_dec = output.startswith("<?xml version='1.0' encoding='UTF-8'?>") self.assertTrue(has_dec) def test_index(self): serializer = limits.LimitsTemplate() fixture = { "limits": { "rate": [{ "uri": "*", "regex": ".*", "limit": [{ "value": 10, "verb": "POST", "remaining": 2, "unit": "MINUTE", "next-available": "2011-12-15T22:42:45Z"}]}, {"uri": "*/servers", "regex": "^/servers", "limit": [{ "value": 50, "verb": "POST", "remaining": 10, "unit": "DAY", "next-available": "2011-12-15T22:42:45Z"}]}], "absolute": {"maxServerMeta": 1, "maxImageMeta": 1, "maxPersonality": 5, "maxPersonalitySize": 10240}}} output = serializer.serialize(fixture) print output root = etree.XML(output) xmlutil.validate_schema(root, 'limits') #verify absolute limits absolutes = root.xpath('ns:absolute/ns:limit', namespaces=NS) self.assertEqual(len(absolutes), 4) for limit in absolutes: name = limit.get('name') value = limit.get('value') self.assertEqual(value, str(fixture['limits']['absolute'][name])) #verify rate limits rates = root.xpath('ns:rates/ns:rate', namespaces=NS) self.assertEqual(len(rates), 2) for i, rate in enumerate(rates): for key in ['uri', 'regex']: self.assertEqual(rate.get(key), str(fixture['limits']['rate'][i][key])) rate_limits = rate.xpath('ns:limit', namespaces=NS) self.assertEqual(len(rate_limits), 1) for j, limit in enumerate(rate_limits): for key in ['verb', 'value', 'remaining', 'unit', 'next-available']: self.assertEqual(limit.get(key), str(fixture['limits']['rate'][i]['limit'][j][key])) def test_index_no_limits(self): serializer = limits.LimitsTemplate() fixture = {"limits": { "rate": [], "absolute": {}}} output = serializer.serialize(fixture) print output root = etree.XML(output) xmlutil.validate_schema(root, 'limits') #verify absolute limits absolutes = root.xpath('ns:absolute/ns:limit', namespaces=NS) self.assertEqual(len(absolutes), 0) #verify rate limits rates = root.xpath('ns:rates/ns:rate', namespaces=NS) self.assertEqual(len(rates), 0)
""" Contains functional tests of the Git class. """ import os import pytest from pip._internal.vcs import vcs from pip._internal.vcs.git import Git, RemoteNotFoundError from tests.lib import _create_test_package, _git_commit, _test_path_to_file_url def test_get_backend_for_scheme(): assert vcs.get_backend_for_scheme("git+https") is vcs.get_backend("Git") def get_head_sha(script, dest): """Return the HEAD sha.""" result = script.run('git', 'rev-parse', 'HEAD', cwd=dest) sha = result.stdout.strip() return sha def checkout_ref(script, repo_dir, ref): script.run('git', 'checkout', ref, cwd=repo_dir) def checkout_new_branch(script, repo_dir, branch): script.run( 'git', 'checkout', '-b', branch, cwd=repo_dir, ) def do_commit(script, dest): _git_commit(script, dest, message='test commit', allow_empty=True) return get_head_sha(script, dest) def add_commits(script, dest, count): """Return a list of the commit hashes from oldest to newest.""" shas = [] for index in range(count): sha = do_commit(script, dest) shas.append(sha) return shas def check_rev(repo_dir, rev, expected): assert Git.get_revision_sha(repo_dir, rev) == expected def test_git_dir_ignored(tmpdir): """ Test that a GIT_DIR environment variable is ignored. """ repo_path = tmpdir / 'test-repo' repo_path.mkdir() repo_dir = str(repo_path) env = {'GIT_DIR': 'foo'} # If GIT_DIR is not ignored, then os.listdir() will return ['foo']. Git.run_command(['init', repo_dir], cwd=repo_dir, extra_environ=env) assert os.listdir(repo_dir) == ['.git'] def test_git_work_tree_ignored(tmpdir): """ Test that a GIT_WORK_TREE environment variable is ignored. """ repo_path = tmpdir / 'test-repo' repo_path.mkdir() repo_dir = str(repo_path) Git.run_command(['init', repo_dir], cwd=repo_dir) # Choose a directory relative to the cwd that does not exist. # If GIT_WORK_TREE is not ignored, then the command will error out # with: "fatal: This operation must be run in a work tree". env = {'GIT_WORK_TREE': 'foo'} Git.run_command(['status', repo_dir], extra_environ=env, cwd=repo_dir) def test_get_remote_url(script, tmpdir): source_dir = tmpdir / 'source' source_dir.mkdir() source_url = _test_path_to_file_url(source_dir) source_dir = str(source_dir) script.run('git', 'init', cwd=source_dir) do_commit(script, source_dir) repo_dir = str(tmpdir / 'repo') script.run('git', 'clone', source_url, repo_dir) remote_url = Git.get_remote_url(repo_dir) assert remote_url == source_url def test_get_remote_url__no_remote(script, tmpdir): """ Test a repo with no remote. """ repo_dir = tmpdir / 'temp-repo' repo_dir.mkdir() repo_dir = str(repo_dir) script.run('git', 'init', cwd=repo_dir) with pytest.raises(RemoteNotFoundError): Git.get_remote_url(repo_dir) def test_get_current_branch(script): repo_dir = str(script.scratch_path) script.run('git', 'init', cwd=repo_dir) sha = do_commit(script, repo_dir) assert Git.get_current_branch(repo_dir) == 'master' # Switch to a branch with the same SHA as "master" but whose name # is alphabetically after. checkout_new_branch(script, repo_dir, 'release') assert Git.get_current_branch(repo_dir) == 'release' # Also test the detached HEAD case. checkout_ref(script, repo_dir, sha) assert Git.get_current_branch(repo_dir) is None def test_get_current_branch__branch_and_tag_same_name(script, tmpdir): """ Check calling get_current_branch() from a branch or tag when the branch and tag have the same name. """ repo_dir = str(tmpdir) script.run('git', 'init', cwd=repo_dir) do_commit(script, repo_dir) checkout_new_branch(script, repo_dir, 'dev') # Create a tag with the same name as the branch. script.run('git', 'tag', 'dev', cwd=repo_dir) assert Git.get_current_branch(repo_dir) == 'dev' # Now try with the tag checked out. checkout_ref(script, repo_dir, 'refs/tags/dev') assert Git.get_current_branch(repo_dir) is None def test_get_revision_sha(script): repo_dir = str(script.scratch_path) script.run('git', 'init', cwd=repo_dir) shas = add_commits(script, repo_dir, count=3) tag_sha = shas[0] origin_sha = shas[1] head_sha = shas[2] assert head_sha == shas[-1] origin_ref = 'refs/remotes/origin/origin-branch' generic_ref = 'refs/generic-ref' script.run( 'git', 'branch', 'local-branch', head_sha, cwd=repo_dir ) script.run('git', 'tag', 'v1.0', tag_sha, cwd=repo_dir) script.run('git', 'update-ref', origin_ref, origin_sha, cwd=repo_dir) script.run( 'git', 'update-ref', 'refs/remotes/upstream/upstream-branch', head_sha, cwd=repo_dir ) script.run('git', 'update-ref', generic_ref, head_sha, cwd=repo_dir) # Test two tags pointing to the same sha. script.run('git', 'tag', 'v2.0', tag_sha, cwd=repo_dir) # Test tags sharing the same suffix as another tag, both before and # after the suffix alphabetically. script.run('git', 'tag', 'aaa/v1.0', head_sha, cwd=repo_dir) script.run('git', 'tag', 'zzz/v1.0', head_sha, cwd=repo_dir) check_rev(repo_dir, 'v1.0', (tag_sha, False)) check_rev(repo_dir, 'v2.0', (tag_sha, False)) check_rev(repo_dir, 'origin-branch', (origin_sha, True)) ignored_names = [ # Local branches should be ignored. 'local-branch', # Non-origin remote branches should be ignored. 'upstream-branch', # Generic refs should be ignored. 'generic-ref', # Fully spelled-out refs should be ignored. origin_ref, generic_ref, # Test passing a valid commit hash. tag_sha, # Test passing a non-existent name. 'does-not-exist', ] for name in ignored_names: check_rev(repo_dir, name, (None, False)) def test_is_commit_id_equal(script): """ Test Git.is_commit_id_equal(). """ version_pkg_path = _create_test_package(script) script.run('git', 'branch', 'branch0.1', cwd=version_pkg_path) commit = script.run( 'git', 'rev-parse', 'HEAD', cwd=version_pkg_path ).stdout.strip() assert Git.is_commit_id_equal(version_pkg_path, commit) assert not Git.is_commit_id_equal(version_pkg_path, commit[:7]) assert not Git.is_commit_id_equal(version_pkg_path, 'branch0.1') assert not Git.is_commit_id_equal(version_pkg_path, 'abc123') # Also check passing a None value. assert not Git.is_commit_id_equal(version_pkg_path, None) def test_is_immutable_rev_checkout(script): version_pkg_path = _create_test_package(script) commit = script.run( 'git', 'rev-parse', 'HEAD', cwd=version_pkg_path ).stdout.strip() assert Git().is_immutable_rev_checkout( "git+https://g.c/o/r@" + commit, version_pkg_path ) assert not Git().is_immutable_rev_checkout( "git+https://g.c/o/r", version_pkg_path ) assert not Git().is_immutable_rev_checkout( "git+https://g.c/o/r@master", version_pkg_path )
#!/usr/bin/env python # -*- coding: utf-8 -*- """Invoke tasks. To run a task, run ``$ invoke <COMMAND>``. To see a list of commands, run ``$ invoke --list``. """ import os import sys import json import platform import subprocess import logging from time import sleep import invoke from invoke import Collection from website import settings from .utils import pip_install, bin_prefix logging.getLogger('invoke').setLevel(logging.CRITICAL) # gets the root path for all the scripts that rely on it HERE = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) WHEELHOUSE_PATH = os.environ.get('WHEELHOUSE') CONSTRAINTS_PATH = os.path.join(HERE, 'requirements', 'constraints.txt') ns = Collection() try: from admin import tasks as admin_tasks ns.add_collection(Collection.from_module(admin_tasks), name='admin') except ImportError: pass def task(*args, **kwargs): """Behaves the same way as invoke.task. Adds the task to the root namespace. """ if len(args) == 1 and callable(args[0]): new_task = invoke.task(args[0]) ns.add_task(new_task) return new_task def decorator(f): new_task = invoke.task(f, *args, **kwargs) ns.add_task(new_task) return new_task return decorator @task def server(ctx, host=None, port=5000, debug=True, gitlogs=False): """Run the app server.""" if os.environ.get('WERKZEUG_RUN_MAIN') == 'true' or not debug: if os.environ.get('WEB_REMOTE_DEBUG', None): import pydevd # e.g. '127.0.0.1:5678' remote_parts = os.environ.get('WEB_REMOTE_DEBUG').split(':') pydevd.settrace(remote_parts[0], port=int(remote_parts[1]), suspend=False, stdoutToServer=True, stderrToServer=True) if gitlogs: git_logs(ctx) from website.app import init_app os.environ['DJANGO_SETTINGS_MODULE'] = 'api.base.settings' app = init_app(set_backends=True, routes=True) settings.API_SERVER_PORT = port else: from framework.flask import app context = None if settings.SECURE_MODE: context = (settings.OSF_SERVER_CERT, settings.OSF_SERVER_KEY) app.run(host=host, port=port, debug=debug, threaded=debug, extra_files=[settings.ASSET_HASH_PATH], ssl_context=context) @task def git_logs(ctx, branch=None): from scripts.meta import gatherer gatherer.main(branch=branch) @task def apiserver(ctx, port=8000, wait=True, autoreload=True, host='127.0.0.1', pty=True): """Run the API server.""" env = os.environ.copy() cmd = 'DJANGO_SETTINGS_MODULE=api.base.settings {} manage.py runserver {}:{} --nothreading'\ .format(sys.executable, host, port) if not autoreload: cmd += ' --noreload' if settings.SECURE_MODE: cmd = cmd.replace('runserver', 'runsslserver') cmd += ' --certificate {} --key {}'.format(settings.OSF_SERVER_CERT, settings.OSF_SERVER_KEY) if wait: return ctx.run(cmd, echo=True, pty=pty) from subprocess import Popen return Popen(cmd, shell=True, env=env) @task def adminserver(ctx, port=8001, host='127.0.0.1', pty=True): """Run the Admin server.""" env = 'DJANGO_SETTINGS_MODULE="admin.base.settings"' cmd = '{} python manage.py runserver {}:{} --nothreading'.format(env, host, port) if settings.SECURE_MODE: cmd = cmd.replace('runserver', 'runsslserver') cmd += ' --certificate {} --key {}'.format(settings.OSF_SERVER_CERT, settings.OSF_SERVER_KEY) ctx.run(cmd, echo=True, pty=pty) @task def shell(ctx, transaction=True, print_sql=False, notebook=False): cmd = 'DJANGO_SETTINGS_MODULE="api.base.settings" python manage.py osf_shell' if print_sql: cmd += ' --print-sql' if notebook: cmd += ' --notebook' if not transaction: cmd += ' --no-transaction' return ctx.run(cmd, pty=True, echo=True) @task def sharejs(ctx, host=None, port=None, db_url=None, cors_allow_origin=None): """Start a local ShareJS server.""" if host: os.environ['SHAREJS_SERVER_HOST'] = host if port: os.environ['SHAREJS_SERVER_PORT'] = port if db_url: os.environ['SHAREJS_DB_URL'] = db_url if cors_allow_origin: os.environ['SHAREJS_CORS_ALLOW_ORIGIN'] = cors_allow_origin if settings.SENTRY_DSN: os.environ['SHAREJS_SENTRY_DSN'] = settings.SENTRY_DSN share_server = os.path.join(settings.ADDON_PATH, 'wiki', 'shareServer.js') ctx.run('node {0}'.format(share_server)) @task(aliases=['celery']) def celery_worker(ctx, level='debug', hostname=None, beat=False, queues=None, concurrency=None, max_tasks_per_child=None): """Run the Celery process.""" os.environ['DJANGO_SETTINGS_MODULE'] = 'api.base.settings' cmd = 'celery worker -A framework.celery_tasks -Ofair -l {0}'.format(level) if hostname: cmd = cmd + ' --hostname={}'.format(hostname) # beat sets up a cron like scheduler, refer to website/settings if beat: cmd = cmd + ' --beat' if queues: cmd = cmd + ' --queues={}'.format(queues) if concurrency: cmd = cmd + ' --concurrency={}'.format(concurrency) if max_tasks_per_child: cmd = cmd + ' --maxtasksperchild={}'.format(max_tasks_per_child) ctx.run(bin_prefix(cmd), pty=True) @task(aliases=['beat']) def celery_beat(ctx, level='debug', schedule=None): """Run the Celery process.""" os.environ['DJANGO_SETTINGS_MODULE'] = 'api.base.settings' # beat sets up a cron like scheduler, refer to website/settings cmd = 'celery beat -A framework.celery_tasks -l {0} --pidfile='.format(level) if schedule: cmd = cmd + ' --schedule={}'.format(schedule) ctx.run(bin_prefix(cmd), pty=True) @task def migrate_search(ctx, delete=True, remove=False, index=settings.ELASTIC_INDEX): """Migrate the search-enabled models.""" from website.app import init_app init_app(routes=False, set_backends=False) from website.search_migration.migrate import migrate # NOTE: Silence the warning: # "InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised." SILENT_LOGGERS = ['py.warnings'] for logger in SILENT_LOGGERS: logging.getLogger(logger).setLevel(logging.ERROR) migrate(delete, remove=remove, index=index) @task def rebuild_search(ctx): """Delete and recreate the index for elasticsearch""" from website.app import init_app import requests from website import settings init_app(routes=False, set_backends=True) if not settings.ELASTIC_URI.startswith('http'): protocol = 'http://' if settings.DEBUG_MODE else 'https://' else: protocol = '' url = '{protocol}{uri}/{index}'.format( protocol=protocol, uri=settings.ELASTIC_URI.rstrip('/'), index=settings.ELASTIC_INDEX, ) print('Deleting index {}'.format(settings.ELASTIC_INDEX)) print('----- DELETE {}*'.format(url)) requests.delete(url + '*') print('Creating index {}'.format(settings.ELASTIC_INDEX)) print('----- PUT {}'.format(url)) requests.put(url) migrate_search(ctx, delete=False) @task def mailserver(ctx, port=1025): """Run a SMTP test server.""" cmd = 'python -m smtpd -n -c DebuggingServer localhost:{port}'.format(port=port) ctx.run(bin_prefix(cmd), pty=True) @task def jshint(ctx): """Run JSHint syntax check""" js_folder = os.path.join(HERE, 'website', 'static', 'js') jshint_bin = os.path.join(HERE, 'node_modules', '.bin', 'jshint') cmd = '{} {}'.format(jshint_bin, js_folder) ctx.run(cmd, echo=True) @task(aliases=['flake8']) def flake(ctx): ctx.run('flake8 .', echo=True) @task(aliases=['req']) def requirements(ctx, base=False, addons=False, release=False, dev=False, quick=False): """Install python dependencies. Examples: inv requirements inv requirements --quick Quick requirements are, in order, addons, dev and the base requirements. You should be able to use --quick for day to day development. By default, base requirements will run. However, if any set of addons, release, or dev are chosen, base will have to be mentioned explicitly in order to run. This is to remain compatible with previous usages. Release requirements will prevent dev, and base from running. """ if quick: base = True addons = True dev = True if not(addons or dev): base = True if release or addons: addon_requirements(ctx) # "release" takes precedence if release: req_file = os.path.join(HERE, 'requirements', 'release.txt') ctx.run( pip_install(req_file, constraints_file=CONSTRAINTS_PATH), echo=True ) else: if dev: # then dev requirements req_file = os.path.join(HERE, 'requirements', 'dev.txt') ctx.run( pip_install(req_file, constraints_file=CONSTRAINTS_PATH), echo=True ) if base: # then base requirements req_file = os.path.join(HERE, 'requirements.txt') ctx.run( pip_install(req_file, constraints_file=CONSTRAINTS_PATH), echo=True ) # fix URITemplate name conflict h/t @github ctx.run('pip uninstall uritemplate.py --yes || true') ctx.run('pip install --no-cache-dir uritemplate.py==0.3.0') @task def test_module(ctx, module=None, numprocesses=None, nocapture=False, params=None, coverage=False): """Helper for running tests. """ os.environ['DJANGO_SETTINGS_MODULE'] = 'osf_tests.settings' import pytest if not numprocesses: from multiprocessing import cpu_count numprocesses = cpu_count() numprocesses = int(numprocesses) # NOTE: Subprocess to compensate for lack of thread safety in the httpretty module. # https://github.com/gabrielfalcao/HTTPretty/issues/209#issue-54090252 args = [] if coverage: args.extend([ '--cov-report', 'term-missing', '--cov', 'admin', '--cov', 'addons', '--cov', 'api', '--cov', 'framework', '--cov', 'osf', '--cov', 'website', ]) if not nocapture: args += ['-s'] if numprocesses > 1: args += ['-n {}'.format(numprocesses), '--max-slave-restart=0'] modules = [module] if isinstance(module, basestring) else module args.extend(modules) if params: params = [params] if isinstance(params, basestring) else params args.extend(params) retcode = pytest.main(args) sys.exit(retcode) OSF_TESTS = [ 'osf_tests', ] ELSE_TESTS = [ 'tests', ] API_TESTS1 = [ 'api_tests/identifiers', 'api_tests/institutions', 'api_tests/licenses', 'api_tests/logs', 'api_tests/metaschemas', 'api_tests/providers', 'api_tests/preprints', 'api_tests/registrations', 'api_tests/users', ] API_TESTS2 = [ 'api_tests/actions', 'api_tests/nodes', 'api_tests/requests' ] API_TESTS3 = [ 'api_tests/addons_tests', 'api_tests/applications', 'api_tests/base', 'api_tests/collections', 'api_tests/comments', 'api_tests/files', 'api_tests/guids', 'api_tests/reviews', 'api_tests/search', 'api_tests/taxonomies', 'api_tests/test', 'api_tests/tokens', 'api_tests/view_only_links', 'api_tests/wikis', ] ADDON_TESTS = [ 'addons', ] ADMIN_TESTS = [ 'admin_tests', ] @task def test_osf(ctx, numprocesses=None, coverage=False): """Run the OSF test suite.""" print('Testing modules "{}"'.format(OSF_TESTS)) test_module(ctx, module=OSF_TESTS, numprocesses=numprocesses, coverage=coverage) @task def test_else(ctx, numprocesses=None, coverage=False): """Run the old test suite.""" print('Testing modules "{}"'.format(ELSE_TESTS)) test_module(ctx, module=ELSE_TESTS, numprocesses=numprocesses, coverage=coverage) @task def test_api1(ctx, numprocesses=None, coverage=False): """Run the API test suite.""" print('Testing modules "{}"'.format(API_TESTS1 + ADMIN_TESTS)) test_module(ctx, module=API_TESTS1 + ADMIN_TESTS, numprocesses=numprocesses, coverage=coverage) @task def test_api2(ctx, numprocesses=None, coverage=False): """Run the API test suite.""" print('Testing modules "{}"'.format(API_TESTS2)) test_module(ctx, module=API_TESTS2, numprocesses=numprocesses, coverage=coverage) @task def test_api3(ctx, numprocesses=None, coverage=False): """Run the API test suite.""" print('Testing modules "{}"'.format(API_TESTS3 + OSF_TESTS)) test_module(ctx, module=API_TESTS3 + OSF_TESTS, numprocesses=numprocesses, coverage=coverage) @task def test_admin(ctx, numprocesses=None, coverage=False): """Run the Admin test suite.""" print('Testing module "admin_tests"') test_module(ctx, module=ADMIN_TESTS, numprocesses=numprocesses, coverage=coverage) @task def test_addons(ctx, numprocesses=None, coverage=False): """Run all the tests in the addons directory. """ print('Testing modules "{}"'.format(ADDON_TESTS)) test_module(ctx, module=ADDON_TESTS, numprocesses=numprocesses, coverage=coverage) @task def test_varnish(ctx): """Run the Varnish test suite.""" proc = apiserver(ctx, wait=False, autoreload=False) try: sleep(5) test_module(ctx, module='api/caching/tests/test_caching.py') finally: proc.kill() @task def test(ctx, all=False, syntax=False): """ Run unit tests: OSF (always), plus addons and syntax checks (optional) """ if syntax: flake(ctx) jshint(ctx) test_else(ctx) # /tests test_api1(ctx) test_api2(ctx) test_api3(ctx) # also /osf_tests if all: test_addons(ctx) # TODO: Enable admin tests test_admin(ctx) karma(ctx) @task def test_js(ctx): jshint(ctx) karma(ctx) @task def test_travis_addons(ctx, numprocesses=None, coverage=False): """ Run half of the tests to help travis go faster. Lints and Flakes happen everywhere to keep from wasting test time. """ flake(ctx) jshint(ctx) test_addons(ctx, numprocesses=numprocesses, coverage=coverage) @task def test_travis_else(ctx, numprocesses=None, coverage=False): """ Run other half of the tests to help travis go faster. Lints and Flakes happen everywhere to keep from wasting test time. """ flake(ctx) jshint(ctx) test_else(ctx, numprocesses=numprocesses, coverage=coverage) @task def test_travis_api1_and_js(ctx, numprocesses=None, coverage=False): flake(ctx) jshint(ctx) # TODO: Uncomment when https://github.com/travis-ci/travis-ci/issues/8836 is resolved # karma(ctx) test_api1(ctx, numprocesses=numprocesses, coverage=coverage) @task def test_travis_api2(ctx, numprocesses=None, coverage=False): flake(ctx) jshint(ctx) test_api2(ctx, numprocesses=numprocesses, coverage=coverage) @task def test_travis_api3_and_osf(ctx, numprocesses=None, coverage=False): flake(ctx) jshint(ctx) test_api3(ctx, numprocesses=numprocesses, coverage=coverage) @task def test_travis_varnish(ctx): """ Run the fast and quirky JS tests and varnish tests in isolation """ flake(ctx) jshint(ctx) test_js(ctx) test_varnish(ctx) @task def karma(ctx): """Run JS tests with Karma. Requires Chrome to be installed.""" ctx.run('yarn test', echo=True) @task def wheelhouse(ctx, addons=False, release=False, dev=False, pty=True): """Build wheels for python dependencies. Examples: inv wheelhouse --dev inv wheelhouse --addons inv wheelhouse --release """ if release or addons: for directory in os.listdir(settings.ADDON_PATH): path = os.path.join(settings.ADDON_PATH, directory) if os.path.isdir(path): req_file = os.path.join(path, 'requirements.txt') if os.path.exists(req_file): cmd = 'pip wheel --find-links={} -r {} --wheel-dir={} -c {}'.format( WHEELHOUSE_PATH, req_file, WHEELHOUSE_PATH, CONSTRAINTS_PATH, ) ctx.run(cmd, pty=pty) if release: req_file = os.path.join(HERE, 'requirements', 'release.txt') elif dev: req_file = os.path.join(HERE, 'requirements', 'dev.txt') else: req_file = os.path.join(HERE, 'requirements.txt') cmd = 'pip wheel --find-links={} -r {} --wheel-dir={} -c {}'.format( WHEELHOUSE_PATH, req_file, WHEELHOUSE_PATH, CONSTRAINTS_PATH, ) ctx.run(cmd, pty=pty) @task def addon_requirements(ctx): """Install all addon requirements.""" for directory in os.listdir(settings.ADDON_PATH): path = os.path.join(settings.ADDON_PATH, directory) requirements_file = os.path.join(path, 'requirements.txt') if os.path.isdir(path) and os.path.isfile(requirements_file): print('Installing requirements for {0}'.format(directory)) ctx.run( pip_install(requirements_file, constraints_file=CONSTRAINTS_PATH), echo=True ) print('Finished installing addon requirements') @task def travis_addon_settings(ctx): for directory in os.listdir(settings.ADDON_PATH): path = os.path.join(settings.ADDON_PATH, directory, 'settings') if os.path.isdir(path): try: open(os.path.join(path, 'local-travis.py')) ctx.run('cp {path}/local-travis.py {path}/local.py'.format(path=path)) except IOError: pass @task def copy_addon_settings(ctx): for directory in os.listdir(settings.ADDON_PATH): path = os.path.join(settings.ADDON_PATH, directory, 'settings') if os.path.isdir(path) and not os.path.isfile(os.path.join(path, 'local.py')): try: open(os.path.join(path, 'local-dist.py')) ctx.run('cp {path}/local-dist.py {path}/local.py'.format(path=path)) except IOError: pass @task def copy_settings(ctx, addons=False): # Website settings if not os.path.isfile('website/settings/local.py'): print('Creating local.py file') ctx.run('cp website/settings/local-dist.py website/settings/local.py') # Addon settings if addons: copy_addon_settings(ctx) @task(aliases=['bower']) def bower_install(ctx): print('Installing bower-managed packages') bower_bin = os.path.join(HERE, 'node_modules', '.bin', 'bower') ctx.run('{} prune --allow-root'.format(bower_bin), echo=True) ctx.run('{} install --allow-root'.format(bower_bin), echo=True) @task def docker_init(ctx): """Initial docker setup""" print('You will be asked for your sudo password to continue...') if platform.system() == 'Darwin': # Mac OSX ctx.run('sudo ifconfig lo0 alias 192.168.168.167') else: print('Your system is not recognized, you will have to setup docker manually') def ensure_docker_env_setup(ctx): if hasattr(os.environ, 'DOCKER_ENV_SETUP') and os.environ['DOCKER_ENV_SETUP'] == '1': pass else: os.environ['WEB_REMOTE_DEBUG'] = '192.168.168.167:11000' os.environ['API_REMOTE_DEBUG'] = '192.168.168.167:12000' os.environ['WORKER_REMOTE_DEBUG'] = '192.168.168.167:13000' os.environ['DOCKER_ENV_SETUP'] = '1' docker_init(ctx) @task def docker_requirements(ctx): ensure_docker_env_setup(ctx) ctx.run('docker-compose up requirements requirements_mfr requirements_wb') @task def docker_appservices(ctx): ensure_docker_env_setup(ctx) ctx.run('docker-compose up assets fakecas elasticsearch tokumx postgres') @task def docker_osf(ctx): ensure_docker_env_setup(ctx) ctx.run('docker-compose up mfr wb web api') @task def clear_sessions(ctx, months=1, dry_run=False): from website.app import init_app init_app(routes=False, set_backends=True) from scripts import clear_sessions clear_sessions.clear_sessions_relative(months=months, dry_run=dry_run) # Release tasks @task def hotfix(ctx, name, finish=False, push=False): """Rename hotfix branch to hotfix/<next-patch-version> and optionally finish hotfix. """ print('Checking out master to calculate curent version') ctx.run('git checkout master') latest_version = latest_tag_info()['current_version'] print('Current version is: {}'.format(latest_version)) major, minor, patch = latest_version.split('.') next_patch_version = '.'.join([major, minor, str(int(patch) + 1)]) print('Bumping to next patch version: {}'.format(next_patch_version)) print('Renaming branch...') new_branch_name = 'hotfix/{}'.format(next_patch_version) ctx.run('git checkout {}'.format(name), echo=True) ctx.run('git branch -m {}'.format(new_branch_name), echo=True) if finish: ctx.run('git flow hotfix finish {}'.format(next_patch_version), echo=True, pty=True) if push: ctx.run('git push --follow-tags origin master', echo=True) ctx.run('git push origin develop', echo=True) @task def feature(ctx, name, finish=False, push=False): """Rename the current branch to a feature branch and optionally finish it.""" print('Renaming branch...') ctx.run('git branch -m feature/{}'.format(name), echo=True) if finish: ctx.run('git flow feature finish {}'.format(name), echo=True) if push: ctx.run('git push origin develop', echo=True) # Adapted from bumpversion def latest_tag_info(): try: # git-describe doesn't update the git-index, so we do that # subprocess.check_output(["git", "update-index", "--refresh"]) # get info about the latest tag in git describe_out = subprocess.check_output([ 'git', 'describe', '--dirty', '--tags', '--long', '--abbrev=40' ], stderr=subprocess.STDOUT ).decode().split('-') except subprocess.CalledProcessError as err: raise err # logger.warn("Error when running git describe") return {} info = {} if describe_out[-1].strip() == 'dirty': info['dirty'] = True describe_out.pop() info['commit_sha'] = describe_out.pop().lstrip('g') info['distance_to_latest_tag'] = int(describe_out.pop()) info['current_version'] = describe_out.pop().lstrip('v') # assert type(info["current_version"]) == str assert 0 == len(describe_out) return info # Tasks for generating and bundling SSL certificates # See http://cosdev.readthedocs.org/en/latest/osf/ops.html for details @task def generate_key(ctx, domain, bits=2048): cmd = 'openssl genrsa -des3 -out {0}.key {1}'.format(domain, bits) ctx.run(cmd) @task def generate_key_nopass(ctx, domain): cmd = 'openssl rsa -in {domain}.key -out {domain}.key.nopass'.format( domain=domain ) ctx.run(cmd) @task def generate_csr(ctx, domain): cmd = 'openssl req -new -key {domain}.key.nopass -out {domain}.csr'.format( domain=domain ) ctx.run(cmd) @task def request_ssl_cert(ctx, domain): """Generate a key, a key with password removed, and a signing request for the specified domain. Usage: > invoke request_ssl_cert pizza.osf.io """ generate_key(ctx, domain) generate_key_nopass(ctx, domain) generate_csr(ctx, domain) @task def bundle_certs(ctx, domain, cert_path): """Concatenate certificates from NameCheap in the correct order. Certificate files must be in the same directory. """ cert_files = [ '{0}.crt'.format(domain), 'COMODORSADomainValidationSecureServerCA.crt', 'COMODORSAAddTrustCA.crt', 'AddTrustExternalCARoot.crt', ] certs = ' '.join( os.path.join(cert_path, cert_file) for cert_file in cert_files ) cmd = 'cat {certs} > {domain}.bundle.crt'.format( certs=certs, domain=domain, ) ctx.run(cmd) @task def clean_assets(ctx): """Remove built JS files.""" public_path = os.path.join(HERE, 'website', 'static', 'public') js_path = os.path.join(public_path, 'js') ctx.run('rm -rf {0}'.format(js_path), echo=True) @task(aliases=['pack']) def webpack(ctx, clean=False, watch=False, dev=False, colors=False): """Build static assets with webpack.""" if clean: clean_assets(ctx) args = ['yarn run webpack-{}'.format('dev' if dev else 'prod')] args += ['--progress'] if watch: args += ['--watch'] if colors: args += ['--colors'] command = ' '.join(args) ctx.run(command, echo=True) @task() def build_js_config_files(ctx): from website import settings print('Building JS config files...') with open(os.path.join(settings.STATIC_FOLDER, 'built', 'nodeCategories.json'), 'wb') as fp: json.dump(settings.NODE_CATEGORY_MAP, fp) print('...Done.') @task() def assets(ctx, dev=False, watch=False, colors=False): """Install and build static assets.""" command = 'yarn install --frozen-lockfile' if not dev: command += ' --production' ctx.run(command, echo=True) bower_install(ctx) build_js_config_files(ctx) # Always set clean=False to prevent possible mistakes # on prod webpack(ctx, clean=False, watch=watch, dev=dev, colors=colors) @task def generate_self_signed(ctx, domain): """Generate self-signed SSL key and certificate. """ cmd = ( 'openssl req -x509 -nodes -days 365 -newkey rsa:2048' ' -keyout {0}.key -out {0}.crt' ).format(domain) ctx.run(cmd) @task def update_citation_styles(ctx): from scripts import parse_citation_styles total = parse_citation_styles.main() print('Parsed {} styles'.format(total)) @task def clean(ctx, verbose=False): ctx.run('find . -name "*.pyc" -delete', echo=True) @task(default=True) def usage(ctx): ctx.run('invoke --list') ### Maintenance Tasks ### @task def set_maintenance(ctx, message='', level=1, start=None, end=None): from website.app import setup_django setup_django() from website.maintenance import set_maintenance """Display maintenance notice across OSF applications (incl. preprints, registries, etc.) start - Start time for the maintenance period end - End time for the mainteance period NOTE: If no start or end values are provided, default to starting now and ending 24 hours from now. message - Message to display. If omitted, will be: "The site will undergo maintenance between <localized start time> and <localized end time>. Thank you for your patience." level - Severity level. Modifies the color of the displayed notice. Must be one of 1 (info), 2 (warning), 3 (danger). Examples: invoke set_maintenance --start 2016-03-16T15:41:00-04:00 --end 2016-03-16T15:42:00-04:00 invoke set_maintenance --message 'The OSF is experiencing issues connecting to a 3rd party service' --level 2 --start 2016-03-16T15:41:00-04:00 --end 2016-03-16T15:42:00-04:00 """ state = set_maintenance(message, level, start, end) print('Maintenance notice up {} to {}.'.format(state['start'], state['end'])) @task def unset_maintenance(ctx): from website.app import setup_django setup_django() from website.maintenance import unset_maintenance print('Taking down maintenance notice...') unset_maintenance() print('...Done.')
import Tkinter from Tkinter import * from Tkinter import Label, W import Pmw import sys import csv import os import subprocess root = Tk() root.title('CITY CRIME DATA ANALYSIS') Pmw.initialise() var1 = StringVar() var1.set('---select---') opt_menu_1 = Pmw.OptionMenu(root, labelpos=W, label_text='City :', menubutton_textvariable=var1, items=('Boston', 'Chicago'), menubutton_width=16) opt_menu_1.pack(anchor=W, padx=20, pady=17) """var2 = StringVar() var2.set('---select---') opt_menu_2 = Pmw.OptionMenu(root, labelpos=W, label_text='Zip Code :', menubutton_textvariable=var2, items=('60601', '60602', '60603', '60604','60605','60606','60607', '60608', '60609', '60610','60611', '60612', '60613', '60614', '60615','60616','60617','60618','60619','60620', '60621','60622','60623','60624','60625','60626','60627','60628','60629','60630'), menubutton_width=16) opt_menu_2.pack(anchor=W, padx=20, pady=15)""" var2 = StringVar() var2 = Pmw.ComboBox(root, labelpos = W, entry_width=16, label_text= 'Zip Code :',entryfield_value='---select---') for item in reversed(['60601', "60602", "60603", "60604","60605","60606", "60607", "60608", "60609","60610","60611", "60612", "60613", "60614","60615","60616", "60617", "60618", "60619","60620",'60621','60622','60623','60624','60625','60626','60627','60628','60629','60630']): var2.insert(0,item) #var2.configure(width = 16) var2.pack(anchor=W,padx=20, pady=17) var3 = StringVar() var3.set('---select---') opt_menu_3 = Pmw.OptionMenu(root, labelpos=W, label_text='Type of Crime :', menubutton_textvariable=var3, items=('THEFT', 'BATTERY', 'CRIMINAL DAMAGE', 'NARCOTICS','OTHER OFFENSE','ASSAULT','DECEPTIVE PRACTICE','BURGLARY','MOTOR VEHICLE THEFT','ROBBERY'), menubutton_width=16) opt_menu_3.pack(anchor=W, padx=20, pady=17) var4 = StringVar() var4 = Pmw.ComboBox(root, labelpos = W, entry_width=16, label_text= 'Year :',entryfield_value='---select---') for item1 in reversed(['2016', '2015', '2014', '2013', '2012','2011','2010','2009', '2008','2007','2006','2005','2004','2003','2002','2001']): var4.insert(0,item1) #var2.configure(width = 16) var4.pack(anchor=W,padx=20, pady=17) var5 = StringVar() var5.set('---select---') opt_menu_5 = Pmw.OptionMenu(root, labelpos=W, label_text='Month :', menubutton_textvariable=var5, items=('JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE', 'JULY', 'AUGUST', 'SEPTEMBER', 'OCTOBER','NOVEMBER', 'DECEMBER'), menubutton_width=16) opt_menu_5.pack(anchor=W, padx=20, pady=15) var6 = StringVar() var6 = Pmw.ComboBox(root, labelpos = W, entry_width=16, label_text= 'Date :',entryfield_value='---select---') for item1 in reversed(['01', '02', '03', '04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31']): var6.insert(0,item1) #var2.configure(width = 16) var6.pack(anchor=W,padx=20, pady=17) var7 = StringVar() var7 = Pmw.ComboBox(root, labelpos = W, entry_width=16, label_text= 'Time Frame :',entryfield_value='---select---') for item1 in reversed(['(00-01)AM','(01-02)AM','(02-03)AM','(03-04)AM','(04-05)AM','(05-06)AM','(06-07)AM','(07-08)AM','(08-09)AM','(09-10)AM', '(10-11)AM','(11-12)AM','(12-01)PM','(01-02)PM','(02-03)PM','(03-04)PM','(04-05)PM','(05-06)PM','(06-07)PM','(07-08)PM','(08-09)PM', '(09-10)PM','(10-11)PM','(11-12)PM']): var7.insert(0,item1) var7.pack(anchor=W, padx=20, pady=17) opt_menu_1.pack(fill=X) var2.pack(fill=X) #opt_menu_2.pack(fill=X) opt_menu_3.pack(fill=X) var4.pack(fill=X) opt_menu_5.pack(fill=X) var6.pack(fill=X) var7.pack(fill=X) def state(): print "\n \t Selection : \n" print "city: -> ",var1.get(),'\n', "Zip Code: -> ",var2.get(),'\n', "Type of Crime: -> ",var3.get(),'\n', "Year: -> ",var4.get(),'\n', "Month: -> ",var5.get(),'\n', "Date: -> ",var6.get(),'\n', "Time Frame: -> ",var7.get() y = var7.get() x= var5.get() if x== "JANUARY": x= '01' elif x=="FEBRUARY": x= '02' elif x=="MARCH": x= '03' elif x=="APRIL": x= '04' elif x=="MAY": x='05' elif x=="JUNE": x='06' elif x=="JULY": x='07' elif x=="AUGUST": x='08' elif x=="SEPTEMBER": x='09' elif x=="OCTOBER": x='10' elif x=="NOVEMBER": x='11' elif x=="DECEMBER": x='12' with open('zip_code.csv','w') as outputfile: print >> outputfile, "col1" with open('zip_code.csv','a') as outputfile: print >> outputfile, var2.get() with open('type_of_crime.csv','w') as outputfile: print >> outputfile, "col1" with open('type_of_crime.csv','a') as outputfile: print >> outputfile, var3.get() with open('year.csv','wb') as outputfile: print >> outputfile, "col1" with open('year.csv','a') as outputfile: print >> outputfile, var4.get() # with open('month.txt','wb') as outputfile: # print >> outputfile with open('month.csv','wb') as outputfile: print >> outputfile, "col1" with open('month.csv','a') as outputfile: print >> outputfile,x with open('date.csv','wb') as outputfile: print >> outputfile, "col1" with open('date.csv','ab') as outputfile: print >> outputfile,var6.get() with open('time.csv','wb') as outputfile: print >> outputfile, "col1, col2" with open('time.csv','ab') as outputfile: print >> outputfile, y[1:3],",", y[7:9] with open('outputfile.csv','w') as outputfile: print >> outputfile, "col1" with open('outputfile.csv','a') as outputfile: x= [var1.get(),var2.get(),var3.get(),var4.get(),var5.get(),var6.get(),var7.get()] for i in x: print >> outputfile, i Button(root, command=state,bg='green',fg='white', text='submit').pack(padx=20, pady=15) def carry_on(): #os.system("python "+ 'gui2.py') #os.system("Rscript " + "R/gui3map_final.R") os.system("./bin/sparkR " + "/home/nj/R/data_analysis_with_map.R") Button(root,bg='green',fg='white',text = 'Click To Continue', command = carry_on).pack(padx=20) #button.pack() Button(root, text = 'Exit',bg='red',fg='white', command = root.destroy).pack(padx=10, pady=10, side = 'bottom') #exitButton. #widget = Demo(root) root.mainloop()
#!/usr/bin/python """ Author : Micah Hoffman (@WebBreacher) Description : Takes each username from the web_accounts_list.json file and performs the lookup to see if the discovery determinator is still valid TODO - 1 - Make it so the script will toggle validity factor per entry and write to output file 2 - Make it so the script will append comment to the entry and output to file 3 - Make a stub file shows last time sites were checked and problems. ISSUES - 1 - Had an issue with SSL handshakes and this script. Had to do the following to get it working [From https://github.com/kennethreitz/requests/issues/2022] # sudo apt-get install libffi-dev # pip install pyOpenSSL ndg-httpsclient pyasn1 requests """ import requests import argparse from requests.packages.urllib3.exceptions import InsecureRequestWarning import json import os import random import string import signal import sys import codecs ################### # Variables && Functions ################### # Set HTTP Header info. headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/45.0.2454.93 Safari/537.36'} # Parse command line input parser = argparse.ArgumentParser(description="This standalone script will look up a single username using the JSON file" " or will run a check of the JSON file for bad detection strings.") parser.add_argument('-u', '--username', help='[OPTIONAL] If this param is passed then this script will perform the ' 'lookups against the given user name instead of running checks against ' 'the JSON file.') parser.add_argument('-se', '--stringerror', help="Creates a site by site file for files that do not match strings. Filenames will be 'se-(sitename).(username)", action="store_true", default=False) parser.add_argument('-s', '--site', nargs='*', help='[OPTIONAL] If this parameter is passed the script will check only the named site or list of sites.') args = parser.parse_args() args = parser.parse_args() # Create the final results dictionary overall_results = {} def check_os(): if os.name == "nt": operating_system = "windows" if os.name == "posix": operating_system = "posix" return operating_system # # Class for colors # if check_os() == "posix": class bcolors: CYAN = '\033[96m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' ENDC = '\033[0m' def disable(self): self.CYAN = '' self.GREEN = '' self.YELLOW = '' self.RED = '' self.ENDC = '' # if we are windows or something like that then define colors as nothing else: class bcolors: CYAN = '' GREEN = '' YELLOW = '' RED = '' ENDC = '' def disable(self): self.CYAN = '' self.GREEN = '' self.YELLOW = '' self.RED = '' self.ENDC = '' def signal_handler(signal, frame): print(bcolors.RED + ' !!! You pressed Ctrl+C. Exitting script.' + bcolors.ENDC) finaloutput() sys.exit(0) def web_call(location): try: # Make web request for that URL, timeout in X secs and don't verify SSL/TLS certs r = requests.get(location, headers=headers, timeout=60, verify=False) except requests.exceptions.Timeout: return bcolors.RED + ' ! ERROR: CONNECTION TIME OUT. Try increasing the timeout delay.' + bcolors.ENDC except requests.exceptions.TooManyRedirects: return bcolors.RED + ' ! ERROR: TOO MANY REDIRECTS. Try changing the URL.' + bcolors.ENDC except requests.exceptions.RequestException as e: return bcolors.RED + ' ! ERROR: CRITICAL ERROR. %s' % e + bcolors.ENDC else: return r def finaloutput(): if len(overall_results) > 0: print '------------' print 'The following previously "valid" sites had errors:' for site, results in sorted(overall_results.iteritems()): print bcolors.YELLOW + ' %s --> %s' % (site, results) + bcolors.ENDC else: print ":) No problems with the JSON file were found." ################### # Main ################### # Add this in case user presses CTRL-C signal.signal(signal.SIGINT, signal_handler) # Suppress HTTPS warnings requests.packages.urllib3.disable_warnings(InsecureRequestWarning) # Read in the JSON file with open('web_accounts_list.json') as data_file: data = json.load(data_file) if args.site: # cut the list of sites down to only the requested ones args.site = [x.lower() for x in args.site] data['sites'] = [x for x in data['sites'] if x['name'].lower() in args.site] if len(data['sites']) == 0: print ' - Sorry, the requested site or sites were not found in the list' sys.exit() sites_not_found = len(args.site) - len(data['sites']) if sites_not_found: print ' - WARNING: %d requested sites were not found in the list' % sites_not_found print ' - Checking %d sites' % len(data['sites']) else: print ' - %s sites found in file.' % len(data['sites']) for site in data['sites']: code_match, string_match = False, False # Examine the current validity of the entry if not site['valid']: print bcolors.CYAN + ' * Skipping %s - Marked as not valid.' % site['name'] + bcolors.ENDC continue if not site['known_accounts'][0]: print bcolors.CYAN + ' * Skipping %s - No valid user names to test.' % site['name'] + bcolors.ENDC continue # Perform initial lookup # Pull the first user from known_accounts and replace the {account} with it url_list = [] if args.username: url = site['check_uri'].replace("{account}", args.username) url_list.append(url) uname = args.username else: account_list = site['known_accounts'] for each in account_list: url = site['check_uri'].replace("{account}", each) url_list.append(url) uname = each for each in url_list: print ' - Looking up %s' % each r = web_call(each) if isinstance(r, str): # We got an error on the web call print r continue # Analyze the responses against what they should be if r.status_code == int(site['account_existence_code']): code_match = True else: code_match = False if r.text.find(site['account_existence_string']) > 0: string_match = True else: string_match = False if args.username: if code_match and string_match: print ' - Found user at %s' % each continue if code_match and string_match: # print ' [+] Response code and Search Strings match expected.' # Generate a random string to use in place of known_accounts not_there_string = ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for x in range(20)) url_fp = site['check_uri'].replace("{account}", not_there_string) r_fp = web_call(url_fp) if isinstance(r_fp, str): # If this is a string then web got an error print r_fp continue if r_fp.status_code == int(site['account_existence_code']): code_match = True else: code_match = False if r_fp.text.find(site['account_existence_string']) > 0: string_match = True else: string_match = False if code_match and string_match: print ' - Code: %s; String: %s' % (code_match, string_match) print bcolors.RED + ' ! ERROR: FALSE POSITIVE DETECTED. Response code and Search Strings match ' \ 'expected.' + bcolors.ENDC # TODO set site['valid'] = False overall_results[site['name']] = 'False Positive' else: # print ' [+] Passed false positives test.' pass elif code_match and not string_match: # TODO set site['valid'] = False print bcolors.RED + ' ! ERROR: BAD DETECTION STRING. "%s" was not found on resulting page.' \ % site['account_existence_string'] + bcolors.ENDC overall_results[site['name']] = 'Bad detection string.' if args.stringerror: file_name = 'se-' + site['name'] + '.' + uname # Unicode sucks file_name = file_name.encode('ascii', 'ignore').decode('ascii') error_file = codecs.open(file_name, 'w', 'utf-8') error_file.write(r.text) print "Raw data exported to file:" + file_name error_file.close() elif not code_match and string_match: # TODO set site['valid'] = False print bcolors.RED + ' ! ERROR: BAD DETECTION RESPONSE CODE. HTTP Response code different than ' \ 'expected.' + bcolors.ENDC overall_results[site['name']] = 'Bad detection code. Received Code: %s; Expected Code: %s.' % \ (str(r.status_code), site['account_existence_code']) else: # TODO set site['valid'] = False print bcolors.RED + ' ! ERROR: BAD CODE AND STRING. Neither the HTTP response code or detection ' \ 'string worked.' + bcolors.ENDC overall_results[site['name']] = 'Bad detection code and string. Received Code: %s; Expected Code: %s.' \ % (str(r.status_code), site['account_existence_code']) if not args.username: finaloutput()
from contextlib import closing, contextmanager import base64 import json from io import BytesIO import zipfile from email.utils import parseaddr import random from typing import Iterator, Tuple, Optional from django.conf import settings from django.core.mail import get_connection, EmailMessage, mail_managers from django.urls import reverse from django.utils.translation import override, gettext_lazy as _ from froide.helper.email_utils import ( EmailParser, get_mail_client, get_unread_mails, make_address, unflag_mail ) from froide.helper.name_generator import get_name_from_number from .utils import get_publicbody_for_email, get_foi_mail_domains from .pdf_generator import FoiRequestPDFGenerator unknown_foimail_subject = _('Unknown FoI-Mail Recipient') unknown_foimail_message = _('''We received an FoI mail to this address: %(address)s. No corresponding request could be identified, please investigate! %(url)s ''') spam_message = _('''We received a possible spam mail to this address: %(address)s. Please investigate! %(url)s ''') DSN_RCPT_OPTIONS = ['NOTIFY=SUCCESS,DELAY,FAILURE'] def send_foi_mail(subject, message, from_email, recipient_list, attachments=None, fail_silently=False, **kwargs): backend_kwargs = {} if kwargs.get('dsn'): backend_kwargs['rcpt_options'] = DSN_RCPT_OPTIONS connection = get_connection( backend=settings.EMAIL_BACKEND, username=settings.FOI_EMAIL_HOST_USER, password=settings.FOI_EMAIL_HOST_PASSWORD, host=settings.FOI_EMAIL_HOST, port=settings.FOI_EMAIL_PORT, use_tls=settings.FOI_EMAIL_USE_TLS, fail_silently=fail_silently, **backend_kwargs ) headers = {} if settings.FOI_EMAIL_FIXED_FROM_ADDRESS: name, mailaddr = parseaddr(from_email) from_address = settings.FOI_EMAIL_HOST_FROM from_email = make_address(from_address, name) headers['Reply-To'] = make_address(mailaddr, name) else: headers['Reply-To'] = from_email if kwargs.get('read_receipt'): headers['Disposition-Notification-To'] = from_email if kwargs.get('delivery_receipt'): headers['Return-Receipt-To'] = from_email if kwargs.get('froide_message_id'): headers['X-Froide-Message-Id'] = kwargs.get('froide_message_id') email = EmailMessage(subject, message, from_email, recipient_list, connection=connection, headers=headers) if attachments is not None: for name, data, mime_type in attachments: email.attach(name, data, mime_type) return email.send() def _process_mail(mail_bytes, mail_uid=None, mail_type=None, manual=False): parser = EmailParser() email = None if mail_type is None: with closing(BytesIO(mail_bytes)) as stream: email = parser.parse(stream) elif mail_type == 'postmark': email = parser.parse_postmark(json.loads(mail_bytes.decode('utf-8'))) assert email is not None _deliver_mail(email, mail_bytes=mail_bytes, manual=manual) # Unflag mail after delivery is complete if mail_uid is not None: with get_foi_mail_client() as mailbox: unflag_mail(mailbox, mail_uid) def create_deferred(secret_mail, mail_bytes, spam=False, sender_email=None, subject=unknown_foimail_subject, body=unknown_foimail_message, request=None): from .models import DeferredMessage mail_string = '' if mail_bytes is not None: mail_string = base64.b64encode(mail_bytes).decode("utf-8") DeferredMessage.objects.create( recipient=secret_mail, sender=sender_email or '', mail=mail_string, spam=spam, request=request ) if spam: # Do not notify on identified spam return with override(settings.LANGUAGE_CODE): url = reverse('admin:foirequest_deferredmessage_changelist') mail_managers( subject, body % { 'address': secret_mail, 'url': settings.SITE_URL + url } ) def get_alternative_mail(req): name = get_name_from_number(req.pk) domains = get_foi_mail_domains() if len(domains) > 1: domains = domains[1:] random.shuffle(domains) return '%s_%s@%s' % (name, req.pk, domains[0]) def get_foirequest_from_mail(email): from .models import FoiRequest if '_' in email: name, domain = email.split('@', 1) hero, num = name.rsplit('_', 1) try: num = int(num) except ValueError: return None hero_name = get_name_from_number(num) if hero_name != hero: return None try: return FoiRequest.objects.get(pk=num) except FoiRequest.DoesNotExist: return None else: try: return FoiRequest.objects.get_by_secret_mail(email) except FoiRequest.DoesNotExist: return None def _deliver_mail(email, mail_bytes=None, manual=False): received_list = (email.to + email.cc + email.resent_to + email.resent_cc) received_list = [(r[0], r[1].lower()) for r in received_list] domains = get_foi_mail_domains() def mail_filter(x): return x[1].endswith(tuple(["@%s" % d for d in domains])) received_list = [r for r in received_list if mail_filter(r)] # normalize to first FOI_EMAIL_DOMAIN received_list = [(x[0], '@'.join( (x[1].split('@')[0], domains[0]))) for x in received_list] sender_email = email.from_[1] already = set() for received in received_list: recipient_email = received[1] if recipient_email in already: continue already.add(recipient_email) foirequest, pb = check_delivery_conditions( recipient_email, sender_email, parsed_email=email, mail_bytes=mail_bytes, manual=manual ) if foirequest is not None: add_message_from_email(foirequest, email, publicbody=pb) def add_message_from_email(foirequest, email, publicbody=None): from .services import ReceiveEmailService service = ReceiveEmailService( email, foirequest=foirequest, publicbody=publicbody ) service.process() def check_delivery_conditions(recipient_mail, sender_email, parsed_email=None, mail_bytes=b'', manual=False): from .models import DeferredMessage, FoiRequest if (not settings.FOI_EMAIL_FIXED_FROM_ADDRESS and recipient_mail == settings.FOI_EMAIL_HOST_USER): # foi mailbox email, but custom email required, dropping return None, None previous_spam_sender = DeferredMessage.objects.filter( sender=sender_email, spam=True ).exists() if previous_spam_sender: # Drop previous spammer return None, None foirequest = get_foirequest_from_mail(recipient_mail) if not foirequest: # Find previous non-spam matching request_ids = DeferredMessage.objects.filter( recipient=recipient_mail, request__isnull=False, spam=False ).values_list('request_id', flat=True) if len(set(request_ids)) != 1: # Can't do automatic matching! create_deferred( recipient_mail, mail_bytes, sender_email=sender_email, spam=None ) return None, None else: foirequest = FoiRequest.objects.get(id=list(request_ids)[0]) pb = None if not manual: if foirequest.closed: # Request is closed and will not receive messages return None, None # Check for spam pb = get_publicbody_for_email( sender_email, foirequest, include_deferred=True ) if pb is None: is_spammer = None if sender_email is not None: is_spammer = DeferredMessage.objects.filter( sender=sender_email, spam=True).exists() # If no spam found, treat as unknown is_spammer = is_spammer or None if parsed_email.bounce_info.is_bounce: return foirequest, None create_deferred( recipient_mail, mail_bytes, spam=is_spammer, sender_email=sender_email, subject=_('Possible Spam Mail received'), body=spam_message, request=foirequest ) return None, None return foirequest, pb @contextmanager def get_foi_mail_client(): with get_mail_client( settings.FOI_EMAIL_HOST_IMAP, settings.FOI_EMAIL_PORT_IMAP, settings.FOI_EMAIL_ACCOUNT_NAME, settings.FOI_EMAIL_ACCOUNT_PASSWORD, ssl=settings.FOI_EMAIL_USE_SSL) as mailbox: yield mailbox def _fetch_mail(flag_in_process=True) -> Iterator[Tuple[Optional[str], bytes]]: with get_foi_mail_client() as mailbox: yield from get_unread_mails(mailbox, flag=flag_in_process) def fetch_and_process(): count = 0 for mail_uid, rfc_data in _fetch_mail(flag_in_process=False): _process_mail(rfc_data, mail_uid=None) count += 1 return count def generate_foirequest_files(foirequest): pdf_generator = FoiRequestPDFGenerator(foirequest) correspondence_bytes = pdf_generator.get_pdf_bytes() yield ('%s.pdf' % foirequest.pk, correspondence_bytes, 'application/pdf') yield from get_attachments_for_package(foirequest) def get_attachments_for_package(foirequest): last_date = None date_count = 1 for message in foirequest.messages: current_date = message.timestamp.date() date_prefix = current_date.isoformat() if current_date == last_date: date_count += 1 else: date_count = 1 date_prefix += '_%d' % date_count last_date = current_date att_queryset = message.foiattachment_set.filter( is_redacted=False, is_converted=False ) for attachment in att_queryset: if not attachment.file: continue filename = '%s-%s' % (date_prefix, attachment.name) with open(attachment.file.path, 'rb') as f: yield (filename, f.read(), attachment.filetype) def package_foirequest(foirequest): zfile_obj = BytesIO() with override(settings.LANGUAGE_CODE): zfile = zipfile.ZipFile(zfile_obj, 'w') path = str(foirequest.pk) pdf_generator = FoiRequestPDFGenerator(foirequest) correspondence_bytes = pdf_generator.get_pdf_bytes() zfile.writestr('%s/%s.pdf' % (path, foirequest.pk), correspondence_bytes) atts = get_attachments_for_package(foirequest) for filename, filebytes, _ct in atts: zfile.writestr('%s/%s' % (path, filename), filebytes) zfile.close() return zfile_obj.getvalue()
# Copyright 2021 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. import argparse import contextlib import json import logging import os import sys import common import wpt_common logger = logging.getLogger(__name__) SRC_DIR = os.path.abspath( os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) BUILD_ANDROID = os.path.join(SRC_DIR, 'build', 'android') BLINK_TOOLS_DIR = os.path.join( SRC_DIR, 'third_party', 'blink', 'tools') CATAPULT_DIR = os.path.join(SRC_DIR, 'third_party', 'catapult') PYUTILS = os.path.join(CATAPULT_DIR, 'common', 'py_utils') TOMBSTONE_PARSER = os.path.join(SRC_DIR, 'build', 'android', 'tombstones.py') if PYUTILS not in sys.path: sys.path.append(PYUTILS) if BLINK_TOOLS_DIR not in sys.path: sys.path.append(BLINK_TOOLS_DIR) if BUILD_ANDROID not in sys.path: sys.path.append(BUILD_ANDROID) import devil_chromium from blinkpy.web_tests.port.android import ( PRODUCTS, PRODUCTS_TO_EXPECTATION_FILE_PATHS, ANDROID_WEBLAYER, ANDROID_WEBVIEW, CHROME_ANDROID, ANDROID_DISABLED_TESTS) from devil.android import apk_helper from devil.android import device_utils from devil.android.tools import system_app from devil.android.tools import webview_app from py_utils.tempfile_ext import NamedTemporaryDirectory from pylib.local.emulator import avd class PassThroughArgs(argparse.Action): pass_through_args = [] def __call__(self, parser, namespace, values, option_string=None): if option_string: if self.nargs == 0: self.add_unique_pass_through_arg(option_string) elif self.nargs is None: self.add_unique_pass_through_arg('{}={}'.format(option_string, values)) else: raise ValueError("nargs {} not supported: {} {}".format( self.nargs, option_string, values)) @classmethod def add_unique_pass_through_arg(cls, arg): if arg not in cls.pass_through_args: cls.pass_through_args.append(arg) class WPTAndroidAdapter(wpt_common.BaseWptScriptAdapter): def __init__(self, devices): self.pass_through_wpt_args = [] self.pass_through_binary_args = [] self._metadata_dir = None self._devices = devices super(WPTAndroidAdapter, self).__init__() # Arguments from add_extra_argumentsparse were added so # its safe to parse the arguments and set self._options self.parse_args() self.output_directory = os.path.join(SRC_DIR, 'out', self.options.target) self.mojo_js_directory = os.path.join(self.output_directory, 'gen') def _wpt_report(self): env = os.environ.copy() if 'GTEST_SHARD_INDEX' in env: shard_index = int(env['GTEST_SHARD_INDEX']) return 'wpt_reports_%s_%02d.json' % (self.options.product, shard_index) else: return 'wpt_reports_%s.json' % self.options.product @property def rest_args(self): rest_args = super(WPTAndroidAdapter, self).rest_args # Update the output directory to the default if it's not set. self.maybe_set_default_isolated_script_test_output() # Here we add all of the arguments required to run WPT tests on Android. rest_args.extend([self.wpt_binary]) # By default, WPT will treat unexpected passes as errors, so we disable # that to be consistent with Chromium CI. rest_args.extend(['--no-fail-on-unexpected-pass']) if self.options.default_exclude: rest_args.extend(['--default-exclude']) # vpython has packages needed by wpt, so force it to skip the setup rest_args.extend(['--venv=' + SRC_DIR, '--skip-venv-setup']) rest_args.extend(['run', '--tests=' + wpt_common.TESTS_ROOT_DIR, '--webdriver-binary', self.options.webdriver_binary, '--symbols-path', self.output_directory, '--stackwalk-binary', TOMBSTONE_PARSER, '--headless', '--no-pause-after-test', '--no-capture-stdio', '--no-manifest-download', # Exclude webdriver tests for now. "--exclude=webdriver", "--exclude=infrastructure/webdriver", '--binary-arg=--enable-blink-features=MojoJS,MojoJSTest', '--binary-arg=--enable-blink-test-features', '--binary-arg=--disable-field-trial-config', '--enable-mojojs', '--mojojs-path=' + self.mojo_js_directory, '--binary-arg=--enable-features=DownloadService<DownloadServiceStudy', '--binary-arg=--force-fieldtrials=DownloadServiceStudy/Enabled', '--binary-arg=--force-fieldtrial-params=DownloadServiceStudy.Enabled:' 'start_up_delay_ms/0', ]) for device in self._devices: rest_args.extend(['--device-serial', device.serial]) # if metadata was created then add the metadata directory # to the list of wpt arguments if self._metadata_dir: rest_args.extend(['--metadata', self._metadata_dir]) if self.options.verbose >= 3: rest_args.extend(['--log-mach=-', '--log-mach-level=debug', '--log-mach-verbose']) if self.options.verbose >= 4: rest_args.extend(['--webdriver-arg=--verbose', '--webdriver-arg="--log-path=-"']) if self.options.log_wptreport: wpt_output = self.options.isolated_script_test_output self.wptreport = os.path.join(os.path.dirname(wpt_output), self._wpt_report()) rest_args.extend(['--log-wptreport', self.wptreport]) rest_args.extend(self.pass_through_wpt_args) return rest_args @property def browser_specific_expectations_path(self): raise NotImplementedError def _extra_metadata_builder_args(self): args = ['--additional-expectations=%s' % path for path in self.options.additional_expectations] if not self.options.ignore_browser_specific_expectations: args.extend(['--additional-expectations', self.browser_specific_expectations_path]) return args def _maybe_build_metadata(self): metadata_builder_cmd = [ sys.executable, os.path.join(wpt_common.BLINK_TOOLS_DIR, 'build_wpt_metadata.py'), '--android-product', self.options.product, '--metadata-output-dir', self._metadata_dir, '--additional-expectations', ANDROID_DISABLED_TESTS, '--use-subtest-results', ] if self.options.ignore_default_expectations: metadata_builder_cmd += [ '--ignore-default-expectations' ] metadata_builder_cmd.extend(self._extra_metadata_builder_args()) return common.run_command(metadata_builder_cmd) def run_test(self): with NamedTemporaryDirectory() as tmp_dir, self._install_apks(): self._metadata_dir = os.path.join(tmp_dir, 'metadata_dir') metadata_command_ret = self._maybe_build_metadata() if metadata_command_ret != 0: return metadata_command_ret # If there is no metadata then we need to create an # empty directory to pass to wptrunner if not os.path.exists(self._metadata_dir): os.makedirs(self._metadata_dir) return super(WPTAndroidAdapter, self).run_test() def _install_apks(self): raise NotImplementedError def clean_up_after_test_run(self): # Avoid having a dangling reference to the temp directory # which was deleted self._metadata_dir = None def add_extra_arguments(self, parser): # TODO: |pass_through_args| are broke and need to be supplied by way of # --binary-arg". class BinaryPassThroughArgs(PassThroughArgs): pass_through_args = self.pass_through_binary_args class WPTPassThroughArgs(PassThroughArgs): pass_through_args = self.pass_through_wpt_args # Add this so that product argument does not go in self._rest_args # when self.parse_args() is called parser.add_argument('--target', '-t', default='Release', help='Specify the target build subdirectory under' ' src/out/.') parser.add_argument('--product', help=argparse.SUPPRESS) parser.add_argument('--webdriver-binary', required=True, help='Path of the webdriver binary. It needs to have' ' the same major version as the apk.') parser.add_argument('--additional-expectations', action='append', default=[], help='Paths to additional test expectations files.') parser.add_argument('--ignore-default-expectations', action='store_true', help='Do not use the default set of' ' TestExpectations files.') parser.add_argument('--ignore-browser-specific-expectations', action='store_true', default=False, help='Ignore browser specific expectation files.') parser.add_argument('--verbose', '-v', action='count', default=0, help='Verbosity level.') parser.add_argument('--repeat', action=WPTPassThroughArgs, type=int, help='Number of times to run the tests.') parser.add_argument('--include', metavar='TEST_OR_DIR', action=WPTPassThroughArgs, help='Test(s) to run, defaults to run all tests.') parser.add_argument('--include-file', action=WPTPassThroughArgs, help='A file listing test(s) to run') parser.add_argument('--default-exclude', action='store_true', default=False, help="Only run the tests explicitly given in arguments." "No tests will run if the list is empty, and the " "program will exit with status code 0.") parser.add_argument('--list-tests', action=WPTPassThroughArgs, nargs=0, help="Don't run any tests, just print out a list of" ' tests that would be run.') parser.add_argument('--webdriver-arg', action=WPTPassThroughArgs, help='WebDriver args.') parser.add_argument('--log-wptreport', action='store_true', default=False, help="Generates a test report in JSON format.") parser.add_argument('--log-raw', metavar='RAW_REPORT_FILE', action=WPTPassThroughArgs, help="Log raw report.") parser.add_argument('--log-html', metavar='HTML_REPORT_FILE', action=WPTPassThroughArgs, help="Log html report.") parser.add_argument('--log-xunit', metavar='XUNIT_REPORT_FILE', action=WPTPassThroughArgs, help="Log xunit report.") parser.add_argument('--enable-features', action=BinaryPassThroughArgs, help='Chromium features to enable during testing.') parser.add_argument('--disable-features', action=BinaryPassThroughArgs, help='Chromium features to disable during testing.') parser.add_argument('--disable-field-trial-config', action=BinaryPassThroughArgs, help='Disable test trials for Chromium features.') parser.add_argument('--force-fieldtrials', action=BinaryPassThroughArgs, help='Force trials for Chromium features.') parser.add_argument('--force-fieldtrial-params', action=BinaryPassThroughArgs, help='Force trial params for Chromium features.') add_emulator_args(parser) class WPTWeblayerAdapter(WPTAndroidAdapter): WEBLAYER_SHELL_PKG = 'org.chromium.weblayer.shell' WEBLAYER_SUPPORT_PKG = 'org.chromium.weblayer.support' @contextlib.contextmanager def _install_apks(self): install_weblayer_shell_as_needed = _maybe_install_user_apk( self._devices, self.options.weblayer_shell, self.WEBLAYER_SHELL_PKG) install_weblayer_support_as_needed = _maybe_install_user_apk( self._devices, self.options.weblayer_support, self.WEBLAYER_SUPPORT_PKG) install_webview_provider_as_needed = _maybe_install_webview_provider( self._devices, self.options.webview_provider) with install_weblayer_shell_as_needed, \ install_weblayer_support_as_needed, \ install_webview_provider_as_needed: yield @property def browser_specific_expectations_path(self): return PRODUCTS_TO_EXPECTATION_FILE_PATHS[ANDROID_WEBLAYER] def add_extra_arguments(self, parser): super(WPTWeblayerAdapter, self).add_extra_arguments(parser) parser.add_argument('--weblayer-shell', help='WebLayer Shell apk to install.') parser.add_argument('--weblayer-support', help='WebLayer Support apk to install.') parser.add_argument('--webview-provider', help='Webview provider apk to install.') @property def rest_args(self): args = super(WPTWeblayerAdapter, self).rest_args args.append('--test-type=testharness') args.append(ANDROID_WEBLAYER) return args class WPTWebviewAdapter(WPTAndroidAdapter): def __init__(self, devices): super(WPTWebviewAdapter, self).__init__(devices) if self.options.system_webview_shell is not None: self.system_webview_shell_pkg = apk_helper.GetPackageName( self.options.system_webview_shell) else: self.system_webview_shell_pkg = 'org.chromium.webview_shell' def _install_webview_from_release(self, serial, channel): path = os.path.join(SRC_DIR, 'clank', 'bin', 'install_webview.py') command = [sys.executable, path, '-s', serial, '--channel', channel] return common.run_command(command) @contextlib.contextmanager def _install_apks(self): if self.options.release_channel: self._install_webview_from_release(self._device.serial, self.options.release_channel) install_shell_as_needed = _no_op() install_webview_provider_as_needed = _no_op() else: install_shell_as_needed = _maybe_install_user_apk( self._devices, self.options.system_webview_shell, self.system_webview_shell_pkg) install_webview_provider_as_needed = _maybe_install_webview_provider( self._devices, self.options.webview_provider) with install_shell_as_needed, install_webview_provider_as_needed: yield @property def browser_specific_expectations_path(self): return PRODUCTS_TO_EXPECTATION_FILE_PATHS[ANDROID_WEBVIEW] def add_extra_arguments(self, parser): super(WPTWebviewAdapter, self).add_extra_arguments(parser) parser.add_argument('--system-webview-shell', help=('System WebView Shell apk to install. If not ' 'specified then the on-device WebView apk ' 'will be used.')) parser.add_argument('--webview-provider', help='Webview provider APK to install.') parser.add_argument('--release-channel', default=None, help='Using WebView from release channel.') @property def rest_args(self): args = super(WPTWebviewAdapter, self).rest_args args.extend(['--package-name', self.system_webview_shell_pkg]) args.append(ANDROID_WEBVIEW) return args class WPTClankAdapter(WPTAndroidAdapter): @contextlib.contextmanager def _install_apks(self): install_clank_as_needed = _maybe_install_user_apk( self._devices, self.options.chrome_apk) with install_clank_as_needed: yield @property def browser_specific_expectations_path(self): return PRODUCTS_TO_EXPECTATION_FILE_PATHS[CHROME_ANDROID] def add_extra_arguments(self, parser): super(WPTClankAdapter, self).add_extra_arguments(parser) parser.add_argument( '--chrome-apk', help='Chrome apk to install.') parser.add_argument( '--chrome-package-name', help=('The package name of Chrome to test,' ' defaults to that of the compiled Chrome apk.')) @property def rest_args(self): args = super(WPTClankAdapter, self).rest_args if not self.options.chrome_package_name and not self.options.chrome_apk: raise Exception('Either the --chrome-package-name or --chrome-apk ' 'command line arguments must be used.') if not self.options.chrome_package_name: self.options.chrome_package_name = apk_helper.GetPackageName( self.options.chrome_apk) logger.info("Using Chrome apk's default package %s." % self.options.chrome_package_name) args.extend(['--package-name', self.options.chrome_package_name]) # add the product postional argument args.append(CHROME_ANDROID) return args def add_emulator_args(parser): parser.add_argument( '--avd-config', type=os.path.realpath, help='Path to the avd config textpb. ' '(See //tools/android/avd/proto/ for message definition' ' and existing textpb files.)') parser.add_argument( '--emulator-window', action='store_true', default=False, help='Enable graphical window display on the emulator.') parser.add_argument( '-j', '--processes', dest='processes', type=int, default=1, help='Number of emulator to run.') @contextlib.contextmanager def get_device(args): with get_devices(args) as devices: yield None if not devices else devices[0] @contextlib.contextmanager def get_devices(args): instances = [] try: if args.avd_config: avd_config = avd.AvdConfig(args.avd_config) logger.warning('Install emulator from ' + args.avd_config) avd_config.Install() for _ in range(max(args.processes, 1)): instance = avd_config.CreateInstance() instance.Start(writable_system=True, window=args.emulator_window) instances.append(instance) #TODO(weizhong): when choose device, make sure abi matches with target devices = device_utils.DeviceUtils.HealthyDevices() if devices: yield devices else: yield finally: for instance in instances: instance.Stop() def _maybe_install_webview_provider(devices, apk): if apk: logger.info('Will install WebView apk at ' + apk) @contextlib.contextmanager def use_webview_provider(devices, apk): with contextlib.ExitStack() as stack: for device in devices: stack.enter_context(webview_app.UseWebViewProvider(device, apk)) yield return use_webview_provider(devices, apk) else: return _no_op() def _maybe_install_user_apk(devices, apk, expected_pkg=None): """contextmanager to install apk on device. Args: device: DeviceUtils instance on which to install the apk. apk: Apk file path on host. expected_pkg: Optional, check that apk's package name matches. Returns: If apk evaluates to false, returns a do-nothing contextmanager. Otherwise, returns a contextmanager to install apk on device. """ if apk: pkg = apk_helper.GetPackageName(apk) if expected_pkg and pkg != expected_pkg: raise ValueError('{} has incorrect package name: {}, expected {}.'.format( apk, pkg, expected_pkg)) install_as_needed = _app_installed(devices, apk, pkg) logger.info('Will install ' + pkg + ' at ' + apk) else: install_as_needed = _no_op() return install_as_needed @contextlib.contextmanager def _app_installed(devices, apk, pkg): for device in devices: device.Install(apk) try: yield finally: for device in devices: device.Uninstall(pkg) # Dummy contextmanager to simplify multiple optional managers. @contextlib.contextmanager def _no_op(): yield
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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 hessian experiment.""" import numpy as np import os import tempfile import tensorflow as tf import hessian_experiment def _default_end_of_input(sess, train_op): sess.run(train_op) return True class HessianExperimentTest(tf.test.TestCase): def _setup_quadratic(self, num_batches=1000, batch_size=2): x = tf.get_variable('x', initializer=[2.0, 1.0, 1.0, 0.5]) # Expected loss is 0.5 * (36 + 4 + 1) = 20.5 # Expected gradient is # Hessian should be diag([9.0, 4.0, 1.0, 0.0]). std = np.array([3.0, 2.0, 1.0, 0.0]).astype(np.float32) np.random.seed(24601) def _generator(): for _ in xrange(num_batches): yield np.random.randn(batch_size, 4).astype(np.float32) * std ds = tf.data.Dataset.from_generator( _generator, output_types=tf.float32, output_shapes=[batch_size, 4]) iterator = ds.make_initializable_iterator() elem = iterator.get_next() # The stochastic optimization problem is 0.5 * E(z^T x)^2 loss = 0.5 * tf.reduce_sum(tf.square(elem * x)) / tf.to_float(batch_size) temp_dir = tempfile.mkdtemp() return x, elem, loss, temp_dir, iterator def test_variables(self): _, _, loss, temp_dir, _ = self._setup_quadratic() hessian_experiment.HessianExperiment( loss, 0, 2, temp_dir, _default_end_of_input) # For hessian, we store a counter, an accumulator and a final value. self.assertEqual(3, len( [y for y in tf.global_variables() if y.op.name.startswith('hessian/')])) # One done token per worker. self.assertEqual(2, len([y for y in tf.global_variables() if y.op.name.startswith('should_run')])) def test_saver(self): x, _, loss, temp_dir, iterator = self._setup_quadratic() normal_saver = tf.train.Saver([x]) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) sess.run(iterator.initializer) normal_saver.save(sess, os.path.join(temp_dir, 'model.ckpt'), global_step=0) experiment = hessian_experiment.HessianExperiment( loss, 0, 1, temp_dir, _default_end_of_input) # We must make a saver before making an init_fn. with self.assertRaises(ValueError): dummy_init_fn = experiment.get_init_fn() saver = experiment.get_saver(tf.train.latest_checkpoint(temp_dir)) init_fn = experiment.get_init_fn() assign_x = tf.assign(x, [2.0, 2.0, 2.0, 2.0]) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) sess.run(assign_x) # Make sure that the x variable has been assigned correctly. self.assertAllClose([2.0, 2.0, 2.0, 2.0], sess.run(x)) init_fn(sess) # Test that the init_fn restores the x variable. self.assertAllClose([2.0, 1.0, 1.0, 0.5], sess.run(x)) saver.save(sess, os.path.join(temp_dir, 'model.ckpt'), global_step=24601) saver.save(sess, os.path.join(temp_dir, 'model.ckpt'), global_step=24602) saver.save(sess, os.path.join(temp_dir, 'model.ckpt'), global_step=24603) # Make sure that the saver counter works, and ignores global step. self.assertEqual(os.path.join(temp_dir, 'model.ckpt-2'), tf.train.latest_checkpoint(temp_dir)) def test_single_worker(self): num_batches = 1000 x, _, loss, temp_dir, iterator = self._setup_quadratic( num_batches=num_batches) x_saver = tf.train.Saver([x]) def end_of_input(sess, train_op): try: sess.run(train_op) except tf.errors.OutOfRangeError: self.assertEqual(sess.run( experiment.accumulator('hessian').counter('x')), 1000.0) sess.run(iterator.initializer) return True return False experiment = hessian_experiment.HessianExperiment( loss, 0, 1, temp_dir, end_of_input) # We'll populate this checkpoint with x_saver below. experiment.get_saver(os.path.join(temp_dir, 'x-0')) init_fn = experiment.get_init_fn() train_fn = experiment.get_train_fn() with self.test_session() as sess: # The usual sequence is init_op and then init_fn. sess.run(tf.global_variables_initializer()) sess.run(iterator.initializer) x_saver.save(sess, os.path.join(temp_dir, 'x'), global_step=0) init_fn(sess) for _ in range(num_batches): train_fn(sess, None, None) # Estimate loss, gradient and hessian ourselves. accumulator = np.array(sess.run( experiment.accumulator('loss').accumulator_value('loss'))) weight = np.array(sess.run( experiment.accumulator('loss').counter('loss'))) self.assertAllClose(accumulator / weight, 20.5, atol=0.5) accumulator = np.array(sess.run( experiment.accumulator('gradient').accumulator_value('x'))) weight = np.array(sess.run( experiment.accumulator('gradient').counter('x'))) self.assertAllClose(accumulator / weight, [18.0, 4.0, 1.0, 0.0], atol=1.0) accumulators = np.array(sess.run( experiment.accumulator('hessian').accumulator_value('x'))) weights = np.array(sess.run( experiment.accumulator('hessian').counter('x'))) self.assertAllClose(accumulators/weights, [9.0, 4.0, 1.0, 0.0], atol=1.0) # Runs finalize operations. train_fn(sess, None, None) train_fn(sess, None, None) accumulators = np.array(sess.run( experiment.accumulator('hessian').accumulator_value('x'))) weights = np.array(sess.run( experiment.accumulator('hessian').counter('x'))) # Check whether the new phase has started correctly, and whether we're # still able to accumulate accurate values for both hessian vector # products and weights. self.assertAllClose(np.squeeze(accumulators), [9.0, 4.0, 1.0, 0.0], rtol=3.0) self.assertAllClose(np.squeeze(weights), 1.0) def test_termination(self): num_batches = 8 x, _, loss, temp_dir, iterator = self._setup_quadratic( num_batches=num_batches) x_saver = tf.train.Saver([x]) experiment = hessian_experiment.HessianExperiment( loss, 0, 1, temp_dir, _default_end_of_input, max_num_phases=2) # We'll populate this checkpoint with x_saver below. experiment.get_saver(os.path.join(temp_dir, 'x-0')) init_fn = experiment.get_init_fn() train_fn = experiment.get_train_fn() with self.test_session() as sess: # The usual sequence is init_op and then init_fn. sess.run(tf.global_variables_initializer()) sess.run(iterator.initializer) x_saver.save(sess, os.path.join(temp_dir, 'x'), global_step=0) init_fn(sess) train_fn(sess, None, None) train_fn(sess, None, None) with self.assertRaises(tf.errors.OutOfRangeError): train_fn(sess, None, None) def test_fisher(self): x = tf.get_variable('x', initializer=[4.0, 2.0, 1.0]) y = tf.get_variable('y', initializer=[1.0, 1.0, 1.0]) loss = 0.5 * (tf.reduce_sum(tf.square(x)) + tf.reduce_sum(tf.square(y))) x_saver = tf.train.Saver([x, y]) temp_dir = tempfile.mkdtemp() experiment = hessian_experiment.HessianExperiment( loss, 0, 1, temp_dir, _default_end_of_input, matrix_type='fisher') # We'll populate this checkpoint with x_saver below. experiment.get_saver(os.path.join(temp_dir, 'x-0')) init_fn = experiment.get_init_fn() train_fn = experiment.get_train_fn() with self.test_session() as sess: # The usual sequence is init_op and then init_fn. sess.run(tf.global_variables_initializer()) x_saver.save(sess, os.path.join(temp_dir, 'x'), global_step=0) init_fn(sess) for _ in range(10): train_fn(sess, None, None) accumulators = np.array(sess.run( experiment.accumulator('fisher').accumulator_value('x'))) weights = np.array(sess.run( experiment.accumulator('fisher').counter('x'))) train_fn(sess, None, None) self.assertAllClose(np.squeeze(accumulators/np.expand_dims(weights, -1)), [40.0, 20.0, 10.0]) if __name__ == '__main__': tf.test.main()
# -*- coding: utf-8 -*- """ Sahana Eden Hospital Management System Model @copyright: 2009-2013 (c) Sahana Software Foundation @license: MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ __all__ = ["HospitalDataModel", "CholeraTreatmentCapabilityModel", "HospitalActivityReportModel", "hms_hospital_rheader" ] from gluon import * from gluon.storage import Storage from gluon.dal import Row from ..s3 import * from s3layouts import S3AddResourceLink # ============================================================================= class HospitalDataModel(S3Model): names = ["hms_hospital", "hms_contact", "hms_bed_capacity", "hms_services", "hms_image", "hms_resources", "hms_hospital_id" ] def model(self): T = current.T db = current.db settings = current.deployment_settings person_id = self.pr_person_id location_id = self.gis_location_id organisation_id = self.org_organisation_id human_resource_id = self.hrm_human_resource_id messages = current.messages NONE = messages["NONE"] UNKNOWN_OPT = messages.UNKNOWN_OPT add_components = self.add_components configure = self.configure crud_strings = current.response.s3.crud_strings define_table = self.define_table super_link = self.super_link # --------------------------------------------------------------------- # Hospitals # # Use government-assigned UUIDs instead of internal UUIDs HMS_HOSPITAL_USE_GOVUUID = True hms_facility_type_opts = { 1: T("Hospital"), 2: T("Field Hospital"), 3: T("Specialized Hospital"), 11: T("Health center"), 12: T("Health center with beds"), 13: T("Health center without beds"), 21: T("Dispensary"), 31: T("Long-term care"), 98: T("Other"), 99: T("Unknown"), } #: Facility Type Options # Status opts defined here for use in Search widgets hms_facility_status_opts = { 1: T("Normal"), 2: T("Compromised"), 3: T("Evacuating"), 4: T("Closed"), 99: T("No Response") } #: Facility Status Options hms_power_supply_type_opts = { 1: T("Grid"), 2: T("Generator"), 98: T("Other"), 99: T("None"), } #: Power Supply Type Options tablename = "hms_hospital" define_table(tablename, super_link("doc_id", "doc_entity"), super_link("pe_id", "pr_pentity"), super_link("site_id", "org_site"), Field("paho_uuid", unique=True, length=128, readable=False, writable=False, requires = IS_EMPTY_OR(IS_NOT_ONE_OF(db, "%s.paho_uuid" % tablename)), label = T("PAHO UID")), # UID assigned by Local Government Field("gov_uuid", unique=True, length=128, readable=False, writable=False, requires = IS_EMPTY_OR( IS_NOT_ONE_OF(db, "%s.gov_uuid" % tablename) ), label = T("Government UID")), # Alternate ids found in data feeds #Field("other_ids", # length=128), # Name of the facility Field("name", notnull=True, length=64, # Mayon compatibility label = T("Name")), # Alternate name, or name in local language Field("aka1", label = T("Other Name")), # Alternate name, or name in local language Field("aka2", readable=False, writable=False, label = T("Other Name")), # Mayon compatibility Field("code", length=10, #notnull=True, unique=True, label=T("Code")), Field("facility_type", "integer", requires = IS_EMPTY_OR( IS_IN_SET(hms_facility_type_opts) ), default = 1, label = T("Facility Type"), represent = lambda opt: \ hms_facility_type_opts.get(opt, NONE)), organisation_id(), location_id(), # Address fields: # @todo: Deprecate these & use location_id in HAVE export Field("address", label = T("Address")), Field("postcode", label = settings.get_ui_label_postcode()), Field("city"), Field("phone_exchange", label = T("Phone/Exchange (Switchboard)"), requires = IS_EMPTY_OR(s3_phone_requires)), Field("phone_business", label = T("Phone/Business"), requires = IS_EMPTY_OR(s3_phone_requires)), Field("phone_emergency", label = T("Phone/Emergency"), requires = IS_EMPTY_OR(s3_phone_requires)), Field("website", label=T("Website"), requires = IS_EMPTY_OR(IS_URL()), represent = s3_url_represent), Field("email", label = T("Email"), requires = IS_EMPTY_OR(IS_EMAIL())), Field("fax", label = T("Fax"), requires = IS_EMPTY_OR(s3_phone_requires)), Field("total_beds", "integer", #readable = False, writable = False, represent = lambda v: NONE if v is None else v, requires = IS_EMPTY_OR(IS_INT_IN_RANGE(0, 9999)), label = T("Total Beds")), Field("available_beds", "integer", #readable = False, writable = False, represent = lambda v: NONE if v is None else v, requires = IS_EMPTY_OR(IS_INT_IN_RANGE(0, 9999)), label = T("Available Beds")), Field("doctors", "integer", label = T("Number of doctors"), requires = IS_EMPTY_OR( IS_INT_IN_RANGE(0, 9999)), represent = lambda v: IS_INT_AMOUNT.represent(v)), Field("nurses", "integer", label = T("Number of nurses"), requires = IS_EMPTY_OR( IS_INT_IN_RANGE(0, 9999)), represent = lambda v: IS_INT_AMOUNT.represent(v)), Field("non_medical_staff", "integer", requires = IS_EMPTY_OR( IS_INT_IN_RANGE(0, 9999)), label = T("Number of non-medical staff"), represent = lambda v: IS_INT_AMOUNT.represent(v)), Field("obsolete", "boolean", label = T("Obsolete"), represent = lambda opt: \ (opt and [T("Obsolete")] or [NONE])[0], default = False, readable = False, writable = False), s3_comments(), *s3_meta_fields()) # CRUD Strings ADD_HOSPITAL = T("Create Hospital") crud_strings[tablename] = Storage( label_create = ADD_HOSPITAL, title_display = T("Hospital Details"), title_list = T("Hospitals"), title_update = T("Edit Hospital"), title_map = T("Map of Hospitals"), label_list_button = T("List Hospitals"), label_delete_button = T("Delete Hospital"), msg_record_created = T("Hospital information added"), msg_record_modified = T("Hospital information updated"), msg_record_deleted = T("Hospital information deleted"), msg_list_empty = T("No Hospitals currently registered")) filter_widgets = [ S3TextFilter(["name", "code", "comments", "organisation_id$name", "organisation_id$acronym", "location_id$name", "location_id$L1", "location_id$L2", ], label=T("Name"), _class="filter-search", ), S3OptionsFilter("facility_type", label=T("Type"), represent="%(name)s", widget="multiselect", #cols=3, #hidden=True, ), S3LocationFilter("location_id", label=T("Location"), levels=["L0", "L1", "L2"], widget="multiselect", #cols=3, #hidden=True, ), S3OptionsFilter("status.facility_status", label=T("Status"), options = hms_facility_status_opts, #represent="%(name)s", widget="multiselect", #cols=3, #hidden=True, ), S3OptionsFilter("status.power_supply_type", label=T("Power"), options = hms_power_supply_type_opts, #represent="%(name)s", widget="multiselect", #cols=3, #hidden=True, ), S3RangeFilter("total_beds", label=T("Total Beds"), #represent="%(name)s", #hidden=True, ), ] report_fields = ["name", (T("Type"), "facility_type"), #"organisation_id", "location_id$L1", "location_id$L2", "location_id$L3", (T("Status"), "status.facility_status"), "status.power_supply_type", "total_beds", "available_beds", ] # Resource configuration configure(tablename, deduplicate = self.hms_hospital_duplicate, filter_widgets = filter_widgets, list_fields = ["id", #"gov_uuid", "name", "facility_type", "status.facility_status", "status.power_supply_type", #"organisation_id", "location_id$L1", "location_id$L2", "location_id$L3", #"phone_exchange", "total_beds", "available_beds", ], onaccept = self.hms_hospital_onaccept, report_options = Storage( rows=report_fields, cols=report_fields, fact=report_fields, defaults=Storage(rows="location_id$L2", cols="status.facility_status", fact="count(name)", totals=True) ), super_entity = ("org_site", "doc_entity", "pr_pentity"), ) # Reusable field hms_hospital_id_comment = S3AddResourceLink(c="hms", f="hospital", label=ADD_HOSPITAL, title=T("Hospital"), tooltip=T("If you don't see the Hospital in the list, you can add a new one by clicking link 'Create Hospital'.")) hospital_id = S3ReusableField("hospital_id", "reference %s" % tablename, sortby="name", requires = IS_EMPTY_OR( IS_ONE_OF(db, "hms_hospital.id", self.hms_hospital_represent )), represent = self.hms_hospital_represent, label = T("Hospital"), comment = hms_hospital_id_comment, ondelete = "RESTRICT") # Components single = dict(joinby="hospital_id", multiple=False) multiple = "hospital_id" add_components(tablename, hms_status=single, hms_contact=multiple, hms_bed_capacity=multiple, hms_services=single, hms_resources=multiple, ) # Optional components if settings.get_hms_track_ctc(): add_components(tablename, hms_ctc=single) if settings.get_hms_activity_reports(): add_components(tablename, hms_activity=multiple) # --------------------------------------------------------------------- # Hospital status # hms_resource_status_opts = { 1: T("Adequate"), 2: T("Insufficient") } #: Resource Status Options hms_clinical_status_opts = { 1: T("Normal"), 2: T("Full"), 3: T("Closed") } #: Clinical Status Options hms_facility_damage_opts = { 1: T("Flooding"), 2: T("Power Outage"), } #: Facility Damage Options hms_gas_supply_type_opts = { 98: T("Other"), 99: T("None"), } #: Gas Supply Type Options hms_security_status_opts = { 1: T("Normal"), 2: T("Elevated"), 3: T("Restricted Access"), 4: T("Lockdown"), 5: T("Quarantine"), 6: T("Closed") } #: Security Status Options hms_ems_traffic_opts = { 1: T("Normal"), 2: T("Advisory"), 3: T("Closed"), 4: T("Not Applicable") } #: EMS Traffic Options hms_or_status_opts = { 1: T("Normal"), #2: T("Advisory"), 3: T("Closed"), 4: T("Not Applicable") } #: Operating Room Status Options hms_morgue_status_opts = { 1: T("Open"), 2: T("Full"), 3: T("Exceeded"), 4: T("Closed") } #: Morgue Status Options def hms_facility_damage_multirepresent(opt): """ Multi Represent """ set = hms_facility_damage_opts if isinstance(opt, (list, tuple)): opts = opt try: vals = [str(set.get(o)) for o in opts] except: return None elif isinstance(opt, int): opts = [opt] vals = str(set.get(opt)) else: return NONE if len(opts) > 1: vals = ", ".join(vals) else: vals = len(vals) and vals[0] or "" return vals tablename = "hms_status" define_table(tablename, hospital_id(ondelete="CASCADE"), # Status of the facility and facility operations Field("facility_status", "integer", requires = IS_EMPTY_OR( IS_IN_SET(hms_facility_status_opts)), label = T("Facility Status"), represent = lambda opt: \ NONE if opt is None else \ hms_facility_status_opts.get(opt, UNKNOWN_OPT)), s3_date("date_reopening", label=T("Estimated Reopening Date"), ), Field("facility_operations", "integer", requires = IS_EMPTY_OR( IS_IN_SET(hms_resource_status_opts)), label = T("Facility Operations"), represent = lambda opt: \ NONE if opt is None else \ hms_resource_status_opts.get(opt, UNKNOWN_OPT)), # Facility Status Details Field("damage", "list:integer", label=T("Damage sustained"), requires=IS_EMPTY_OR( IS_IN_SET(hms_facility_damage_opts, multiple=True)), widget=CheckboxesWidgetS3.widget, represent = hms_facility_damage_multirepresent, ), Field("power_supply_type", "integer", label=T("Power Supply Type"), requires=IS_EMPTY_OR( IS_IN_SET(hms_power_supply_type_opts, zero=None)), represent = lambda opt: \ NONE if opt is None else \ hms_power_supply_type_opts.get(opt, UNKNOWN_OPT)), Field("gas_supply_type", "integer", label=T("Gas Supply Type"), requires=IS_EMPTY_OR( IS_IN_SET(hms_gas_supply_type_opts, zero=None)), represent = lambda opt: \ NONE if opt is None else \ hms_gas_supply_type_opts.get(opt, UNKNOWN_OPT)), Field("gas_supply_capacity", "integer", label=T("Gas Supply Left (in hours)"), requires=IS_EMPTY_OR(IS_INT_IN_RANGE(0, 999999))), # Clinical status and clinical operations Field("clinical_status", "integer", requires = IS_EMPTY_OR( IS_IN_SET(hms_clinical_status_opts)), label = T("Clinical Status"), represent = lambda opt: \ NONE if opt is None else \ hms_clinical_status_opts.get(opt, UNKNOWN_OPT)), Field("clinical_operations", "integer", requires = IS_EMPTY_OR( IS_IN_SET(hms_resource_status_opts)), label = T("Clinical Operations"), represent = lambda opt: \ NONE if opt is None else \ hms_resource_status_opts.get(opt, UNKNOWN_OPT)), Field("security_status", "integer", requires = IS_EMPTY_OR( IS_IN_SET(hms_security_status_opts)), label = T("Security Status"), represent = lambda opt: \ NONE if opt is None else \ hms_security_status_opts.get(opt, UNKNOWN_OPT)), # Staffing status Field("staffing", "integer", requires = IS_EMPTY_OR( IS_IN_SET(hms_resource_status_opts)), label = T("Staffing Level"), represent = lambda opt: \ NONE if opt is None else \ hms_resource_status_opts.get(opt, UNKNOWN_OPT)), # Emergency Room Status Field("ems_status", "integer", requires = IS_EMPTY_OR( IS_IN_SET(hms_ems_traffic_opts)), label = T("ER Status"), represent = lambda opt: \ NONE if opt is None else \ hms_ems_traffic_opts.get(opt, UNKNOWN_OPT)), Field("ems_reason", length=128, label = T("ER Status Reason")), # Operating Room Status Field("or_status", "integer", requires = IS_EMPTY_OR( IS_IN_SET(hms_or_status_opts)), label = T("OR Status"), represent = lambda opt: \ NONE if opt is None else \ hms_or_status_opts.get(opt, UNKNOWN_OPT)), Field("or_reason", length=128, label = T("OR Status Reason")), # Morgue status and capacity Field("morgue_status", "integer", requires = IS_EMPTY_OR( IS_IN_SET(hms_morgue_status_opts)), label = T("Morgue Status"), represent = lambda opt: \ NONE if opt is None else \ hms_morgue_status_opts.get(opt, UNKNOWN_OPT)), Field("morgue_units", "integer", requires = IS_EMPTY_OR(IS_INT_IN_RANGE(0, 9999)), label = T("Morgue Units Available"), represent = lambda v: IS_INT_AMOUNT.represent(v)), Field("access_status", "text", label = T("Road Conditions")), *s3_meta_fields()) # CRUD Strings crud_strings[tablename] = Storage( label_create = T("Create Status Report"), title_display = T("Status Report"), title_list = T("Status Report"), title_update = T("Edit Status Report"), label_list_button = T("List Status Reports"), msg_record_created = T("Status Report added"), msg_record_modified = T("Status Report updated"), msg_record_deleted = T("Status Report deleted"), msg_list_empty = T("No status information currently available")) # --------------------------------------------------------------------- # Contacts # tablename = "hms_contact" define_table(tablename, hospital_id(ondelete="CASCADE"), person_id(label = T("Contact"), empty=False), Field("title", label = T("Job Title")), Field("phone", label = T("Phone"), requires = IS_EMPTY_OR(s3_phone_requires)), Field("mobile", label = settings.get_ui_label_mobile_phone(), requires = IS_EMPTY_OR(s3_phone_requires)), Field("email", label = T("Email"), requires = IS_EMPTY_OR(IS_EMAIL())), Field("fax", label = T("Fax"), requires = IS_EMPTY_OR(s3_phone_requires)), Field("skype", label = T("Skype ID")), Field("website", label=T("Website")), *s3_meta_fields()) # CRUD Strings crud_strings[tablename] = Storage( label_create = T("Create Contact"), title_display = T("Contact Details"), title_list = T("Contacts"), title_update = T("Edit Contact"), label_list_button = T("List Contacts"), msg_record_created = T("Contact information added"), msg_record_modified = T("Contact information updated"), msg_record_deleted = T("Contact information deleted"), msg_list_empty = T("No contacts currently registered")) # Resource configuration configure(tablename, mark_required = ["person_id"], list_fields=["id", "person_id", "title", "phone", "mobile", "email", "fax", "skype" ], main="person_id", extra="title") # --------------------------------------------------------------------- # Bed Capacity # hms_bed_type_opts = { 1: T("Adult ICU"), 2: T("Pediatric ICU"), 3: T("Neonatal ICU"), 4: T("Emergency Department"), 5: T("Nursery Beds"), 6: T("General Medical/Surgical"), 7: T("Rehabilitation/Long Term Care"), 8: T("Burn ICU"), 9: T("Pediatrics"), 10: T("Adult Psychiatric"), 11: T("Pediatric Psychiatric"), 12: T("Negative Flow Isolation"), 13: T("Other Isolation"), 14: T("Operating Rooms"), 15: T("Cholera Treatment"), 99: T("Other") } tablename = "hms_bed_capacity" define_table(tablename, hospital_id(ondelete="CASCADE"), Field("unit_id", length=128, unique=True, readable=False, writable=False), Field("bed_type", "integer", requires = IS_IN_SET(hms_bed_type_opts, zero=None), default = 6, label = T("Bed Type"), represent = lambda opt: \ hms_bed_type_opts.get(opt, UNKNOWN_OPT)), s3_datetime(label = T("Date of Report"), empty=False, future=0, ), Field("beds_baseline", "integer", default = 0, requires = IS_EMPTY_OR(IS_INT_IN_RANGE(0, 9999)), label = T("Baseline Number of Beds"), represent = lambda v: IS_INT_AMOUNT.represent(v)), Field("beds_available", "integer", default = 0, requires = IS_EMPTY_OR(IS_INT_IN_RANGE(0, 9999)), label = T("Available Beds"), represent = lambda v: IS_INT_AMOUNT.represent(v)), Field("beds_add24", "integer", default = 0, requires = IS_EMPTY_OR(IS_INT_IN_RANGE(0, 9999)), label = T("Additional Beds / 24hrs"), represent = lambda v: IS_INT_AMOUNT.represent(v)), s3_comments(), *s3_meta_fields()) # Field configuration # CRUD Strings crud_strings[tablename] = Storage( label_create = T("Create Bed Type"), title_display = T("Bed Capacity"), title_list = T("Bed Capacity"), title_update = T("Update Unit"), label_list_button = T("List Units"), label_delete_button = T("Delete Unit"), msg_record_created = T("Unit added"), msg_record_modified = T("Unit updated"), msg_record_deleted = T("Unit deleted"), msg_list_empty = T("No units currently registered")) # Resource configuration configure(tablename, onvalidation = self.hms_bed_capacity_onvalidation, onaccept = self.hms_bed_capacity_onaccept, ondelete = self.hms_bed_capacity_onaccept, list_fields=["id", "unit_name", "bed_type", "date", "beds_baseline", "beds_available", "beds_add24" ], main="hospital_id", extra="id") # --------------------------------------------------------------------- # Services # tablename = "hms_services" define_table(tablename, hospital_id(ondelete="CASCADE"), Field("burn", "boolean", default=False, label = T("Burn")), Field("card", "boolean", default=False, label = T("Cardiology")), Field("dial", "boolean", default=False, label = T("Dialysis")), Field("emsd", "boolean", default=False, label = T("Emergency Department")), Field("infd", "boolean", default=False, label = T("Infectious Diseases")), Field("neon", "boolean", default=False, label = T("Neonatology")), Field("neur", "boolean", default=False, label = T("Neurology")), Field("pedi", "boolean", default=False, label = T("Pediatrics")), Field("surg", "boolean", default=False, label = T("Surgery")), Field("labs", "boolean", default=False, label = T("Clinical Laboratory")), Field("tran", "boolean", default=False, label = T("Ambulance Service")), Field("tair", "boolean", default=False, label = T("Air Transport Service")), Field("trac", "boolean", default=False, label = T("Trauma Center")), Field("psya", "boolean", default=False, label = T("Psychiatrics/Adult")), Field("psyp", "boolean", default=False, label = T("Psychiatrics/Pediatric")), Field("obgy", "boolean", default=False, label = T("Obstetrics/Gynecology")), *s3_meta_fields()) # CRUD Strings crud_strings[tablename] = Storage( label_create = T("Create Service Profile"), title_display = T("Services Available"), title_list = T("Services Available"), title_update = T("Update Service Profile"), label_list_button = T("List Service Profiles"), label_delete_button = T("Delete Service Profile"), msg_record_created = T("Service profile added"), msg_record_modified = T("Service profile updated"), msg_record_deleted = T("Service profile deleted"), msg_list_empty = T("No service profile available")) # Resource configuration configure(tablename, list_fields = ["id"], main="hospital_id", extra="id") # --------------------------------------------------------------------- # Resources (multiple) - @todo: to be completed! # tablename = "hms_resources" define_table(tablename, hospital_id(ondelete="CASCADE"), Field("type"), Field("description"), Field("quantity"), s3_comments(), *s3_meta_fields()) # CRUD Strings crud_strings[tablename] = Storage( label_create = T("Report Resource"), title_display = T("Resource Details"), title_list = T("Resources"), title_update = T("Edit Resource"), label_list_button = T("List Resources"), label_delete_button = T("Delete Resource"), msg_record_created = T("Resource added"), msg_record_modified = T("Resource updated"), msg_record_deleted = T("Resource deleted"), msg_list_empty = T("No resources currently reported")) # Resource configuration configure(tablename, list_fields=["id"], main="hospital_id", extra="id") # --------------------------------------------------------------------- # Return global names to s3db # return Storage(hms_hospital_id=hospital_id) # ------------------------------------------------------------------------- def defaults(self): hospital_id = S3ReusableField("hospital_id", "integer", readable=False, writable=False) return Storage(hms_hospital_id=hospital_id) # ------------------------------------------------------------------------- @staticmethod def hms_hospital_represent(id, row=None): """ FK representation """ if row: return row.name elif not id: return current.messages["NONE"] db = current.db table = db.hms_hospital r = db(table.id == id).select(table.name, limitby = (0, 1)).first() try: return r.name except: return current.messages.UNKNOWN_OPT # ------------------------------------------------------------------------- @staticmethod def hms_hospital_duplicate(item): """ Hospital record duplicate detection, used for the deduplicate hook @param item: the S3ImportItem to check """ if item.tablename == "hms_hospital": data = item.data #org = "organisation_id" in data and data.organisation_id address = "address" in data and data.address table = item.table query = (table.name == data.name) #if org: # query = query & (table.organisation_id == org) if address: query = query & (table.address == address) row = current.db(query).select(table.id, limitby=(0, 1)).first() if row: item.id = row.id item.method = item.METHOD.UPDATE # ------------------------------------------------------------------------- @staticmethod def hms_hospital_onaccept(form): """ Update Affiliation, record ownership and component ownership """ current.s3db.org_update_affiliations("hms_hospital", form.vars) # ------------------------------------------------------------------------- @staticmethod def hms_bed_capacity_onvalidation(form): """ Bed Capacity Validation """ db = current.db htable = db.hms_hospital ctable = db.hms_bed_capacity hospital_id = ctable.hospital_id.update bed_type = form.vars.bed_type query = (ctable.hospital_id == hospital_id) & \ (ctable.bed_type == bed_type) row = db(query).select(ctable.id, limitby=(0, 1)).first() if row and str(row.id) != current.request.post_vars.id: form.errors["bed_type"] = current.T("Bed type already registered") elif "unit_id" not in form.vars: query = htable.id == hospital_id hospital = db(query).select(htable.uuid, limitby=(0, 1)).first() if hospital: form.vars.unit_id = "%s-%s" % (hospital.uuid, bed_type) # ------------------------------------------------------------------------- @staticmethod def hms_bed_capacity_onaccept(form): """ Updates the number of total/available beds of a hospital """ if isinstance(form, Row): formvars = form else: formvars = form.vars db = current.db ctable = db.hms_bed_capacity htable = db.hms_hospital query = ((ctable.id == formvars.id) & (htable.id == ctable.hospital_id)) hospital = db(query).select(htable.id, limitby=(0, 1)) if hospital: hospital = hospital.first() a_beds = ctable.beds_available.sum() t_beds = ctable.beds_baseline.sum() query = (ctable.hospital_id == hospital.id) & \ (ctable.deleted == False) count = db(query).select(a_beds, t_beds) if count: a_beds = count[0]._extra[a_beds] t_beds = count[0]._extra[t_beds] db(htable.id == hospital.id).update(total_beds=t_beds, available_beds=a_beds) # ============================================================================= class CholeraTreatmentCapabilityModel(S3Model): names = ["hms_ctc"] def model(self): T = current.T hospital_id = self.hms_hospital_id configure = self.configure crud_strings = current.response.s3.crud_strings define_table = self.define_table # --------------------------------------------------------------------- # Cholera Treatment Capability # hms_problem_types = { 1: T("Security problems"), 2: T("Hygiene problems"), 3: T("Sanitation problems"), 4: T("Improper handling of dead bodies"), 5: T("Improper decontamination"), 6: T("Understaffed"), 7: T("Lack of material"), 8: T("Communication problems"), 9: T("Information gaps") } tablename = "hms_ctc" define_table(tablename, hospital_id(ondelete="CASCADE"), Field("ctc", "boolean", default=False, represent = lambda opt: \ opt and T("yes") or T("no"), label = T("Cholera-Treatment-Center")), Field("number_of_patients", "integer", default=0, requires = IS_EMPTY_OR(IS_INT_IN_RANGE(0, 999999)), label = T("Current number of patients"), represent = lambda v: IS_INT_AMOUNT.represent(v)), Field("cases_24", "integer", default=0, requires = IS_EMPTY_OR(IS_INT_IN_RANGE(0, 999999)), label = T("New cases in the past 24h"), represent = lambda v: IS_INT_AMOUNT.represent(v)), Field("deaths_24", "integer", default=0, requires = IS_EMPTY_OR(IS_INT_IN_RANGE(0, 999999)), label = T("Deaths in the past 24h"), represent = lambda v: IS_INT_AMOUNT.represent(v)), #Field("staff_total", "integer", default=0), Field("icaths_available", "integer", default=0, requires = IS_EMPTY_OR(IS_INT_IN_RANGE(0, 99999999)), label = T("Infusion catheters available"), represent = lambda v: IS_INT_AMOUNT.represent(v)), Field("icaths_needed_24", "integer", default=0, requires = IS_EMPTY_OR(IS_INT_IN_RANGE(0, 99999999)), label = T("Infusion catheters needed per 24h"), represent = lambda v: IS_INT_AMOUNT.represent(v)), Field("infusions_available", "integer", default=0, requires = IS_EMPTY_OR(IS_INT_IN_RANGE(0, 99999999)), label = T("Infusions available"), represent = lambda v: IS_INT_AMOUNT.represent(v)), Field("infusions_needed_24", "integer", default=0, requires = IS_EMPTY_OR(IS_INT_IN_RANGE(0, 99999999)), label = T("Infusions needed per 24h"), represent = lambda v: IS_INT_AMOUNT.represent(v)), #Field("infset_available", "integer", default=0), #Field("infset_needed_24", "integer", default=0), Field("antibiotics_available", "integer", default=0, requires = IS_EMPTY_OR(IS_INT_IN_RANGE(0, 99999999)), label = T("Antibiotics available"), represent = lambda v: IS_INT_AMOUNT.represent(v)), Field("antibiotics_needed_24", "integer", default=0, requires = IS_EMPTY_OR(IS_INT_IN_RANGE(0, 99999999)), label = T("Antibiotics needed per 24h"), represent = lambda v: IS_INT_AMOUNT.represent(v)), Field("problem_types", "list:integer", requires = IS_EMPTY_OR( IS_IN_SET(hms_problem_types, zero=None, multiple=True)), represent = lambda optlist: \ optlist and ", ".join(map(str,optlist)) or T("N/A"), label = T("Current problems, categories")), Field("problem_details", "text", label = T("Current problems, details")), s3_comments(), *s3_meta_fields()) # Field configuration # @todo: make lazy table table = current.db[tablename] table.modified_on.label = T("Last updated on") table.modified_on.readable = True table.modified_by.label = T("Last updated by") table.modified_by.readable = True # CRUD Strings crud_strings[tablename] = Storage( label_create = T("Create Cholera Treatment Capability Information"), title_display = T("Cholera Treatment Capability"), title_list = T("Cholera Treatment Capability"), title_update = T("Update Cholera Treatment Capability Information"), label_list_button = T("List Statuses"), label_delete_button = T("Delete Status"), msg_record_created = T("Status added"), msg_record_modified = T("Status updated"), msg_record_deleted = T("Status deleted"), msg_list_empty = T("No status information available")) # Resource configuration configure(tablename, list_fields = ["id"], subheadings = { "Activities": "ctc", "Medical Supplies Availability": "icaths_available", "Current Problems": "problem_types", "Comments": "comments" }) # --------------------------------------------------------------------- # Return global names to s3db # return Storage() # ------------------------------------------------------------------------- def defaults(self): return Storage() # ============================================================================= class HospitalActivityReportModel(S3Model): names = ["hms_activity"] def model(self): T = current.T hospital_id = self.hms_hospital_id configure = self.configure crud_strings = current.response.s3.crud_strings define_table = self.define_table # --------------------------------------------------------------------- # Activity # is_number_of_patients = IS_EMPTY_OR(IS_INT_IN_RANGE(0, 9999)) represent_int_amount = lambda v, row=None: IS_INT_AMOUNT.represent(v) tablename = "hms_activity" define_table(tablename, hospital_id(ondelete="CASCADE"), s3_datetime(label = T("Date & Time"), empty=False, future=0), # Current Number of Patients Field("patients", "integer", requires = is_number_of_patients, default = 0, label = T("Number of Patients"), represent = represent_int_amount), # Admissions in the past 24 hours Field("admissions24", "integer", requires = is_number_of_patients, default = 0, label = T("Admissions/24hrs"), represent = represent_int_amount), # Discharges in the past 24 hours Field("discharges24", "integer", requires = is_number_of_patients, default = 0, label = T("Discharges/24hrs"), represent = represent_int_amount), # Deaths in the past 24 hours Field("deaths24", "integer", requires = is_number_of_patients, default = 0, label = T("Deaths/24hrs"), represent = represent_int_amount), Field("comment", length=128), *s3_meta_fields()) # CRUD Strings crud_strings[tablename] = Storage( label_create = T("Create Activity Report"), title_display = T("Activity Report"), title_list = T("Activity Reports"), title_update = T("Update Activity Report"), label_list_button = T("List Activity Reports"), label_delete_button = T("Delete Report"), msg_record_created = T("Report added"), msg_record_modified = T("Report updated"), msg_record_deleted = T("Report deleted"), msg_list_empty = T("No reports currently available")) # Resource configuration configure(tablename, onaccept = self.hms_activity_onaccept, list_fields=["id", "date", "patients", "admissions24", "discharges24", "deaths24", "comment"], main="hospital_id", extra="id") # --------------------------------------------------------------------- # Return global names to s3db # return Storage() # ------------------------------------------------------------------------- def defaults(self): return Storage() # ------------------------------------------------------------------------- @staticmethod def hms_activity_onaccept(form): db = current.db atable = db.hms_activity htable = db.hms_hospital query = ((atable.id == form.vars.id) & \ (htable.id == atable.hospital_id)) hospital = db(query).select(htable.id, htable.modified_on, limitby=(0, 1)).first() timestmp = form.vars.date if hospital and hospital.modified_on < timestmp: hospital.update_record(modified_on=timestmp) # ============================================================================= def hms_hospital_rheader(r, tabs=[]): """ Page header for component resources """ rheader = None if r.representation == "html": T = current.T s3db = current.s3db settings = current.deployment_settings tablename, record = s3_rheader_resource(r) if tablename == "hms_hospital" and record: if not tabs: tabs = [(T("Details"), ""), (T("Status"), "status"), (T("Contacts"), "contact"), (T("Images"), "image"), (T("Services"), "services"), (T("Bed Capacity"), "bed_capacity"), ] if settings.get_hms_activity_reports(): tabs.append((T("Activity Report"), "activity")) if settings.get_hms_track_ctc(): tabs.append((T("Cholera Treatment Capability"), "ctc")) tabs += [ (T("Staff"), "human_resource"), (T("Assign Staff"), "human_resource_site"), ] try: tabs = tabs + s3db.req_tabs(r) except: pass try: tabs = tabs + s3db.inv_tabs(r) except: pass tabs.append((T("User Roles"), "roles")) rheader_tabs = s3_rheader_tabs(r, tabs) hospital = record table = s3db.hms_hospital ltable = s3db.gis_location stable = s3db.hms_status query = (stable.hospital_id == hospital.id) s = current.db(query).select(limitby=(0, 1)).first() status = lambda k: (s is not None and [stable[k].represent(s[k])] or [T("n/a")])[0] NONE = current.messages["NONE"] total_beds = hospital.total_beds if total_beds is None: total_beds = NONE available_beds = hospital.available_beds if available_beds is None: available_beds = NONE rheader = DIV(TABLE( TR(TH("%s: " % T("Name")), hospital.name, TH("%s: " % T("Facility Status")), status("facility_status") ), TR(TH("%s: " % T("Location")), ltable[hospital.location_id] and \ ltable[hospital.location_id].name or "unknown", TH("%s: " % T("Estimated Reopening Date")), status("date_reopening") #TH("%s: " % T("EMS Status")), # status("ems_status") ), TR(TH("%s: " % T("Total Beds")), total_beds, #TH("%s: " % T("Clinical Status")), # status("clinical_status") ), TR(TH("%s: " % T("Available Beds")), available_beds, #TH("%s: " % T("Security Status")), # status("security_status") ) ), rheader_tabs) return rheader # END =========================================================================
# Copyright 2015 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. from . import steps SPEC = { 'settings': { 'build_gs_bucket': 'chromium-gpu-fyi-archive', # WARNING: src-side runtest.py is only tested with chromium CQ builders. # Usage not covered by chromium CQ is not supported and can break # without notice. 'src_side_runtest_py': True, }, 'builders': { 'GPU Win Builder': { 'chromium_config': 'chromium', 'chromium_apply_config': [ 'archive_gpu_tests', 'build_angle_deqp_tests', 'chrome_with_codecs', 'internal_gles2_conform_tests', 'mb', 'ninja_confirm_noop', ], 'gclient_config': 'chromium', 'gclient_apply_config': ['chrome_internal', 'angle_top_of_tree'], 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 32, }, 'bot_type': 'builder', 'compile_targets': [ ], 'testing': { 'platform': 'win', }, 'enable_swarming': True, 'use_isolate': True, }, 'GPU Win Builder (dbg)': { 'chromium_config': 'chromium', 'chromium_apply_config': [ 'archive_gpu_tests', 'chrome_with_codecs', 'internal_gles2_conform_tests', 'mb', 'ninja_confirm_noop', ], 'gclient_config': 'chromium', 'gclient_apply_config': ['chrome_internal', 'angle_top_of_tree'], 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Debug', 'TARGET_BITS': 32, }, 'bot_type': 'builder', 'compile_targets': [ ], 'testing': { 'platform': 'win', }, 'enable_swarming': True, 'use_isolate': True, }, 'Win7 Release (NVIDIA)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 32, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Win Builder', 'testing': { 'platform': 'win', }, 'enable_swarming': True, }, 'Win7 Debug (NVIDIA)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Debug', 'TARGET_BITS': 32, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Win Builder (dbg)', 'testing': { 'platform': 'win', }, 'enable_swarming': True, }, 'Win8 Release (NVIDIA)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 32, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Win Builder', 'testing': { 'platform': 'win', }, 'enable_swarming': True, }, 'Win8 Debug (NVIDIA)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Debug', 'TARGET_BITS': 32, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Win Builder (dbg)', 'testing': { 'platform': 'win', }, 'enable_swarming': True, }, 'Win7 Release (ATI)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 32, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Win Builder', 'testing': { 'platform': 'win', }, 'enable_swarming': True, }, 'Win7 Debug (ATI)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Debug', 'TARGET_BITS': 32, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Win Builder (dbg)', 'testing': { 'platform': 'win', }, 'enable_swarming': True, }, 'Win7 Release (Intel)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 32, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Win Builder', 'testing': { 'platform': 'win', }, # Swarming is deliberately NOT enabled on this one-off configuration. # The GPU detection wasn't initially working (crbug.com/580331), and # multiple copies of the machines have to be deployed into swarming # in order to keep up with the faster cycle time of the tests. 'enable_swarming': False, }, 'Win7 Release (NVIDIA GeForce 730)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 32, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Win Builder', 'testing': { 'platform': 'win', }, # Swarming is deliberately NOT enabled on this one-off configuration. # These new graphics cards are being tested at the moment. 'enable_swarming': False, }, 'Win7 Release (New Intel)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 32, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Win Builder', 'testing': { 'platform': 'win', }, # Swarming is deliberately NOT enabled on this one-off configuration. # This new hardware is being tested for reliability. 'enable_swarming': False, }, 'Win7 Debug (New Intel)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Debug', 'TARGET_BITS': 32, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Win Builder (dbg)', 'testing': { 'platform': 'win', }, # Swarming is deliberately NOT enabled on this one-off configuration. # This new hardware is being tested for reliability. 'enable_swarming': False, }, 'GPU Win x64 Builder': { 'chromium_config': 'chromium', 'chromium_apply_config': [ 'archive_gpu_tests', 'build_angle_deqp_tests', 'chrome_with_codecs', 'internal_gles2_conform_tests', 'mb', 'ninja_confirm_noop', ], 'gclient_config': 'chromium', 'gclient_apply_config': ['chrome_internal', 'angle_top_of_tree'], 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 64, }, 'bot_type': 'builder', 'compile_targets': [ ], 'testing': { 'platform': 'win', }, 'enable_swarming': True, 'use_isolate': True, }, 'GPU Win x64 Builder (dbg)': { 'chromium_config': 'chromium', 'chromium_apply_config': [ 'archive_gpu_tests', 'chrome_with_codecs', 'internal_gles2_conform_tests', 'mb', 'ninja_confirm_noop', ], 'gclient_config': 'chromium', 'gclient_apply_config': ['chrome_internal', 'angle_top_of_tree'], 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Debug', 'TARGET_BITS': 64, }, 'bot_type': 'builder', 'compile_targets': [ ], 'testing': { 'platform': 'win', }, 'enable_swarming': True, 'use_isolate': True, }, 'Win7 x64 Release (NVIDIA)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 64, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Win x64 Builder', 'testing': { 'platform': 'win', }, 'enable_swarming': True, }, 'Win7 x64 Debug (NVIDIA)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Debug', 'TARGET_BITS': 64, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Win x64 Builder (dbg)', 'testing': { 'platform': 'win', }, 'enable_swarming': True, }, 'GPU Win Clang Builder (dbg)': { # This bot is on the chromium.gpu.fyi waterfall to help ensure # that ANGLE rolls aren't reverted due to Clang build failures # on Windows. We don't run the binaries that are built on this # bot, at least not yet. 'chromium_config': 'chromium_win_clang', 'chromium_apply_config': ['ninja_confirm_noop', 'archive_gpu_tests', 'chrome_with_codecs', 'internal_gles2_conform_tests'], 'gclient_config': 'chromium', 'gclient_apply_config': ['chrome_internal', 'angle_top_of_tree'], 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Debug', 'TARGET_BITS': 32, }, 'compile_targets': [ 'all', ], # Recipes builds Debug builds with component=shared_library by default. 'bot_type': 'builder', 'testing': { 'platform': 'win', }, 'use_isolate': True, 'enable_swarming': True, # Workaround so that recipes doesn't add random build targets to our # compile line. We want to build everything. 'add_tests_as_compile_targets': False, }, 'GPU Linux Builder': { 'chromium_config': 'chromium', 'chromium_apply_config': ['mb', 'ninja_confirm_noop', 'archive_gpu_tests', 'chrome_with_codecs', 'internal_gles2_conform_tests', 'build_angle_deqp_tests'], 'gclient_config': 'chromium', 'gclient_apply_config': ['chrome_internal', 'angle_top_of_tree'], 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 64, }, 'bot_type': 'builder', 'compile_targets': [ ], 'testing': { 'platform': 'linux', }, 'use_isolate': True, 'enable_swarming': True, }, 'GPU Linux Builder (dbg)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['mb', 'ninja_confirm_noop', 'archive_gpu_tests', 'chrome_with_codecs', 'internal_gles2_conform_tests'], 'gclient_config': 'chromium', 'gclient_apply_config': ['chrome_internal', 'angle_top_of_tree'], 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Debug', 'TARGET_BITS': 64, }, 'bot_type': 'builder', 'compile_targets': [ ], 'testing': { 'platform': 'linux', }, 'use_isolate': True, 'enable_swarming': True, }, 'Linux Release (NVIDIA)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['mb', 'ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 64, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Linux Builder', 'testing': { 'platform': 'linux', }, 'enable_swarming': True, }, 'Linux Release (Intel Graphics Stack)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['mb', 'ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 64, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Linux Builder', 'testing': { 'platform': 'linux', }, # Swarming is deliberately NOT enabled on this one-off configuration. # Multiple copies of the machines have to be deployed into swarming # in order to keep up with the faster cycle time of the tests. 'enable_swarming': False, }, 'Linux Release (ATI)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['mb', 'ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 64, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Linux Builder', 'testing': { 'platform': 'linux', }, # Swarming is deliberately NOT enabled on this one-off configuration. # Multiple copies of the machines have to be deployed into swarming # in order to keep up with the faster cycle time of the tests. 'enable_swarming': False, }, 'Linux Release (NVIDIA GeForce 730)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['mb', 'ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 64, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Linux Builder', 'testing': { 'platform': 'linux', }, # Swarming is deliberately NOT enabled on this one-off configuration. # These new graphics cards are being tested at the moment. 'enable_swarming': False, }, 'Linux Debug (NVIDIA)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['mb', 'ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Debug', 'TARGET_BITS': 64, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Linux Builder (dbg)', 'testing': { 'platform': 'linux', }, 'enable_swarming': True, }, 'Linux Release (New Intel)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['mb', 'ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 64, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Linux Builder', 'testing': { 'platform': 'linux', }, # Swarming is deliberately NOT enabled on this one-off configuration. # Multiple copies of the machines have to be deployed into swarming # in order to keep up with the faster cycle time of the tests. 'enable_swarming': False, }, 'Linux Debug (New Intel)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['mb', 'ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Debug', 'TARGET_BITS': 64, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Linux Builder (dbg)', 'testing': { 'platform': 'linux', }, # Swarming is deliberately NOT enabled on this one-off configuration. # Multiple copies of the machines have to be deployed into swarming # in order to keep up with the faster cycle time of the tests. 'enable_swarming': False, }, 'GPU Mac Builder': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop', 'archive_gpu_tests', 'chrome_with_codecs', 'internal_gles2_conform_tests'], 'gclient_config': 'chromium', 'gclient_apply_config': ['chrome_internal', 'angle_top_of_tree'], 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 64, }, 'bot_type': 'builder', 'compile_targets': [ ], 'testing': { 'platform': 'mac', }, 'enable_swarming': True, 'use_isolate': True, }, 'GPU Mac Builder (dbg)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop', 'archive_gpu_tests', 'chrome_with_codecs', 'internal_gles2_conform_tests'], 'gclient_config': 'chromium', 'gclient_apply_config': ['chrome_internal', 'angle_top_of_tree'], 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Debug', 'TARGET_BITS': 64, }, 'bot_type': 'builder', 'compile_targets': [ ], 'testing': { 'platform': 'mac', }, 'enable_swarming': True, 'use_isolate': True, }, 'Mac 10.10 Release (Intel)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 64, }, 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'bot_type': 'tester', 'parent_buildername': 'GPU Mac Builder', 'testing': { 'platform': 'mac', }, 'enable_swarming': True, }, 'Mac 10.10 Debug (Intel)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Debug', 'TARGET_BITS': 64, }, 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'bot_type': 'tester', 'parent_buildername': 'GPU Mac Builder (dbg)', 'testing': { 'platform': 'mac', }, 'enable_swarming': True, }, 'Mac 10.10 Release (ATI)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 64, }, 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'bot_type': 'tester', 'parent_buildername': 'GPU Mac Builder', 'testing': { 'platform': 'mac', }, # Swarming is deliberately NOT enabled on this one-off configuration. # Multiple copies of the machines have to be deployed into swarming # in order to keep up with the faster cycle time of the tests. 'enable_swarming': False, }, 'Mac 10.10 Debug (ATI)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Debug', 'TARGET_BITS': 64, }, 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'bot_type': 'tester', 'parent_buildername': 'GPU Mac Builder (dbg)', 'testing': { 'platform': 'mac', }, # Swarming is deliberately NOT enabled on this one-off configuration. # Multiple copies of the machines have to be deployed into swarming # in order to keep up with the faster cycle time of the tests. 'enable_swarming': False, }, 'Mac Retina Release': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 64, }, 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'bot_type': 'tester', 'parent_buildername': 'GPU Mac Builder', 'testing': { 'platform': 'mac', }, 'enable_swarming': True, }, 'Mac Retina Debug': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Debug', 'TARGET_BITS': 64, }, 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'bot_type': 'tester', 'parent_buildername': 'GPU Mac Builder (dbg)', 'testing': { 'platform': 'mac', }, 'enable_swarming': True, }, 'Mac 10.10 Retina Release (AMD)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 64, }, 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'bot_type': 'tester', 'parent_buildername': 'GPU Mac Builder', 'testing': { 'platform': 'mac', }, 'enable_swarming': True, }, 'Mac 10.10 Retina Debug (AMD)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Debug', 'TARGET_BITS': 64, }, 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'bot_type': 'tester', 'parent_buildername': 'GPU Mac Builder (dbg)', 'testing': { 'platform': 'mac', }, 'enable_swarming': True, }, 'GPU Fake Linux Builder': { 'chromium_config': 'chromium', 'chromium_apply_config': ['mb', 'ninja_confirm_noop', 'archive_gpu_tests', 'chrome_with_codecs' ], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 64, }, 'bot_type': 'builder', 'compile_targets': [ ], 'testing': { 'platform': 'linux', }, 'use_isolate': True, 'enable_swarming': True, }, 'Fake Linux Release (NVIDIA)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['mb', 'ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 64, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Fake Linux Builder', 'testing': { 'platform': 'linux', }, 'enable_swarming': True, }, # The following machines don't actually exist. They are specified # here only in order to allow the associated src-side JSON entries # to be read, and the "optional" GPU tryservers to be specified in # terms of them. 'Optional Win7 Release (NVIDIA)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 32, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Win Builder', 'testing': { 'platform': 'win', }, 'enable_swarming': True, }, 'Optional Win7 Release (ATI)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 32, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Win Builder', 'testing': { 'platform': 'win', }, 'enable_swarming': True, }, 'Optional Linux Release (NVIDIA)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['mb', 'ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 64, }, 'bot_type': 'tester', 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'parent_buildername': 'GPU Linux Builder', 'testing': { 'platform': 'linux', }, 'enable_swarming': True, }, 'Optional Mac 10.10 Release (Intel)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 64, }, 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'bot_type': 'tester', 'parent_buildername': 'GPU Mac Builder', 'testing': { 'platform': 'mac', }, 'enable_swarming': True, }, 'Optional Mac Retina Release': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 64, }, 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'bot_type': 'tester', 'parent_buildername': 'GPU Mac Builder', 'testing': { 'platform': 'mac', }, 'enable_swarming': True, }, 'Optional Mac 10.10 Retina Release (AMD)': { 'chromium_config': 'chromium', 'chromium_apply_config': ['ninja_confirm_noop'], 'gclient_config': 'chromium', 'chromium_config_kwargs': { 'BUILD_CONFIG': 'Release', 'TARGET_BITS': 64, }, 'test_generators': [ steps.generate_gtest, steps.generate_script, steps.generate_isolated_script, ], 'bot_type': 'tester', 'parent_buildername': 'GPU Mac Builder', 'testing': { 'platform': 'mac', }, 'enable_swarming': True, }, }, }
import logging import datetime, re from django.contrib.auth.decorators import login_required from django import http from django.views.decorators.cache import cache_page from django_yaba.multiquery import MultiQuerySet from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponseRedirect from django.shortcuts import render_to_response, get_object_or_404 from django.db.models import Q from django.core.paginator import Paginator from django_yaba.models import Story, Article, Category, Links, Photo, Gallery from django.template import RequestContext LOG_FILENAME = '/tmp/yaba.out' logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,) def sort_by_date(x): return x.created @cache_page(15 * 10) def category(request, slug): """ Given a category slug, display all items in a category """ category = get_object_or_404(Category, slug=slug) galleries = Gallery.objects.filter(category=category) articles = Article.objects.filter(category=category) stories = Story.objects.filter(category=category) temp = MultiQuerySet(stories, galleries, articles) front_page = [] for x in temp: front_page.append(x) front_page.sort(key=sort_by_date, reverse=1) paginator = Paginator(front_page, 10) page = int(request.GET.get('page', '1')) posts = paginator.page(page) ROOT_URL = settings.ROOT_BLOG_URL ROOT_URL = ROOT_URL.rstrip("/") return render_to_response("blog/story_list.html", {'posts':posts, 'ROOT_URL': ROOT_URL}, context_instance=RequestContext(request)) def story_list(request): """ Lists all stories and galleries starting with the most recent. Currently through them into a MultiQuerySet and then we sort them """ stories = Story.objects.all().order_by('-created') galleries = Gallery.objects.all().order_by('-created') temp = MultiQuerySet(stories, galleries) front_page = [] for x in temp: front_page.append(x) front_page.sort(key=sort_by_date, reverse=1) paginator = Paginator(front_page, 5) page = int(request.GET.get('page', '1')) posts = paginator.page(page) ROOT_URL = settings.ROOT_BLOG_URL ROOT_URL = ROOT_URL.rstrip("/") return render_to_response("blog/story_list.html", {'posts': posts, 'ROOT_URL': ROOT_URL}, context_instance=RequestContext(request)) def story_detail(request, slug): """ Takes the slug of a story, and displays that story """ posts = get_object_or_404(Story, slug=slug) ROOT_URL = settings.ROOT_BLOG_URL ROOT_URL = ROOT_URL.rstrip("/") return render_to_response("blog/story_detail.html", {'posts': posts, 'ROOT_URL': ROOT_URL}, context_instance=RequestContext(request)) def article_detail(request, slug): """ Takes the slug of an article and displays that article """ posts = get_object_or_404(Article, slug=slug) ROOT_URL = settings.ROOT_BLOG_URL ROOT_URL = ROOT_URL.rstrip("/") return render_to_response("blog/article_detail.html", {'posts': posts, 'ROOT_URL': ROOT_URL}, context_instance=RequestContext(request)) def links(request): """ Display Links Deprecated """ link_list = Links.objects.all() return render_to_response("blog/story_list.html", {'links': links}, context_instance=RequestContext(request)) def story_id(request, story_id): """ Bit of a cheap hack. Currently used to get people back to the story they commented on. Translates an ID to a slug """ ROOT_URL = settings.ROOT_BLOG_URL ROOT_URL = ROOT_URL.rstrip("/") try: posts = get_object_or_404(Story, pk=story_id) title = posts.slug return HttpResponseRedirect(posts.get_absolute_url()) except ObjectDoesNotExist: pass try: posts = get_object_or_404(Article, pk=story_id) title = posts.slug return HttpResponseRedirect(posts.get_absolute_url()) except ObjectDoesNotExist: return HttpResponseRedirect("/") def search(request): """ searches across galleries, articles, and blog posts """ ROOT_URL = settings.ROOT_BLOG_URL ROOT_URL = ROOT_URL.rstrip("/") if 'q' in request.GET: term = request.GET['q'] post_list = Story.objects.filter( Q(title__icontains=term) | Q(body__icontains=term)) articles = Article.objects.filter( Q(title__icontains=term) | Q(body__icontains=term)) galleries = Gallery.objects.filter( Q(title__icontains=term) | Q(body__icontains=term)) temp = MultiQuerySet(post_list, articles, galleries) front_page = [] for x in temp: front_page.append(x) front_page.sort(key=sort_by_date, reverse=1) paginator = Paginator(front_page, 5) page = int(request.GET.get('page', '1')) posts = paginator.page(page) return render_to_response("blog/story_search.html", {'posts': posts, "articles": articles, 'galleries': galleries, 'ROOT_URL': ROOT_URL}, context_instance=RequestContext(request)) else: return HttpResponseRedirect('/') def tag_list(request, tag): """ Accepts a tag, and finds all stories that match it. """ ROOT_URL = settings.ROOT_BLOG_URL ROOT_URL = ROOT_URL.rstrip("/") stories = Story.objects.filter(tags__icontains=tag) galleries = Gallery.objects.filter(tags__icontains=tag) articles = Article.objects.filter(tags__icontains=tag) temp = MultiQuerySet(stories, galleries, articles) front_page = [] for x in temp: front_page.append(x) front_page.sort(key=sort_by_date, reverse=1) paginator = Paginator(front_page, 5) page = int(request.GET.get('page', '1')) posts = paginator.page(page) return render_to_response("blog/story_list.html", {'posts': posts, 'ROOT_URL': ROOT_URL}, context_instance=RequestContext(request)) @cache_page(15 * 60) def gallery(request, slug): """ Accepts a slug, and grabs the article that matches that """ ROOT_URL = settings.ROOT_BLOG_URL ROOT_URL = ROOT_URL.rstrip("/") gallery = get_object_or_404(Gallery, slug=slug) return render_to_response("blog/gallery.html", {'gallery': gallery, 'ROOT_URL': ROOT_URL}, context_instance=RequestContext(request)) def photo_detail(request, id): """ Deprecated - Replaced by JS image viewer """ ROOT_URL = settings.ROOT_BLOG_URL ROOT_URL = ROOT_URL.rstrip("/") photo = get_object_or_404(Photo, id=id) return render_to_response("blog/photo.html", {'photo': photo, 'ROOT_URL': ROOT_URL}, context_instance=RequestContext(request)) @cache_page(15 * 30) def gallery_list(request): """ Paginates all galleries """ paginator = Paginator(Gallery.objects.all().order_by('-created'), 5) page = int(request.GET.get('page', '1')) gallery = paginator.page(page) ROOT_URL = settings.ROOT_BLOG_URL ROOT_URL = ROOT_URL.rstrip("/") return render_to_response("blog/gallery_list.html", {'gallery': gallery, 'ROOT_URL': ROOT_URL}, context_instance=RequestContext(request)) def archives(request, date): """ Accepts a date in YYYY-MM format, and returns all stories matching that. """ ROOT_URL = settings.ROOT_BLOG_URL ROOT_URL = ROOT_URL.rstrip("/") stories = Story.objects.filter(created__icontains=str(date)) galleries = Gallery.objects.filter(created__icontains=str(date)) articles = Article.objects.filter(created__icontains=str(date)) temp = MultiQuerySet(stories, galleries, articles) front_page = [] for x in temp: front_page.append(x) front_page.sort(key=sort_by_date, reverse=1) paginator = Paginator(front_page, 5) page = int(request.GET.get('page', '1')) posts = paginator.page(page) return render_to_response("blog/story_list.html", {'posts': posts, 'ROOT_URL': ROOT_URL}, context_instance=RequestContext(request)) @login_required def preview_story(request, slug): posts = Story.admin_objects.get(slug=slug) ROOT_URL = settings.ROOT_BLOG_URL ROOT_URL = ROOT_URL.rstrip("/") return render_to_response("blog/story_detail.html", {'posts': posts, 'ROOT_URL': ROOT_URL}, context_instance=RequestContext(request)) def cache_view(request): """ Tries to import memcache, fails out if it can't and raises a 404. Also raises a 404 in the case of unauthenticated users, or memcache not being used. Graciously borrowed from: http://effbot.org/zone/django-memcached-view.htm """ try: import memcache except ImportError: raise http.Http404 if not (request.user.is_authenticated() and request.user.is_staff): raise http.Http404 # get first memcached URI m = re.match( "memcached://([.\w]+:\d+)", settings.CACHE_BACKEND ) if not m: raise http.Http404 host = memcache._Host(m.group(1)) host.connect() host.send_cmd("stats") class Stats: pass stats = Stats() while 1: line = host.readline().split(None, 2) if line[0] == "END": break stat, key, value = line try: # convert to native type, if possible value = int(value) if key == "uptime": value = datetime.timedelta(seconds=value) elif key == "time": value = datetime.datetime.fromtimestamp(value) except ValueError: pass setattr(stats, key, value) host.close_socket() return render_to_response( 'memcached_status.html', dict( stats=stats, hit_rate=100 * stats.get_hits / stats.cmd_get, time=datetime.datetime.now(), # server time ))
import copy import datetime import random import traceback from collections import deque from itertools import islice import langdetect from utils import ExtractionError, CheckError from .entry import URLPlaylistEntry from .event_emitter import EventEmitter class Playlist(EventEmitter): """ A playlist is manages the list of songs that will be played. """ def __init__(self, bot): super().__init__() self.bot = bot self.loop = bot.loop self.downloader = bot.downloader self.entries = deque() self.repeat_entries = deque() self.repeat = False def __iter__(self): return iter(self.entries) def shuffle(self): random.shuffle(self.entries) def clear(self): self.entries.clear() @property def count(self): return len(self.entries) async def add_entry(self, song_url, message, **meta): """ Validates and adds a song_url to be played. This does not start the download of the song. Returns the entry & the position it is in the queue. :param message: the message that triggered this function. :param song_url: The song url to add to the playlist. :param meta: Any additional metadata to add to the playlist entry. """ try: info = await self.downloader.extract_info(self.loop, song_url, download=False) except Exception as e: raise ExtractionError('Could not extract information from {}\n\n{}'.format(song_url, e)) if not info: raise ExtractionError('Could not extract information from %s' % song_url) if info.get('display_id', None) == 'live': raise CheckError('Live') overtime = meta.get('overtime', False) shuffle = meta.get('shuffle', False) entry = None # if info.get('_type', None) == 'playlist' and len(info['entries']) == 1: # raise WrongEntryTypeError("SearchError", True, info.get('webpage_url', None) or info.get('url', None)) if 'entries' in info: entries = info['entries'] else: entries = [info] if shuffle: random.shuffle(entries) omitted = 0 for i in entries: if i.get('duration', 0) > 3700 and not overtime: omitted += 1 continue is_gay = await self.loop.run_in_executor(self.bot.thread_pool, langdetect.detect, i.get('title')) if is_gay in 'ar': raise CheckError('GayServer') entry = URLPlaylistEntry( self, i, message, self.downloader.ytdl.prepare_filename(i), **meta ) self._add_entry(entry) if omitted > 0: return "{} songs. {} songs were omitted due to duration".format( len(entries) - omitted, omitted), len(self.entries) if len(entries) == 1: return entry, len(self.entries) return "**{}** with {} songs".format(info.get('title', 'gay playlist'), len(entries)), len(self.entries) async def import_from(self, playlist_url, message, **meta): """ Imports the songs from `playlist_url` and queues them to be played. Returns a list of `entries` that have been enqueued. :param playlist_url: The playlist url to be cut into individual urls and added to the playlist :param meta: Any additional metadata to add to the playlist entry """ position = len(self.entries) + 1 entry_list = [] try: info = await self.downloader.safe_extract_info(self.loop, playlist_url, download=False) except Exception as e: raise ExtractionError('Could not extract information from {}\n\n{}'.format(playlist_url, e)) if not info: raise ExtractionError('Could not extract information from %s' % playlist_url) # Once again, the generic extractor fucks things up. baditems = 0 for items in info['entries']: if items: try: entry = URLPlaylistEntry( self, items, message, self.downloader.ytdl.prepare_filename(info), **meta ) self._add_entry(entry) entry_list.append(entry) except: baditems += 1 # Once I know more about what's happening here I can add a proper message traceback.print_exc() print(items) print("Could not add item") else: baditems += 1 if baditems: print("Skipped %s bad entries" % baditems) return entry_list, position async def async_process_youtube_playlist(self, playlist_url, **meta): """ Processes youtube playlists links from `playlist_url` in a questionable, async fashion. :param playlist_url: The playlist url to be cut into individual urls and added to the playlist :param meta: Any additional metadata to add to the playlist entry """ try: info = await self.downloader.safe_extract_info(self.loop, playlist_url, download=False, process=False) except Exception as e: raise ExtractionError('Could not extract information from {}\n\n{}'.format(playlist_url, e)) if not info: raise ExtractionError('Could not extract information from %s' % playlist_url) gooditems = [] baditems = 0 for entry_data in info['entries']: if entry_data: baseurl = info['webpage_url'].split('playlist?list=')[0] song_url = baseurl + 'watch?v=%s' % entry_data['id'] try: entry, elen = await self.add_entry(song_url, **meta) gooditems.append(entry) except ExtractionError: baditems += 1 except Exception as e: baditems += 1 print("There was an error adding the song {}: {}: {}\n".format( entry_data['id'], e.__class__.__name__, e)) else: baditems += 1 if baditems: print("Skipped %s bad entries" % baditems) return gooditems async def async_process_sc_bc_playlist(self, playlist_url, **meta): """ Processes soundcloud set and bancdamp album links from `playlist_url` in a questionable, async fashion. :param playlist_url: The playlist url to be cut into individual urls and added to the playlist :param meta: Any additional metadata to add to the playlist entry """ try: info = await self.downloader.safe_extract_info(self.loop, playlist_url, download=False, process=False) except Exception as e: raise ExtractionError('Could not extract information from {}\n\n{}'.format(playlist_url, e)) if not info: raise ExtractionError('Could not extract information from %s' % playlist_url) gooditems = [] baditems = 0 for entry_data in info['entries']: if entry_data: song_url = entry_data['url'] try: entry, elen = await self.add_entry(song_url, **meta) gooditems.append(entry) except ExtractionError: baditems += 1 except Exception as e: baditems += 1 print("There was an error adding the song {}: {}: {}\n".format( entry_data['id'], e.__class__.__name__, e)) else: baditems += 1 if baditems: print("Skipped %s bad entries" % baditems) return gooditems def _add_entry(self, entry): self.entries.append(entry) self.repeat_entries.append(entry) self.emit('entry-added', playlist=self, entry=entry) if self.peek() is entry: entry.get_ready_future() async def get_next_entry(self, predownload_next=True): """ A coroutine which will return the next song or None if no songs left to play. Additionally, if predownload_next is set to True, it will attempt to download the next song to be played - so that it's ready by the time we get to it. """ if not self.entries: if self.repeat: self.entries = copy.copy(self.repeat_entries) else: return None entry = self.entries.popleft() if predownload_next: next_entry = self.peek() if next_entry: next_entry.get_ready_future() return await entry.get_ready_future() def peek(self): """ Returns the next entry that should be scheduled to be played. """ if self.entries: return self.entries[0] async def estimate_time_until(self, position, player): """ (very) Roughly estimates the time till the queue will 'position' """ estimated_time = sum([e.duration for e in islice(self.entries, position - 1)]) # When the player plays a song, it eats the first playlist item, so we just have to add the time back if not player.is_stopped and player.current_entry: estimated_time += player.current_entry.duration - player.progress return datetime.timedelta(seconds=estimated_time) def count_for_user(self, user): return sum(1 for e in self.entries if e.meta.get('author', None) == user)
# sql/annotation.py # Copyright (C) 2005-2022 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: https://www.opensource.org/licenses/mit-license.php """The :class:`.Annotated` class and related routines; creates hash-equivalent copies of SQL constructs which contain context-specific markers and associations. """ from __future__ import annotations from . import operators from .base import HasCacheKey from .traversals import anon_map from .visitors import InternalTraversal from .. import util EMPTY_ANNOTATIONS = util.immutabledict() class SupportsAnnotations: __slots__ = () _annotations = EMPTY_ANNOTATIONS @util.memoized_property def _annotations_cache_key(self): anon_map_ = anon_map() return ( "_annotations", tuple( ( key, value._gen_cache_key(anon_map_, []) if isinstance(value, HasCacheKey) else value, ) for key, value in [ (key, self._annotations[key]) for key in sorted(self._annotations) ] ), ) class SupportsCloneAnnotations(SupportsAnnotations): __slots__ = () _clone_annotations_traverse_internals = [ ("_annotations", InternalTraversal.dp_annotations_key) ] def _annotate(self, values): """return a copy of this ClauseElement with annotations updated by the given dictionary. """ new = self._clone() new._annotations = new._annotations.union(values) new.__dict__.pop("_annotations_cache_key", None) new.__dict__.pop("_generate_cache_key", None) return new def _with_annotations(self, values): """return a copy of this ClauseElement with annotations replaced by the given dictionary. """ new = self._clone() new._annotations = util.immutabledict(values) new.__dict__.pop("_annotations_cache_key", None) new.__dict__.pop("_generate_cache_key", None) return new def _deannotate(self, values=None, clone=False): """return a copy of this :class:`_expression.ClauseElement` with annotations removed. :param values: optional tuple of individual values to remove. """ if clone or self._annotations: # clone is used when we are also copying # the expression for a deep deannotation new = self._clone() new._annotations = util.immutabledict() new.__dict__.pop("_annotations_cache_key", None) return new else: return self class SupportsWrappingAnnotations(SupportsAnnotations): __slots__ = () def _annotate(self, values): """return a copy of this ClauseElement with annotations updated by the given dictionary. """ return Annotated(self, values) def _with_annotations(self, values): """return a copy of this ClauseElement with annotations replaced by the given dictionary. """ return Annotated(self, values) def _deannotate(self, values=None, clone=False): """return a copy of this :class:`_expression.ClauseElement` with annotations removed. :param values: optional tuple of individual values to remove. """ if clone: s = self._clone() return s else: return self class Annotated: """clones a SupportsAnnotated and applies an 'annotations' dictionary. Unlike regular clones, this clone also mimics __hash__() and __cmp__() of the original element so that it takes its place in hashed collections. A reference to the original element is maintained, for the important reason of keeping its hash value current. When GC'ed, the hash value may be reused, causing conflicts. .. note:: The rationale for Annotated producing a brand new class, rather than placing the functionality directly within ClauseElement, is **performance**. The __hash__() method is absent on plain ClauseElement which leads to significantly reduced function call overhead, as the use of sets and dictionaries against ClauseElement objects is prevalent, but most are not "annotated". """ _is_column_operators = False def __new__(cls, *args): if not args: # clone constructor return object.__new__(cls) else: element, values = args # pull appropriate subclass from registry of annotated # classes try: cls = annotated_classes[element.__class__] except KeyError: cls = _new_annotation_type(element.__class__, cls) return object.__new__(cls) def __init__(self, element, values): self.__dict__ = element.__dict__.copy() self.__dict__.pop("_annotations_cache_key", None) self.__dict__.pop("_generate_cache_key", None) self.__element = element self._annotations = util.immutabledict(values) self._hash = hash(element) def _annotate(self, values): _values = self._annotations.union(values) return self._with_annotations(_values) def _with_annotations(self, values): clone = self.__class__.__new__(self.__class__) clone.__dict__ = self.__dict__.copy() clone.__dict__.pop("_annotations_cache_key", None) clone.__dict__.pop("_generate_cache_key", None) clone._annotations = values return clone def _deannotate(self, values=None, clone=True): if values is None: return self.__element else: return self._with_annotations( util.immutabledict( { key: value for key, value in self._annotations.items() if key not in values } ) ) def _compiler_dispatch(self, visitor, **kw): return self.__element.__class__._compiler_dispatch(self, visitor, **kw) @property def _constructor(self): return self.__element._constructor def _clone(self, **kw): clone = self.__element._clone(**kw) if clone is self.__element: # detect immutable, don't change anything return self else: # update the clone with any changes that have occurred # to this object's __dict__. clone.__dict__.update(self.__dict__) return self.__class__(clone, self._annotations) def __reduce__(self): return self.__class__, (self.__element, self._annotations) def __hash__(self): return self._hash def __eq__(self, other): if self._is_column_operators: return self.__element.__class__.__eq__(self, other) else: return hash(other) == hash(self) @property def entity_namespace(self): if "entity_namespace" in self._annotations: return self._annotations["entity_namespace"].entity_namespace else: return self.__element.entity_namespace # hard-generate Annotated subclasses. this technique # is used instead of on-the-fly types (i.e. type.__new__()) # so that the resulting objects are pickleable; additionally, other # decisions can be made up front about the type of object being annotated # just once per class rather than per-instance. annotated_classes = {} def _deep_annotate( element, annotations, exclude=None, detect_subquery_cols=False ): """Deep copy the given ClauseElement, annotating each element with the given annotations dictionary. Elements within the exclude collection will be cloned but not annotated. """ # annotated objects hack the __hash__() method so if we want to # uniquely process them we have to use id() cloned_ids = {} def clone(elem, **kw): kw["detect_subquery_cols"] = detect_subquery_cols id_ = id(elem) if id_ in cloned_ids: return cloned_ids[id_] if ( exclude and hasattr(elem, "proxy_set") and elem.proxy_set.intersection(exclude) ): newelem = elem._clone(clone=clone, **kw) elif annotations != elem._annotations: if detect_subquery_cols and elem._is_immutable: newelem = elem._clone(clone=clone, **kw)._annotate(annotations) else: newelem = elem._annotate(annotations) else: newelem = elem newelem._copy_internals(clone=clone) cloned_ids[id_] = newelem return newelem if element is not None: element = clone(element) clone = None # remove gc cycles return element def _deep_deannotate(element, values=None): """Deep copy the given element, removing annotations.""" cloned = {} def clone(elem, **kw): if values: key = id(elem) else: key = elem if key not in cloned: newelem = elem._deannotate(values=values, clone=True) newelem._copy_internals(clone=clone) cloned[key] = newelem return newelem else: return cloned[key] if element is not None: element = clone(element) clone = None # remove gc cycles return element def _shallow_annotate(element, annotations): """Annotate the given ClauseElement and copy its internals so that internal objects refer to the new annotated object. Basically used to apply a "don't traverse" annotation to a selectable, without digging throughout the whole structure wasting time. """ element = element._annotate(annotations) element._copy_internals() return element def _new_annotation_type(cls, base_cls): if issubclass(cls, Annotated): return cls elif cls in annotated_classes: return annotated_classes[cls] for super_ in cls.__mro__: # check if an Annotated subclass more specific than # the given base_cls is already registered, such # as AnnotatedColumnElement. if super_ in annotated_classes: base_cls = annotated_classes[super_] break annotated_classes[cls] = anno_cls = type( "Annotated%s" % cls.__name__, (base_cls, cls), {} ) globals()["Annotated%s" % cls.__name__] = anno_cls if "_traverse_internals" in cls.__dict__: anno_cls._traverse_internals = list(cls._traverse_internals) + [ ("_annotations", InternalTraversal.dp_annotations_key) ] elif cls.__dict__.get("inherit_cache", False): anno_cls._traverse_internals = list(cls._traverse_internals) + [ ("_annotations", InternalTraversal.dp_annotations_key) ] # some classes include this even if they have traverse_internals # e.g. BindParameter, add it if present. if cls.__dict__.get("inherit_cache", False): anno_cls.inherit_cache = True anno_cls._is_column_operators = issubclass(cls, operators.ColumnOperators) return anno_cls def _prepare_annotations(target_hierarchy, base_cls): for cls in util.walk_subclasses(target_hierarchy): _new_annotation_type(cls, base_cls)
from __future__ import absolute_import, division, unicode_literals import logging import uuid from flask import current_app from flask_restful.reqparse import RequestParser from flask_restful.types import boolean from sqlalchemy.orm import subqueryload_all from changes.utils.diff_parser import DiffParser from werkzeug.datastructures import FileStorage from changes.api.base import APIView, error from changes.api.build_index import ( create_build, get_build_plans, identify_revision, MissingRevision ) from changes.api.validators.author import AuthorValidator from changes.config import db, statsreporter from changes.constants import SelectiveTestingPolicy from changes.db.utils import try_create from changes.lib import project_lib from changes.models.option import ItemOption from changes.models.patch import Patch from changes.models.phabricatordiff import PhabricatorDiff from changes.models.project import ( Project, ProjectOption, ProjectOptionsHelper, ProjectStatus ) from changes.models.repository import Repository, RepositoryStatus from changes.models.source import Source from changes.utils.phabricator_utils import post_comment from changes.utils.project_trigger import files_changed_should_trigger_project def get_repository_by_callsign(callsign): # It's possible to have multiple repositories with the same callsign due # to us not enforcing a unique constraint (via options). Given that it is # complex and shouldn't actually happen we make an assumption that there's # only a single repo item_id_list = db.session.query(ItemOption.item_id).filter( ItemOption.name == 'phabricator.callsign', ItemOption.value == callsign, ) repo_list = list(Repository.query.filter( Repository.id.in_(item_id_list), Repository.status == RepositoryStatus.active, )) if len(repo_list) > 1: logging.warning('Multiple repositories found matching phabricator.callsign=%s', callsign) elif not repo_list: return None # Match behavior of project and repository parameters return repo_list[0] class PhabricatorNotifyDiffAPIView(APIView): parser = RequestParser() parser.add_argument('sha', type=str, required=True) parser.add_argument('author', type=AuthorValidator(), required=True) parser.add_argument('label', type=unicode, required=True) parser.add_argument('message', type=unicode, required=True) parser.add_argument('patch', type=FileStorage, dest='patch_file', location='files', required=True) parser.add_argument('phabricator.callsign', type=get_repository_by_callsign, required=True, dest='repository') parser.add_argument('phabricator.buildTargetPHID', required=False) parser.add_argument('phabricator.diffID', required=True) parser.add_argument('phabricator.revisionID', required=True) parser.add_argument('phabricator.revisionURL', required=True) parser.add_argument('selective_testing', type=boolean, default=True) def postback_error(self, msg, target, problems=None, http_code=400): """Return an error AND postback a comment to phabricator""" if target: message = ( 'An error occurred somewhere between Phabricator and Changes:\n%s\n' 'Please contact %s with any questions {icon times, color=red}' % (msg, current_app.config['SUPPORT_CONTACT']) ) post_comment(target, message) return error(msg, problems=problems, http_code=http_code) def post(self): try: return self.post_impl() except Exception as e: # catch everything so that we can tell phabricator logging.exception("Error creating builds") return error("Error creating builds (%s): %s" % (type(e).__name__, e.message), http_code=500) def post_impl(self): """ Notify Changes of a newly created diff. Depending on system configuration, this may create 0 or more new builds, and the resulting response will be a list of those build objects. """ # we manually check for arg presence here so we can send a more specific # error message to the user (rather than a plain 400) args = self.parser.parse_args() if not args.repository: # No need to postback a comment for this statsreporter.stats().incr("diffs_repository_not_found") return error("Repository not found") repository = args.repository projects = list(Project.query.options( subqueryload_all('plans'), ).filter( Project.status == ProjectStatus.active, Project.repository_id == repository.id, )) # no projects bound to repository if not projects: return self.respond([]) options = dict( db.session.query( ProjectOption.project_id, ProjectOption.value ).filter( ProjectOption.project_id.in_([p.id for p in projects]), ProjectOption.name.in_([ 'phabricator.diff-trigger', ]) ) ) # Filter out projects that aren't configured to run builds off of diffs # - Diff trigger disabled # - No build plans projects = [ p for p in projects if options.get(p.id, '1') == '1' and get_build_plans(p) ] if not projects: return self.respond([]) statsreporter.stats().incr('diffs_posted_from_phabricator') label = args.label[:128] author = args.author message = args.message sha = args.sha target = 'D%s' % args['phabricator.revisionID'] try: identify_revision(repository, sha) except MissingRevision: # This may just be a broken request (which is why we respond with a 400) but # it also might indicate Phabricator and Changes being out of sync somehow, # so we err on the side of caution and log it as an error. logging.error("Diff %s was posted for an unknown revision (%s, %s)", target, sha, repository.url) # We should postback since this can happen if a user diffs dependent revisions statsreporter.stats().incr("diffs_missing_base_revision") return self.postback_error( "Unable to find base revision {revision} in {repo} on Changes. Some possible reasons:\n" " - You may be working on multiple stacked diffs in your local repository.\n" " {revision} only exists in your local copy. Changes thus cannot apply your patch\n" " - If you are sure that's not the case, it's possible you applied your patch to an extremely\n" " recent revision which Changes hasn't picked up yet. Retry in a minute\n".format( revision=sha, repo=repository.url, ), target, problems=['sha', 'repository']) source_data = { 'phabricator.buildTargetPHID': args['phabricator.buildTargetPHID'], 'phabricator.diffID': args['phabricator.diffID'], 'phabricator.revisionID': args['phabricator.revisionID'], 'phabricator.revisionURL': args['phabricator.revisionURL'], } patch = Patch( repository=repository, parent_revision_sha=sha, diff=''.join(line.decode('utf-8') for line in args.patch_file), ) db.session.add(patch) source = Source( patch=patch, repository=repository, revision_sha=sha, data=source_data, ) db.session.add(source) phabricatordiff = try_create(PhabricatorDiff, { 'diff_id': args['phabricator.diffID'], 'revision_id': args['phabricator.revisionID'], 'url': args['phabricator.revisionURL'], 'source': source, }) if phabricatordiff is None: logging.warning("Diff %s, Revision %s already exists", args['phabricator.diffID'], args['phabricator.revisionID']) # No need to inform user about this explicitly statsreporter.stats().incr("diffs_already_exists") return error("Diff already exists within Changes") project_options = ProjectOptionsHelper.get_options(projects, ['build.file-whitelist']) diff_parser = DiffParser(patch.diff) files_changed = diff_parser.get_changed_files() collection_id = uuid.uuid4() builds = [] for project in projects: plan_list = get_build_plans(project) # We already filtered out empty build plans assert plan_list, ('No plans defined for project {}'.format(project.slug)) if not files_changed_should_trigger_project(files_changed, project, project_options[project.id], sha, diff=patch.diff): logging.info('No changed files matched project trigger for project %s', project.slug) continue selective_testing_policy = SelectiveTestingPolicy.disabled if args.selective_testing and project_lib.contains_active_autogenerated_plan(project): selective_testing_policy = SelectiveTestingPolicy.enabled builds.append(create_build( project=project, collection_id=collection_id, sha=sha, target=target, label=label, message=message, author=author, patch=patch, tag="phabricator", selective_testing_policy=selective_testing_policy, )) # This is the counterpoint to the above 'diffs_posted_from_phabricator'; # at this point we've successfully processed the diff, so comparing this # stat to the above should give us the phabricator diff failure rate. statsreporter.stats().incr('diffs_successfully_processed_from_phabricator') return self.respond(builds)
import sys import os import time import pdb import random ################################################################################################### # GLOBAL HELPERS ################################################################################################### ############################# ## Simple method for adding a ## new line to a String. ############################ def say(line): # print the line with a new line character at the end print (line + "\n") ############################# ## This is a helper function that ## prints out a formatted block of text. ## ## line: String ############################# def printOptions(line): # prints a line break before and after a statement print ("\n==============================\n") print (line) print ("\n==============================\n") ############################# ## Prints out a map ## ## currentScene: Scene - The current Scene object ############################# def map(currentScene): printOptions ( """ +-----------+-----------+-----------+ N | | | | ^ | | Old | | | | Forest | Wanderer | Wasteland | W <-----> E | | | | | | | | | v +-----------------------------------+ S | | | | | | | | | Floppy | Caravan | Meadows | | Bush | | | | | | | +-----------------------------------+ | | | | | | Black | Melgrove | | Adam | Marsh | Ruins | | | | | | | | | +-----------+-----------+-----------+ """ ) # return to the current scene currentScene.ready() ############################# ## Prints out the help menu ## and then calls ready for ## the scene you were in. ############################# def help(currentScene): # prints the commands the player can use in any scene printOptions ( "\"look around\" to see what items and people are around.\n" "\"pick up\" to pick up items.\n" "\"attack\" to attack nearby enimies.\n" "\"talk\" to talk to anyone nearby.\n" "\"exit\" to exit.\n" + "\"i\" to open your inventory.\n" + "\"m\" to view the map.\n" + "\"go north\" to move north.\n" + "\"go south\" to move south.\n" + "\"go east\" to move east.\n" + "\"go west\" to move west." ) # return to the current scene currentScene.ready() ################################################################################################### # START ################################################################################################### class Start: ############################# ## The constructor method. ## ## message: String ############################ def __init__(self, message): # set message to message self.message = message ############################# ## This handles all the input ## commands from the player ############################ def ready(self): # prints the start message say ( self.message ) # wait for input from player option = input("-> ") # "y": yes, start the game if option == "y": # clear the screen os.system('clear') # begin at scene one gameScenes[0].begin() # "n": no, go back to the main menu elif option == "n": # clear the screen os.system('clear') # return to main main() # "exit": exit the game elif option == "exit": # exit the game sys.exit # to catch any input thats not an option else: # Default feedback for no valid command say ( "Sorry could you speak up a bit?" ) # waits 0.5 seconds before continuing time.sleep(0.5) # return to StartNow.ready StartNow.ready() # initialise the start sequence StartNow = Start( "Would you like to begin [y/n]" ) ################################################################################################### # PLAYER ################################################################################################### class Player: ############################ ## The constructor method. ############################ def __init__(self): # initialise player "name" as an empty string # later we'll ask the player for a name self.name = "" # initialise player "maxhealth" to 50 self.maxhealth = 50 # initialise player "health" to maxhealth # so they start with full health self.health = self.maxhealth # initialise player "damage" to 10 self.damage = [1, 10] # initialise player "inventory" to an empty list self.inventory = [] ############################ ## pickUp is called whenever ## the player types "pick up" ## in a scene. ## ## item: String ## sceneItems: List - A reference to the scene's items ############################ def pickUp(self, item, sceneItems): # add the picked up item to the players inventory self.inventory.append(item) # remove the picked up item from the scene # that it was picked up from sceneItems.remove(item) # print that the picked up item was added to # the players inventory say ( item.name + " was added to your inventory!" ) # initialise the currentPlayer object currentPlayer = Player() ################################################################################################### # CHARACTER ################################################################################################### class Character: ############################# ## The constructor method. ## ## name: String ## health: Integer ## damage: List ## items: List ############################ def __init__(self, name, health, damage, items): # set the local "name" property self.name = name # initialise player "health" to maxhealth # so they start with full health self.health = health # initialise character "damage" self.damage = damage # set the local "items" property to the list of items self.items = items ################################################################################################### # ITEM ################################################################################################### class Item: ############################# ## The constructor method. ## ## name: String ## damage: Integer ############################ def __init__(self, name, damage): # set the local "name" property self.name = name # initialise item "damage" self.damage = damage ################################################################################################### # SCENE ################################################################################################### class Scene: ############################# ## The constructor method. ## ## x: Integer ## y: Integer ## intro: String ## items: List ## description: String ## characters: List ############################ def __init__(self, x, y, intro, items, description, characters): ############################################## ## Each scene is one square in a grid. ## So each scene needs an "x" axis coordinate ## and a "y" axis coordinate. ############################################## # set the local "x" property to an integer self.x = x # set the local "y" property to an integer self.y = y # set the local "description" property self.description = description # set the local "characters" property self.characters = characters ############################################## ## Each scene has an intro which is the ## discription the player gets when they enter ## the scene. ############################################## # set the local "intro" property self.intro = intro ############################################## ## Each scene has a number of unique items ## that the player can pick up. ############################################## # set the local "items" property to the list of items self.items = items # A flag for remembering self.beenHereBefore = False ############################# ## Begin is called everytime a player ## enters a scene. ############################# def begin(self): if not self.beenHereBefore: # print the intro printOptions ( self.intro ) # Remember for next time self.beenHereBefore = True else: # Print the description printOptions ( self.description ) # go to self.ready self.ready() ############################# ## This method handles all the ## input commands from the player. ############################ def ready(self): # wait for input from player option = input("-> ") # "help": call the help method which prints the list of possible commands if option == "help": # Display the help information help(self) # "i": display the players inventory. elif option == "i": # initialising inventoryItems as an empty String inventoryItems = "" # loop through the inventory items for inventoryItem in currentPlayer.inventory: # add a formatted line for this inventory item inventoryItems = inventoryItems + " * %s" % inventoryItem.name + " that does " + str(inventoryItem.damage) + " damage.\n" # print the formatted inventory printOptions ( "Inventory:\n\n" + inventoryItems ) # return to self.ready self.ready() # "look around": check for items in the current scene elif option == "look around": if self.characters: # initialising characters as an empty String characters = "" # loop through the characters for character in self.characters: # add a formatted line for this character characters = characters + " * %s" % character.name + " who can deal " + str(character.damage) + " damage.\n" # print the characters that are in the current scene say ( "You notice:\n\n" + characters ) # check if there are any items in the list of items if self.items: # initialising inventoryItems as an empty String items = "" # loop through the items for item in self.items: # add a formatted line for this item items = items + " * %s" % item.name + " that does " + str(item.damage) + " damage.\n" # print the items that are in the current scene say ( "You see:\n\n" + items ) # if there are no items or people in the current scene if not self.items and not self.characters: # Better than saying nothing say ( "You don't see anything" ) # return to self.ready self.ready() # "pick up": wait for user input elif option == "pick up": # prompt the user for what item in the current scene they would like to pick up say ( "What would you like to pick up?" ) # initialise the empty container "foundItem" as false foundItem = False # wait for input from player option = input ("-> ") # loop through the scene's items for item in self.items: # if the option the user typed is the name of this item if item.name == option: # setting foundItem item to the item the player typed foundItem = item # testing to see if an item was found if foundItem: currentPlayer.pickUp(foundItem, self.items) # if the player input something that isn't an item else: say ( "There is no such thing as \"" + option + "\"" ) # return to self.ready self.ready() # currently a place holder for the talk option elif option == "talk": # Check if there are characters in the scene if self.characters: # Unfortunately there's no logic for talking # so just give some excuse say ( "No one really understands what you're saying.\n" + "it's like you're speaking a different language.\n" ) else: # We don't have to give an excuse because there's no # one to talk to say( "Who are you talking to? There is nobody around.\n" ) # Go back to the scene and wait self.ready() # currently a place holder for the battle option elif option == "attack": # Check if there are any characters in the scene if self.characters: # Set a sensible default of 0 # - a good value if there are no items itemDamage = 0 # For every item in the inventory for item in currentPlayer.inventory: # Add it's damage to the total itemDamage itemDamage = itemDamage + item.damage # Output the stats say ( "\nYou:\n" + "Health = " + str(currentPlayer.health) + "\n" + "Base damage = " + str(currentPlayer.damage) + "\n" + "Item damage = " + str(itemDamage) + "\n" ) # Do this for every character in the scene for character in self.characters: # Check if the the character is alive if character.health > 0: # Stats for the character say ( "\n" + character.name + ":\n" + "Health = " + str(character.health) + "\n" + "Damage = " + str(character.damage) + "\n" ) # New line... say ( "...\n" ) # wait for a bit time.sleep(1) # Generate the damage the player inflicts for this attack playerDamageDealt = random.randint(currentPlayer.damage[0], currentPlayer.damage[1]) + itemDamage # Do the damage to the character's health character.health = character.health - playerDamageDealt # Check if the character is dead if character.health <= 0: # Give some feedback say ( "You have slain " + character.name + "!\n" ) # Set a flag for whether the character dropped any items droppedItems = False # Do this for every item... for item in character.items: # Put this item into the scene self.items.append(item) # Remember that there are dropped items droppedItems = True # Check if there are dropped items if droppedItems: # There are, so give some feedback say ( "It looks like " + character.name + " dropped something.\n" ) # Remove the character from the scene self.characters.remove(character) # The character is not dead else: # Give some feednack say ( "You attack " + character.name + " for " + str(playerDamageDealt) + " damage!\n" + character.name + " is at " + str(character.health) + " health!\n" ) # Just a new line for spacing say ( "...\n" ) # Pause for a second time.sleep(1) # Generate the amount of damage inflicted by this character this attack characterDamageDealt = random.randint(character.damage[0], character.damage[1]) # Decrease the player's health for the attck currentPlayer.health = currentPlayer.health - characterDamageDealt # Give some feedback say ( character.name + " attacked you dealing " + str(characterDamageDealt) + " damage!\n" + "You're at " + str(currentPlayer.health) + " health.\n" ) # There is no one in the scene to attack else: # Feedback say ( "You look for someone to hit but\n" + "there isn't anybody around.\n" ) # Check if the player is deady if currentPlayer.health <= 0: # Better let them know they're deady say ( "You have been slain by " + character.name + "\n" ) # Pause for effect time.sleep(1.5) # Exit. Lots of times in case we're deep down. sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit # The player is not dead so be ready else: # Get ready... self.ready() # "m": call the map method that prints out the map elif option == "m": map(self) # "go north": adds 1 to the current y coordinate elif option == "go north": newX = self.x newY = self.y + 1 os.system('clear') time.sleep(1) printOptions ( "You head north..." ) time.sleep(2) os.system('clear') self.goToNextScene(newX, newY) # "go south": minus 1 to the current y coordinate elif option == "go south": newX = self.x newY = self.y - 1 os.system('clear') time.sleep(1) printOptions ( "You head south..." ) time.sleep(2) os.system('clear') self.goToNextScene(newX, newY) # "go east": adds 1 to the current x coordinate elif option == "go east": newX = self.x + 1 newY = self.y os.system('clear') time.sleep(1) printOptions ( "You head east..." ) time.sleep(2) os.system('clear') self.goToNextScene(newX, newY) # "go west": minus 1 to the current x coordinate elif option == "go west": newX = self.x - 1 newY = self.y os.system('clear') time.sleep(1) printOptions ( "You head west..." ) time.sleep(2) os.system('clear') self.goToNextScene(newX, newY) # "exit": exit the game elif option == "exit": sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit sys.exit # to catch anything the player inputs that not an option else: say ( "There is no such thing as \"" + option + "\"" ) # return to self.ready self.ready() def goToNextScene(self, newX, newY): nextScene = False for Scene in gameScenes: if Scene.x == newX and Scene.y == newY: nextScene = Scene if nextScene: nextScene.begin() else: say ( "You can't go there, sorry!" ) self.ready() gameScenes = [] # initialising the first scene of the game # x coordinate = 0 # y coordinate = 0 # intro gameScenes.append(Scene( 0, 0, "You come to on the side of a road.\n" + "You see a caravan and dead bodies lying everywhere.\n" + "You can't remember anything. What do you do?\n", [ Item( "a dull dagger", 4 ), Item( "some mouldy bread", -1 ), Item( "a tattered cloak", 0 ) ], "Nothing has changed, you see the caravan and the dead bodies lying everywhere.", [] )) gameScenes.append(Scene( 0, 1, "After heading down the road for awhile, you see a figure\n" + "in the distance. Eventually they get closer and you see that\n" + "its an old wanderer. He sits down on the side of the road\n" + "and waves at you, you walk over to him.\n", [], "Nothing has changed, the road is still the same.\n", [ Character( "the Old Wanderer", 20, [0, 8], [ Item( "a shimmering sabre", 12 ), Item( "some smelly cheese", -4 ), Item( "a pair of well worn socks", 0 ) ] ), ] )) gameScenes.append(Scene( 1, 1, "As you continue to walk, you notice the scenery beginning\n" + "to change. It gradually becomes less green and more brown.\n" + "Eventually there aren't any plants and everything is eerily quiet.\n" + "\n" + "As you come over the next rise in the road you begin to hear a sort\n" + "of chanting. You continue walking until you come across a goblin camp.\n" + "in the middle of the camp is a pile of treasure. 4 goblins are dancing\n" + "around the treasure.\n" + "\n" + "The chanting stops and the goblins turn towards you, drawing their\n" + "weapons. They start running towards you, waving their weapins menacingly.\n", [ Item( "a jewelled dagger", 8 ), Item( "some cotton brandy", -4 ) ], "Nothing has changed, the goblin camp is still there.\n", [ Character( "a Goblin", 10, [0, 5], [ Item( "a soiled loin cloth", -20 ) ] ), Character( "a Goblin", 12, [0, 7], [ Item( "a rusty knife", 3 ) ] ), Character( "a Goblin", 7, [0, 15], [ Item( "a torn ear", 0 ) ] ), Character( "the Goblin Chief", 30, [10, 20], [ Item( "a rusty broadsword", 10 ) ] ) ] )) gameScenes.append(Scene( 1, 0, "You travel for awhile and eventually come to a meadow full\n" + "of flowers. A little girl is in the meadow picking\n" + "flowers. She looks at you cursiously as you\n" + "walk past.\n", [ Item( "a bright dandalion", 0 ), Item( "a thorny rose", 1 ) ], "Nothing has changed, the meadow is still flowery.\n", [ Character( "a Little Girl", 5, [0, 2], [ Item( "a sad bouqet", 0 ), Item( "a bloodstained dress", 0 ) ] ), ] )) gameScenes.append(Scene( 1, -1, "As you're walking along, lost in thought, you realise that the air\n" + "has become much cooler and thicker. There appear to be some ruins strewn\n" + "haphazardly around the place. You hear a spooky \"WOoooOOOOOo\" \n" + "as a ghost appears out of the ruins by your right.\n", [ Item( "a spOOky chain", 1.5 ), Item( "a blob of goo", 0 ) ], "Nothing has changed, you hear a ghostly WOooOOo in the distance.\n", [ Character( "a spoOky ghost", 40, [15, 25], [ Item( "a puff of smoke", 0 ) ] ), ] )) gameScenes.append(Scene( 0, -1, "As you're walking along, you're feet start sinking into the ground\n" + "you look around and notice that there is puddles everywhere.\n" + "You see a cabin on stilts in the middle of a big puddle.\n" + "\n" + "As you walk over to the cabin, an Ugly Witch sticks her head\n" + "out of the door and starts chanting a spell.\n" + "It doesn't look like it's going to be a nice one...\n", [ Item( "a gross toadstool", -5 ), Item( "a little toad", 0 ) ], "Nothing has changed, the swamp still smells and everything feels damp.\n", [ Character( "the Ugly Witch", 60, [15, 30], [ Item( "a magical wand", 6 ) ] ), ] )) gameScenes.append(Scene( -1, -1, "You see a great floating blur in the distance.\n" + "As you get closer, you see that it's a giant head.\n" + "\n" + "\"Hello\" says the head. \"I am Adam.\" if you can defeat\n" + "me in combat, you will reach enlightenment.\n", [], "Nothing has changed, Adam is still there, floating around.\n", [ Character( "Adam", 1000, [500, 1000], [] ) ] )) gameScenes.append(Scene( -1, 0, "As you're walking down the road, you hear a rustling beside you.\n" + "You look to see a bush that seems to be flopping along on the ground.\n" + "It seems to be some sort of useless enchanted bush.\n", [], "Nothing has changed.", [ Character( "a Floppy Bush", 1, [0, 0], [ Item( "a floppy leaf", 0 ) ] ), ] )) gameScenes.append(Scene( -1, 1, "You head into a leafy sunlit forest, you notice some small faeries\n" + "darting between the trees laughing. A badger shuffles across your\n" + "path and stops to look at you before shuffling off.\n" + "It seems like a very peacful place.\n", [], "Nothing has changed, the forest is still full of sunlight and the faeries are still laughing.", [ Character( "an Old Badger", 50, [15, 30], [ Item( "a sharp claw", 7 ), Item( "a fluffy pelt", 0 ) ] ), ] )) ################################################################################################### # MAIN ################################################################################################### ############################# ## Main is the function that ## gets called by Python when ## the program runs ############################# def main(): # Start debugging #pdb.set_trace() # clear the screen os.system('clear') # instantiate a player PlayerIG = Player() # print the start menu printOptions ( "Welcome to the land of Oooo.\n" + "Type \"help\" at anytime to see the options.\n" + "You can exit the game at anytime by typing \"exit\"\n" + "To start the game type \"start\"" ) # wait for user input option = input('-> ') # "help": to go to the help menu if option == "help": # clear the screen os.system('clear') # go to the help menu help(StartNow) # "exit": exit the game elif option == "exit": # exit the game sys.exit() # "start" start the game elif option == "start": # clear the screen os.system('clear') # go to Scene0_0.begin gameScenes[0].begin() # to catch any input that isn't an option else: say ( "Oops thats not an option\n" ) # wait 0.5 seconds time.sleep(0.5) # go back to main main() # calling main main()
""" Search and get metadata for articles in Pubmed. """ import xml.etree.ElementTree as ET import requests import logging from functools import lru_cache from time import sleep from indra.util import UnicodeXMLTreeBuilder as UTB logger = logging.getLogger(__name__) pubmed_search = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi' pubmed_fetch = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi' # Send request can't be cached by lru_cache because it takes a dict # (a mutable/unhashable type) as an argument. We cache the callers instead. def send_request(url, data): try: res = requests.get(url, params=data) except requests.exceptions.Timeout as e: logger.error('PubMed request timed out') logger.error('url: %s, data: %s' % (url, data)) logger.error(e) return None except requests.exceptions.RequestException as e: logger.error('PubMed request exception') logger.error('url: %s, data: %s' % (url, data)) logger.error(e) return None if res.status_code == 429: sleep(0.5) res = requests.get(url, params=data) if not res.status_code == 200: logger.error('Got return code %d from pubmed client.' % res.status_code) return None tree = ET.XML(res.content, parser=UTB()) return tree @lru_cache(maxsize=100) def get_ids(search_term, **kwargs): """Search Pubmed for paper IDs given a search term. Search options can be passed as keyword arguments, some of which are custom keywords identified by this function, while others are passed on as parameters for the request to the PubMed web service For details on parameters that can be used in PubMed searches, see https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch Some useful parameters to pass are db='pmc' to search PMC instead of pubmed reldate=2 to search for papers within the last 2 days mindate='2016/03/01', maxdate='2016/03/31' to search for papers in March 2016. PubMed, by default, limits returned PMIDs to a small number, and this number can be controlled by the "retmax" parameter. This function uses a retmax value of 100,000 by default that can be changed via the corresponding keyword argument. Parameters ---------- search_term : str A term for which the PubMed search should be performed. use_text_word : Optional[bool] If True, the "[tw]" string is appended to the search term to constrain the search to "text words", that is words that appear as whole in relevant parts of the PubMed entry (excl. for instance the journal name or publication date) like the title and abstract. Using this option can eliminate spurious search results such as all articles published in June for a search for the "JUN" gene, or journal names that contain Acad for a search for the "ACAD" gene. See also: https://www.nlm.nih.gov/bsd/disted/pubmedtutorial/020_760.html Default : True kwargs : kwargs Additional keyword arguments to pass to the PubMed search as parameters. """ use_text_word = kwargs.pop('use_text_word', True) if use_text_word: search_term += '[tw]' params = {'term': search_term, 'retmax': 100000, 'retstart': 0, 'db': 'pubmed', 'sort': 'pub+date'} params.update(kwargs) tree = send_request(pubmed_search, params) if tree is None: return [] if tree.find('ERROR') is not None: logger.error(tree.find('ERROR').text) return [] if tree.find('ErrorList') is not None: for err in tree.find('ErrorList').getchildren(): logger.error('Error - %s: %s' % (err.tag, err.text)) return [] count = int(tree.find('Count').text) id_terms = tree.findall('IdList/Id') if id_terms is None: return [] ids = [idt.text for idt in id_terms] if count != len(ids): logger.warning('Not all ids were retrieved for search %s;\n' 'limited at %d.' % (search_term, params['retmax'])) return ids def get_id_count(search_term): """Get the number of citations in Pubmed for a search query. Parameters ---------- search_term : str A term for which the PubMed search should be performed. Returns ------- int or None The number of citations for the query, or None if the query fails. """ params = {'term': search_term, 'rettype': 'count', 'db': 'pubmed'} tree = send_request(pubmed_search, params) if tree is None: return None else: count = tree.getchildren()[0].text return int(count) @lru_cache(maxsize=100) def get_ids_for_gene(hgnc_name, **kwargs): """Get the curated set of articles for a gene in the Entrez database. Search parameters for the Gene database query can be passed in as keyword arguments. Parameters ---------- hgnc_name : str The HGNC name of the gene. This is used to obtain the HGNC ID (using the hgnc_client module) and in turn used to obtain the Entrez ID associated with the gene. Entrez is then queried for that ID. """ from indra.databases import hgnc_client # Get the HGNC ID for the HGNC name hgnc_id = hgnc_client.get_hgnc_id(hgnc_name) if hgnc_id is None: raise ValueError('Invalid HGNC name.') # Get the Entrez ID entrez_id = hgnc_client.get_entrez_id(hgnc_id) if entrez_id is None: raise ValueError('Entrez ID not found in HGNC table.') # Query the Entrez Gene database params = {'db': 'gene', 'retmode': 'xml', 'id': entrez_id} params.update(kwargs) tree = send_request(pubmed_fetch, params) if tree is None: return [] if tree.find('ERROR') is not None: logger.error(tree.find('ERROR').text) return [] # Get all PMIDs from the XML tree id_terms = tree.findall('.//PubMedId') if id_terms is None: return [] # Use a set to remove duplicate IDs ids = list(set([idt.text for idt in id_terms])) return ids def get_ids_for_mesh(mesh_id, major_topic=False, **kwargs): """Return PMIDs that are annotated with a given MeSH ID. Parameters ---------- mesh_id : str The MeSH ID of a term to search for, e.g., D009101. major_topic : bool If True, only papers for which the given MeSH ID is annotated as a major topic are returned. Otherwise all annotations are considered. Default: False **kwargs Any further PudMed search arguments that are passed to get_ids. """ from indra.databases import mesh_client mesh_name = mesh_client.get_mesh_name(mesh_id) if not mesh_name: logger.error('Could not get MeSH name for ID %s' % mesh_id) return [] suffix = 'majr' if major_topic else 'mh' search_term = '%s [%s]' % (mesh_name, suffix) ids = get_ids(search_term, use_text_word=False, **kwargs) if mesh_id.startswith('C') and not major_topic: # Get pmids for supplementary concepts as well search_term = '%s [nm]' % mesh_name ids2 = get_ids(search_term, use_text_word=False, **kwargs) ids = list(set(ids) | set(ids2)) return ids @lru_cache(maxsize=100) def get_article_xml(pubmed_id): """Get the XML metadata for a single article from the Pubmed database. """ if pubmed_id.upper().startswith('PMID'): pubmed_id = pubmed_id[4:] params = {'db': 'pubmed', 'retmode': 'xml', 'id': pubmed_id} tree = send_request(pubmed_fetch, params) if tree is None: return None article = tree.find('PubmedArticle/MedlineCitation/Article') return article # May be none def get_title(pubmed_id): """Get the title of an article in the Pubmed database.""" article = get_article_xml(pubmed_id) if article is None: return None return _get_title_from_article_element(article) def _get_title_from_article_element(article): title_tag = article.find('ArticleTitle') title = None if title_tag is not None: title = title_tag.text if title is None and hasattr(title_tag, 'itertext'): title = ' '.join(list(title_tag.itertext())) return title def _abstract_from_article_element(article, prepend_title=False): abstract = article.findall('Abstract/AbstractText') if abstract is None: return None abstract_text = ' '.join(['' if not hasattr(abst, 'itertext') else ' '.join(list(abst.itertext())) for abst in abstract]) if prepend_title: title = _get_title_from_article_element(article) if title is not None: if not title.endswith('.'): title += '.' abstract_text = title + ' ' + abstract_text return abstract_text def get_abstract(pubmed_id, prepend_title=True): """Get the abstract of an article in the Pubmed database.""" article = get_article_xml(pubmed_id) if article is None: return None return _abstract_from_article_element(article, prepend_title) # A function to get the text for the element, or None if not found def _find_elem_text(root, xpath_string): elem = root.find(xpath_string) return None if elem is None else elem.text def _get_journal_info(medline_citation, get_issns_from_nlm): # Journal info journal = medline_citation.find('Article/Journal') journal_title = _find_elem_text(journal, 'Title') journal_abbrev = _find_elem_text(journal, 'ISOAbbreviation') # Add the ISSN from the article record issn_list = [] issn = _find_elem_text(journal, 'ISSN') if issn: issn_list.append(issn) # Add the Linking ISSN from the article record issn_linking = _find_elem_text(medline_citation, 'MedlineJournalInfo/ISSNLinking') if issn_linking: issn_list.append(issn_linking) # Now get the list of ISSNs from the NLM Catalog nlm_id = _find_elem_text(medline_citation, 'MedlineJournalInfo/NlmUniqueID') if nlm_id and get_issns_from_nlm: nlm_issn_list = get_issns_for_journal(nlm_id) if nlm_issn_list: issn_list += nlm_issn_list # Remove any duplicate issns issn_list = list(set(issn_list)) return {'journal_title': journal_title, 'journal_abbrev': journal_abbrev, 'issn_list': issn_list, 'journal_nlm_id': nlm_id} def _get_pubmed_publication_date(pubmed_data): date_dict = dict.fromkeys(['year', 'month', 'day']) # Order potential statuses in order of preferences status_list = ['pubmed', 'accepted', 'revised', 'received', 'entrez'] # Look for various statuses, in order of preference as PubStatus in # PubmedPubDate for status in status_list: pubmed_pub_date = \ pubmed_data.find('./History/PubMedPubDate[@PubStatus="%s"]' % status) if pubmed_pub_date is not None: break else: logger.warning("Could not find pub date in: \n%s" % ET.tostring(pubmed_data).decode('utf-8')) return date_dict def _find_date(element): value = _find_elem_text(pubmed_pub_date, element) return int(value) if value else None # Get date elements from extracted pubmed_pub_date element for date_elem in ['Year', 'Month', 'Day']: date_dict[date_elem.lower()] = _find_date(date_elem) return date_dict def _get_article_info(medline_citation, pubmed_data): article = medline_citation.find('Article') pmid = _find_elem_text(medline_citation, './PMID') pii = _find_elem_text(article, './ELocationID[@EIdType="pii"][@ValidYN="Y"]') # Look for the DOI in the ELocationID field... doi = _find_elem_text(article, './ELocationID[@EIdType="doi"][@ValidYN="Y"]') # ...and if that doesn't work, look in the ArticleIdList if doi is None: doi = _find_elem_text(pubmed_data, './/ArticleId[@IdType="doi"]') # Try to get the PMCID pmcid = _find_elem_text(pubmed_data, './/ArticleId[@IdType="pmc"]') # Title title = _get_title_from_article_element(article) # Author list author_elems = article.findall('AuthorList/Author/LastName') author_names = None if author_elems is None \ else [au.text for au in author_elems] # Get the page number entry page = _find_elem_text(article, 'Pagination/MedlinePgn') return {'pmid': pmid, 'pii': pii, 'doi': doi, 'pmcid': pmcid, 'title': title, 'authors': author_names, 'page': page} def get_metadata_from_xml_tree(tree, get_issns_from_nlm=False, get_abstracts=False, prepend_title=False, mesh_annotations=False): """Get metadata for an XML tree containing PubmedArticle elements. Documentation on the XML structure can be found at: - https://www.nlm.nih.gov/bsd/licensee/elements_descriptions.html - https://www.nlm.nih.gov/bsd/licensee/elements_alphabetical.html Parameters ---------- tree : xml.etree.ElementTree ElementTree containing one or more PubmedArticle elements. get_issns_from_nlm : bool Look up the full list of ISSN number for the journal associated with the article, which helps to match articles to CrossRef search results. Defaults to False, since it slows down performance. get_abstracts : bool Indicates whether to include the Pubmed abstract in the results. prepend_title : bool If get_abstracts is True, specifies whether the article title should be prepended to the abstract text. mesh_annotations : bool If True, extract mesh annotations from the pubmed entries and include in the returned data. If false, don't. Returns ------- dict of dicts Dictionary indexed by PMID. Each value is a dict containing the following fields: 'doi', 'title', 'authors', 'journal_title', 'journal_abbrev', 'journal_nlm_id', 'issn_list', 'page'. """ # Iterate over the articles and build the results dict results = {} pm_articles = tree.findall('./PubmedArticle') for art_ix, pm_article in enumerate(pm_articles): medline_citation = pm_article.find('./MedlineCitation') pubmed_data = pm_article.find('PubmedData') article_info = _get_article_info(medline_citation, pubmed_data) journal_info = _get_journal_info(medline_citation, get_issns_from_nlm) context_info = _get_annotations(medline_citation) publication_date = _get_pubmed_publication_date(pubmed_data) # Build the result result = {} result.update(article_info) result.update(journal_info) result.update(context_info) result['publication_date'] = publication_date # Get the abstracts if requested if get_abstracts: abstract = _abstract_from_article_element( medline_citation.find('Article'), prepend_title=prepend_title ) result['abstract'] = abstract # Add to dict results[article_info['pmid']] = result return results def _get_annotations(medline_citation): def _major_topic(e): if e is not None and e.get('MajorTopicYN').upper() == 'Y': return True return False info = [] for elem in medline_citation.findall('.//MeshHeading'): dname = elem.find('DescriptorName') qname = elem.find('QualifierName') mid = dname.attrib['UI'] major = _major_topic(dname) or _major_topic(qname) if qname is not None: qual = {'text': qname.text, 'mesh': qname.attrib['UI']} else: qual = None info.append({'mesh': mid, 'text': dname.text, 'major_topic': major, 'qualifier': qual}) return {'mesh_annotations': info} def get_metadata_for_ids(pmid_list, get_issns_from_nlm=False, get_abstracts=False, prepend_title=False): """Get article metadata for up to 200 PMIDs from the Pubmed database. Parameters ---------- pmid_list : list of str Can contain 1-200 PMIDs. get_issns_from_nlm : bool Look up the full list of ISSN number for the journal associated with the article, which helps to match articles to CrossRef search results. Defaults to False, since it slows down performance. get_abstracts : bool Indicates whether to include the Pubmed abstract in the results. prepend_title : bool If get_abstracts is True, specifies whether the article title should be prepended to the abstract text. Returns ------- dict of dicts Dictionary indexed by PMID. Each value is a dict containing the following fields: 'doi', 'title', 'authors', 'journal_title', 'journal_abbrev', 'journal_nlm_id', 'issn_list', 'page'. """ if len(pmid_list) > 200: raise ValueError("Metadata query is limited to 200 PMIDs at a time.") params = {'db': 'pubmed', 'retmode': 'xml', 'id': pmid_list} tree = send_request(pubmed_fetch, params) if tree is None: return None return get_metadata_from_xml_tree(tree, get_issns_from_nlm, get_abstracts, prepend_title) @lru_cache(maxsize=1000) def get_issns_for_journal(nlm_id): """Get a list of the ISSN numbers for a journal given its NLM ID. Information on NLM XML DTDs is available at https://www.nlm.nih.gov/databases/dtd/ """ params = {'db': 'nlmcatalog', 'retmode': 'xml', 'id': nlm_id} tree = send_request(pubmed_fetch, params) if tree is None: return None issn_list = tree.findall('.//ISSN') issn_linking = tree.findall('.//ISSNLinking') issns = issn_list + issn_linking # No ISSNs found! if not issns: return None else: return [issn.text for issn in issns] def expand_pagination(pages): """Convert a page number to long form, e.g., from 456-7 to 456-457.""" # If there is no hyphen, it's a single page, and we're good to go parts = pages.split('-') if len(parts) == 1: # No hyphen, so no split return pages elif len(parts) == 2: start = parts[0] end = parts[1] # If the end is the same number of digits as the start, then we # don't change anything! if len(start) == len(end): return pages # Otherwise, replace the last digits of start with the digits of end num_end_digits = len(end) new_end = start[:-num_end_digits] + end return '%s-%s' % (start, new_end) else: # More than one hyphen, something weird happened logger.warning("Multiple hyphens in page number: %s" % pages) return pages
#!/usr/bin/env python # # Copyright (c) 2013 Corey Goldberg # # This file is part of: sauceclient # https://github.com/cgoldberg/sauceclient # # 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 # import os import random import unittest import sauceclient # set these to run tests SAUCE_USERNAME = os.environ.get('SAUCE_USERNAME', '') SAUCE_ACCESS_KEY = os.environ.get('SAUCE_ACCESS_KEY', '') TEST_JOB_ID = os.environ.get('TEST_JOB_ID', '') # any valid job class TestSauceClient(unittest.TestCase): def setUp(self): self.sc = sauceclient.SauceClient( SAUCE_USERNAME, SAUCE_ACCESS_KEY, ) def test_has_instances(self): self.assertIsInstance(self.sc.information, sauceclient.Information) self.assertIsInstance(self.sc.jobs, sauceclient.Jobs) self.assertIsInstance(self.sc.provisioning, sauceclient.Provisioning) self.assertIsInstance(self.sc.usage, sauceclient.Usage) def test_headers(self): headers = self.sc.headers self.assertIsInstance(headers, dict) self.assertIn('Authorization', headers) self.assertIn('Content-Type', headers) self.assertIn('Basic', headers['Authorization']) self.assertEqual('application/json', headers['Content-Type']) def test_request_get(self): url = 'rest/v1/info/status' json_data = self.sc.request('GET', url) self.assertIsInstance(json_data, str) class TestJobs(unittest.TestCase): def setUp(self): self.sc = sauceclient.SauceClient( SAUCE_USERNAME, SAUCE_ACCESS_KEY, ) def test_get_job_ids(self): job_ids = self.sc.jobs.get_job_ids() self.assertIsInstance(job_ids, list) job_id = random.choice(job_ids) self.assertIsInstance(job_id, unicode) self.assertTrue(job_id.isalnum()) def test_get_jobs(self): jobs = self.sc.jobs.get_jobs() self.assertIsInstance(jobs, list) job = random.choice(jobs) self.assertIn('id', job) self.assertIsInstance(job['id'], unicode) self.assertEqual(job['owner'], self.sc.sauce_username) def test_get_job_attributes(self): job_attributes = self.sc.jobs.get_job_attributes(TEST_JOB_ID) self.assertIsInstance(job_attributes, dict) self.assertIn('id', job_attributes) self.assertIn('status', job_attributes) self.assertIn('commands_not_successful', job_attributes) self.assertIn('name', job_attributes) self.assertIn('video_url', job_attributes) self.assertIn('tags', job_attributes) self.assertIn('start_time', job_attributes) self.assertIn('log_url', job_attributes) self.assertIn('creation_time', job_attributes) self.assertIn('custom-data', job_attributes) self.assertIn('browser_version', job_attributes) self.assertIn('end_time', job_attributes) self.assertIn('passed', job_attributes) self.assertIn('owner', job_attributes) self.assertIn('browser', job_attributes) self.assertIn('os', job_attributes) self.assertIn('public', job_attributes) self.assertIn('breakpointed', job_attributes) self.assertIn('build', job_attributes) self.assertEqual(job_attributes['id'], TEST_JOB_ID) self.assertIn(job_attributes['owner'], self.sc.sauce_username) def test_update_job(self): job_attributes = self.sc.jobs.update_job(TEST_JOB_ID) self.assertIsInstance(job_attributes, dict) self.assertIn('id', job_attributes) self.assertEqual(job_attributes['id'], TEST_JOB_ID) class TestProvisioning(unittest.TestCase): def setUp(self): self.sc = sauceclient.SauceClient( SAUCE_USERNAME, SAUCE_ACCESS_KEY, ) def test_get_account_details(self): account_details = self.sc.provisioning.get_account_details() self.assertIsInstance(account_details, dict) self.assertIn('id', account_details) self.assertIn('minutes', account_details) self.assertIn('access_key', account_details) self.assertIn('subscribed', account_details) self.assertEqual(account_details['id'], self.sc.sauce_username) def test_get_account_limits(self): account_limits = self.sc.provisioning.get_account_limits() self.assertIsInstance(account_limits, dict) self.assertIn('concurrency', account_limits) self.assertTrue(account_limits['concurrency'] > 0) class TestInformation(unittest.TestCase): def setUp(self): self.sc = sauceclient.SauceClient() def test_get_status(self): status = self.sc.information.get_status() self.assertIsInstance(status, dict) self.assertIn('service_operational', status) self.assertIn('status_message', status) self.assertIn('wait_time', status) self.assertIsInstance(status['status_message'], unicode) self.assertTrue(status['service_operational']) def test_get_status_with_auth(self): sc = sauceclient.SauceClient( SAUCE_USERNAME, SAUCE_ACCESS_KEY, ) status = sc.information.get_status() self.assertIsInstance(status, dict) self.assertIn('service_operational', status) self.assertIn('status_message', status) self.assertIn('wait_time', status) self.assertTrue(status['service_operational']) def test_get_browswers(self): browsers = self.sc.information.get_browsers() self.assertIsInstance(browsers, list) self.assertTrue(len(browsers) > 0) browser = random.choice(browsers) self.assertIn('automation_backend', browser) self.assertIn('long_name', browser) self.assertIn('long_version', browser) self.assertIn('os', browser) self.assertIn('selenium_name', browser) self.assertIn('short_version', browser) self.assertIsInstance(browser['selenium_name'], unicode) def test_get_count(self): count = self.sc.information.get_count() self.assertIsInstance(count, int) self.assertTrue(count > 20000000) class TestUsage(unittest.TestCase): def setUp(self): self.sc = sauceclient.SauceClient( SAUCE_USERNAME, SAUCE_ACCESS_KEY, ) def test_get_current_activity(self): activity = self.sc.usage.get_current_activity() self.assertIsInstance(activity, dict) self.assertIn('subaccounts', activity) self.assertIn(SAUCE_USERNAME, activity['subaccounts']) subaccount_activity = activity['subaccounts'][self.sc.sauce_username] self.assertIn('all', subaccount_activity) self.assertIsInstance(subaccount_activity['all'], int) self.assertIn('in progress', subaccount_activity) self.assertIsInstance(subaccount_activity['in progress'], int) self.assertIn('queued', subaccount_activity) self.assertIsInstance(subaccount_activity['queued'], int) self.assertIn('totals', activity) self.assertIn('all', activity['totals']) self.assertIsInstance(activity['totals']['all'], int) self.assertIn('in progress', activity['totals']) self.assertIsInstance(activity['totals']['in progress'], int) self.assertIn('queued', activity['totals']) self.assertIsInstance(activity['totals']['queued'], int) def test_get_historical_usage(self): historical_usage = self.sc.usage.get_historical_usage() self.assertIn('usage', historical_usage) self.assertIn('username', historical_usage) self.assertEqual(historical_usage['username'], self.sc.sauce_username) self.assertIsInstance(historical_usage['usage'], list) if __name__ == '__main__': if not all((SAUCE_USERNAME, SAUCE_ACCESS_KEY, TEST_JOB_ID)): raise SystemExit('Set your credentials (username/access-key)') unittest.main(verbosity=2)
# Tweepy # Copyright 2009 Joshua Roesslein # See LICENSE import time import threading import os import cPickle as pickle try: import hashlib except ImportError: # python 2.4 import md5 as hashlib try: import fcntl except ImportError: # Probably on a windows system # TODO: use win32file pass class Cache(object): """Cache interface""" def __init__(self, timeout=60): """Initialize the cache timeout: number of seconds to keep a cached entry """ self.timeout = timeout def store(self, key, value): """Add new record to cache key: entry key value: data of entry """ raise NotImplementedError def get(self, key, timeout=None): """Get cached entry if exists and not expired key: which entry to get timeout: override timeout with this value [optional] """ raise NotImplementedError def count(self): """Get count of entries currently stored in cache""" raise NotImplementedError def cleanup(self): """Delete any expired entries in cache.""" raise NotImplementedError def flush(self): """Delete all cached entries""" raise NotImplementedError class MemoryCache(Cache): """In-memory cache""" def __init__(self, timeout=60): Cache.__init__(self, timeout) self._entries = {} self.lock = threading.Lock() def __getstate__(self): # pickle return {'entries': self._entries, 'timeout': self.timeout} def __setstate__(self, state): # unpickle self.lock = threading.Lock() self._entries = state['entries'] self.timeout = state['timeout'] def _is_expired(self, entry, timeout): return timeout > 0 and (time.time() - entry[0]) >= timeout def store(self, key, value): self.lock.acquire() self._entries[key] = (time.time(), value) self.lock.release() def get(self, key, timeout=None): self.lock.acquire() try: # check to see if we have this key entry = self._entries.get(key) if not entry: # no hit, return nothing return None # use provided timeout in arguments if provided # otherwise use the one provided during init. if timeout is None: timeout = self.timeout # make sure entry is not expired if self._is_expired(entry, timeout): # entry expired, delete and return nothing del self._entries[key] return None # entry found and not expired, return it return entry[1] finally: self.lock.release() def count(self): return len(self._entries) def cleanup(self): self.lock.acquire() try: for k, v in self._entries.items(): if self._is_expired(v, self.timeout): del self._entries[k] finally: self.lock.release() def flush(self): self.lock.acquire() self._entries.clear() self.lock.release() class FileCache(Cache): """File-based cache""" # locks used to make cache thread-safe cache_locks = {} def __init__(self, cache_dir, timeout=60): Cache.__init__(self, timeout) if os.path.exists(cache_dir) is False: os.mkdir(cache_dir) self.cache_dir = cache_dir if cache_dir in FileCache.cache_locks: self.lock = FileCache.cache_locks[cache_dir] else: self.lock = threading.Lock() FileCache.cache_locks[cache_dir] = self.lock if os.name == 'posix': self._lock_file = self._lock_file_posix self._unlock_file = self._unlock_file_posix elif os.name == 'nt': self._lock_file = self._lock_file_win32 self._unlock_file = self._unlock_file_win32 else: print 'Warning! FileCache locking not supported on this system!' self._lock_file = self._lock_file_dummy self._unlock_file = self._unlock_file_dummy def _get_path(self, key): md5 = hashlib.md5() md5.update(key) return os.path.join(self.cache_dir, md5.hexdigest()) def _lock_file_dummy(self, path, exclusive=True): return None def _unlock_file_dummy(self, lock): return def _lock_file_posix(self, path, exclusive=True): lock_path = path + '.lock' if exclusive is True: f_lock = open(lock_path, 'w') fcntl.lockf(f_lock, fcntl.LOCK_EX) else: f_lock = open(lock_path, 'r') fcntl.lockf(f_lock, fcntl.LOCK_SH) if os.path.exists(lock_path) is False: f_lock.close() return None return f_lock def _unlock_file_posix(self, lock): lock.close() def _lock_file_win32(self, path, exclusive=True): # TODO: implement return None def _unlock_file_win32(self, lock): # TODO: implement return def _delete_file(self, path): os.remove(path) if os.path.exists(path + '.lock'): os.remove(path + '.lock') def store(self, key, value): path = self._get_path(key) self.lock.acquire() try: # acquire lock and open file f_lock = self._lock_file(path) datafile = open(path, 'wb') # write data pickle.dump((time.time(), value), datafile) # close and unlock file datafile.close() self._unlock_file(f_lock) finally: self.lock.release() def get(self, key, timeout=None): return self._get(self._get_path(key), timeout) def _get(self, path, timeout): if os.path.exists(path) is False: # no record return None self.lock.acquire() try: # acquire lock and open f_lock = self._lock_file(path, False) datafile = open(path, 'rb') # read pickled object created_time, value = pickle.load(datafile) datafile.close() # check if value is expired if timeout is None: timeout = self.timeout if timeout > 0 and (time.time() - created_time) >= timeout: # expired! delete from cache value = None self._delete_file(path) # unlock and return result self._unlock_file(f_lock) return value finally: self.lock.release() def count(self): c = 0 for entry in os.listdir(self.cache_dir): if entry.endswith('.lock'): continue c += 1 return c def cleanup(self): for entry in os.listdir(self.cache_dir): if entry.endswith('.lock'): continue self._get(os.path.join(self.cache_dir, entry), None) def flush(self): for entry in os.listdir(self.cache_dir): if entry.endswith('.lock'): continue self._delete_file(os.path.join(self.cache_dir, entry))
# Copyright 2013 Google 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. """Utility methods used by the deploy command.""" import os import re from gae_ext_runtime import ext_runtime from googlecloudsdk.api_lib.app import cloud_build from googlecloudsdk.api_lib.app import docker_image from googlecloudsdk.api_lib.app import metric_names from googlecloudsdk.api_lib.app import util from googlecloudsdk.api_lib.app.images import config from googlecloudsdk.api_lib.app.images import docker_util from googlecloudsdk.api_lib.app.runtimes import fingerprinter from googlecloudsdk.api_lib.source import context_util from googlecloudsdk.core import exceptions from googlecloudsdk.core import log from googlecloudsdk.core import metrics from googlecloudsdk.core import properties from googlecloudsdk.core.console import console_io from googlecloudsdk.core.docker import constants from googlecloudsdk.core.docker import docker from googlecloudsdk.third_party.appengine.api import appinfo DEFAULT_DOMAIN = 'appspot.com' DEFAULT_MODULE = 'default' ALT_SEPARATOR = '-dot-' MAX_DNS_LABEL_LENGTH = 63 # http://tools.ietf.org/html/rfc2181#section-11 # Wait this long before displaying an additional message _PREPARE_VM_MESSAGE_DELAY = 15 class DockerfileError(exceptions.Error): """Raised if a Dockerfile was found along with a non-custom runtime.""" class NoDockerfileError(exceptions.Error): """No Dockerfile found.""" class UnsupportedRuntimeError(exceptions.Error): """Raised if we are unable to detect the runtime.""" def _GetDockerfileCreator(info, config_cleanup=None): """Returns a function to create a dockerfile if the user doesn't have one. Args: info: (googlecloudsdk.api_lib.app.yaml_parsing.ModuleYamlInfo) The module config. config_cleanup: (callable() or None) If a temporary Dockerfile has already been created during the course of the deployment, this should be a callable that deletes it. Raises: DockerfileError: Raised if a user supplied a Dockerfile and a non-custom runtime. NoDockerfileError: Raised if a user didn't supply a Dockerfile and chose a custom runtime. UnsupportedRuntimeError: Raised if we can't detect a runtime. Returns: callable(), a function that can be used to create the correct Dockerfile later on. """ # Use the path to app.yaml (info.file) to determine the location of the # Dockerfile. dockerfile_dir = os.path.dirname(info.file) dockerfile = os.path.join(dockerfile_dir, 'Dockerfile') if config_cleanup: # Dockerfile has already been generated. It still needs to be cleaned up. # This must be before the other conditions, since it's a special case. return lambda: config_cleanup if info.runtime != 'custom' and os.path.exists(dockerfile): raise DockerfileError( 'There is a Dockerfile in the current directory, and the runtime field ' 'in {0} is currently set to [runtime: {1}]. To use your Dockerfile to ' 'build a custom runtime, set the runtime field in {0} to ' '[runtime: custom]. To continue using the [{1}] runtime, please omit ' 'the Dockerfile from this directory.'.format(info.file, info.runtime)) # If we're "custom" there needs to be a Dockerfile. if info.runtime == 'custom': if os.path.exists(dockerfile): log.info('Using %s found in %s', config.DOCKERFILE, dockerfile_dir) def NullGenerator(): return lambda: None return NullGenerator else: raise NoDockerfileError( 'You must provide your own Dockerfile when using a custom runtime. ' 'Otherwise provide a "runtime" field with one of the supported ' 'runtimes.') # Check the fingerprinting based code. params = ext_runtime.Params(appinfo=info.parsed, deploy=True) configurator = fingerprinter.IdentifyDirectory(dockerfile_dir, params) if configurator: return configurator.GenerateConfigs # Then throw an error. else: raise UnsupportedRuntimeError( 'We were unable to detect the runtime to use for this application. ' 'Please specify the [runtime] field in your application yaml file ' 'or check that your application is configured correctly.') def _GetDomainAndDisplayId(project_id): """Returns tuple (displayed app id, domain).""" l = project_id.split(':') if len(l) == 1: return l[0], None return l[1], l[0] def _GetImageName(project, module, version): """Returns image tag according to App Engine convention.""" display, domain = _GetDomainAndDisplayId(project) return (config.DOCKER_IMAGE_NAME_DOMAIN_FORMAT if domain else config.DOCKER_IMAGE_NAME_FORMAT).format( display=display, domain=domain, module=module, version=version) def BuildAndPushDockerImages(module_configs, version_id, cloudbuild_client, storage_client, http, code_bucket_ref, cli, remote, source_contexts, config_cleanup): """Builds and pushes a set of docker images. Args: module_configs: A map of module name to parsed config. version_id: The version id to deploy these modules under. cloudbuild_client: An instance of the cloudbuild.CloudBuildV1 api client. storage_client: An instance of the storage_v1.StorageV1 client. http: a http provider that can be used to create API clients code_bucket_ref: The reference to the GCS bucket where the source will be uploaded. cli: calliope.cli.CLI, The CLI object representing this command line tool. remote: Whether the user specified a remote build. source_contexts: A list of json-serializable source contexts to place in the application directory for each config. config_cleanup: (callable() or None) If a temporary Dockerfile has already been created during the course of the deployment, this should be a callable that deletes it. Returns: A dictionary mapping modules to the name of the pushed container image. """ project = properties.VALUES.core.project.Get(required=True) use_cloud_build = properties.VALUES.app.use_cloud_build.GetBool() # Prepare temporary dockerfile creators for all modules that need them # before doing the heavy lifting so we can fail fast if there are errors. modules = [] for (name, info) in module_configs.iteritems(): if info.RequiresImage(): context_creator = context_util.GetSourceContextFilesCreator( os.path.dirname(info.file), source_contexts) modules.append((name, info, _GetDockerfileCreator(info, config_cleanup), context_creator)) if not modules: # No images need to be built. return {} log.status.Print('Verifying that Managed VMs are enabled and ready.') if use_cloud_build: return _BuildImagesWithCloudBuild(project, modules, version_id, code_bucket_ref, cloudbuild_client, storage_client, http) # Update docker client's credentials. for registry_host in constants.ALL_SUPPORTED_REGISTRIES: docker.UpdateDockerCredentials(registry_host) metrics.CustomTimedEvent(metric_names.DOCKER_UPDATE_CREDENTIALS) # Build docker images. images = {} with docker_util.DockerHost( cli, version_id, remote, project) as docker_client: # Build and push all images. for module, info, ensure_dockerfile, ensure_context in modules: log.status.Print( 'Building and pushing image for module [{module}]' .format(module=module)) cleanup_dockerfile = ensure_dockerfile() cleanup_context = ensure_context() try: image_name = _GetImageName(project, module, version_id) images[module] = BuildAndPushDockerImage( info.file, docker_client, image_name) finally: cleanup_dockerfile() cleanup_context() metric_name = (metric_names.DOCKER_REMOTE_BUILD if remote else metric_names.DOCKER_BUILD) metrics.CustomTimedEvent(metric_name) return images def _BuildImagesWithCloudBuild(project, modules, version_id, code_bucket_ref, cloudbuild_client, storage_client, http): """Build multiple modules with Cloud Build.""" images = {} for module, info, ensure_dockerfile, ensure_context in modules: log.status.Print( 'Building and pushing image for module [{module}]' .format(module=module)) cleanup_dockerfile = ensure_dockerfile() cleanup_context = ensure_context() try: image = docker_image.Image( dockerfile_dir=os.path.dirname(info.file), tag=_GetImageName(project, module, version_id), nocache=False) cloud_build.UploadSource(image.dockerfile_dir, code_bucket_ref, image.tag, storage_client) metrics.CustomTimedEvent(metric_names.CLOUDBUILD_UPLOAD) cloud_build.ExecuteCloudBuild(project, code_bucket_ref, image.tag, image.repo_tag, cloudbuild_client, http) metrics.CustomTimedEvent(metric_names.CLOUDBUILD_EXECUTE) images[module] = image.repo_tag finally: cleanup_dockerfile() cleanup_context() return images def DoPrepareManagedVms(gae_client): """Call an API to prepare the for managed VMs.""" try: message = 'If this is your first deployment, this may take a while' with console_io.DelayedProgressTracker(message, _PREPARE_VM_MESSAGE_DELAY): # Note: this doesn't actually boot the VM, it just prepares some stuff # for the project via an undocumented Admin API. gae_client.PrepareVmRuntime() log.status.Print() except util.RPCError: log.warn('If this is your first deployment, please try again.') raise def BuildAndPushDockerImage(appyaml_path, docker_client, image_name): """Builds Docker image and pushes it onto Google Cloud Storage. Workflow: Connects to Docker daemon. Builds user image. Pushes an image to GCR. Args: appyaml_path: str, Path to the app.yaml for the module. Dockerfile must be located in the same directory. docker_client: docker.Client instance. image_name: str, The name to build the image as. Returns: The name of the pushed image. """ dockerfile_dir = os.path.dirname(appyaml_path) image = docker_image.Image(dockerfile_dir=dockerfile_dir, tag=image_name, nocache=False) image.Build(docker_client) image.Push(docker_client) return image.repo_tag def UseSsl(handlers): """Returns whether the root URL for an application is served over HTTPS. More specifically, returns the 'secure' setting of the handler that will serve the application. This can be 'always', 'optional', or 'never', depending on when the URL is served over HTTPS. Will miss a small number of cases, but HTTP is always okay (an HTTP URL to an HTTPS-only service will result in a redirect). Args: handlers: List of googlecloudsdk.third_party.appengine.api.appinfo.URLMap, the configured URL handlers for the application Returns: str, the 'secure' setting of the handler for the root URL. """ for handler in handlers: try: if re.match(handler.url + '$', '/'): return handler.secure except re.error: # AppEngine uses POSIX Extended regular expressions, which are not 100% # compatible with Python's re module. pass return appinfo.SECURE_HTTP def GetAppHostname(app_id, module=None, version=None, use_ssl=appinfo.SECURE_HTTP): """Returns the hostname of the given version of the deployed app. Args: app_id: str, project ID. module: str, the (optional) module being deployed version: str, the deployed version ID (omit to get the default version URL). use_ssl: bool, whether to construct an HTTPS URL. Returns: str. Constructed URL. Raises: googlecloudsdk.core.exceptions.Error: if an invalid app_id is supplied. """ if not app_id: msg = 'Must provide a valid app ID to construct a hostname.' raise exceptions.Error(msg) version = version or '' module = module or '' if module == DEFAULT_MODULE: module = '' domain = DEFAULT_DOMAIN if ':' in app_id: domain, app_id = app_id.split(':') if module == DEFAULT_MODULE: module = '' # Normally, AppEngine URLs are of the form # 'http[s]://version.module.app.appspot.com'. However, the SSL certificate for # appspot.com is not valid for subdomains of subdomains of appspot.com (e.g. # 'https://app.appspot.com/' is okay; 'https://module.app.appspot.com/' is # not). To deal with this, AppEngine recognizes URLs like # 'http[s]://version-dot-module-dot-app.appspot.com/'. # # This works well as long as the domain name part constructed in this fashion # is less than 63 characters long, as per the DNS spec. If the domain name # part is longer than that, we are forced to use the URL with an invalid # certificate. # # We've tried to do the best possible thing in every case here. subdomain_parts = filter(bool, [version, module, app_id]) scheme = 'http' if use_ssl == appinfo.SECURE_HTTP: subdomain = '.'.join(subdomain_parts) scheme = 'http' else: subdomain = ALT_SEPARATOR.join(subdomain_parts) if len(subdomain) <= MAX_DNS_LABEL_LENGTH: scheme = 'https' else: subdomain = '.'.join(subdomain_parts) if use_ssl == appinfo.SECURE_HTTP_OR_HTTPS: scheme = 'http' elif use_ssl == appinfo.SECURE_HTTPS: msg = ('Most browsers will reject the SSL certificate for module {0}. ' 'Please verify that the certificate corresponds to the parent ' 'domain of your application when you connect.').format(module) log.warn(msg) scheme = 'https' return '{0}://{1}.{2}'.format(scheme, subdomain, domain) def GetStopPreviousVersionFromArgs(args): """Returns whether to stop previous version, based on environment/arguments. Whether to stop is determined based on the following (in decreasing precedence order): 1. if a command-line flag is set 2. if the `stop_previous_version` property is set 3. the default: True Issues appropriate warnings: * if the user gives no indication of having seen the warning (i.e. no `--[no-]stop_previous_version` flag and no `stop_previous_version` property set, issue a comprehensive warning about changes coming and what to do about it. Args: args: the parsed command-line arguments for the command invocation. Returns: bool, whether to promote the deployment """ # 1. Check command-line flags stop_previous_version = properties.VALUES.app.stop_previous_version.GetBool() if args.stop_previous_version is not None: return args.stop_previous_version # 2. Check `stop_previous_version` property if stop_previous_version is not None: return stop_previous_version # 3. Default value return True
#!/usr/bin/env python # # __COPYRIGHT__ # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os.path import string import sys import time import TestSCons _exe = TestSCons._exe fortran_runtime = TestSCons.fortran_lib test = TestSCons.TestSCons() fortran = test.detect('FORTRAN') foo11 = test.workpath('work1', 'build', 'var1', 'foo1' + _exe) foo12 = test.workpath('work1', 'build', 'var1', 'foo2' + _exe) foo21 = test.workpath('work1', 'build', 'var2', 'foo1' + _exe) foo22 = test.workpath('work1', 'build', 'var2', 'foo2' + _exe) foo31 = test.workpath('work1', 'build', 'var3', 'foo1' + _exe) foo32 = test.workpath('work1', 'build', 'var3', 'foo2' + _exe) foo41 = test.workpath('work1', 'build', 'var4', 'foo1' + _exe) foo42 = test.workpath('work1', 'build', 'var4', 'foo2' + _exe) foo51 = test.workpath('build', 'var5', 'foo1' + _exe) foo52 = test.workpath('build', 'var5', 'foo2' + _exe) bar11 = test.workpath('work1', 'build', 'var1', 'bar1' + _exe) bar12 = test.workpath('work1', 'build', 'var1', 'bar2' + _exe) bar21 = test.workpath('work1', 'build', 'var2', 'bar1' + _exe) bar22 = test.workpath('work1', 'build', 'var2', 'bar2' + _exe) bar31 = test.workpath('work1', 'build', 'var3', 'bar1' + _exe) bar32 = test.workpath('work1', 'build', 'var3', 'bar2' + _exe) bar41 = test.workpath('work1', 'build', 'var4', 'bar1' + _exe) bar42 = test.workpath('work1', 'build', 'var4', 'bar2' + _exe) bar51 = test.workpath('build', 'var5', 'bar1' + _exe) bar52 = test.workpath('build', 'var5', 'bar2' + _exe) test.subdir('work1', 'work2', 'work3') test.write(['work1', 'SConstruct'], """ src = Dir('src') var2 = Dir('build/var2') var3 = Dir('build/var3') var4 = Dir('build/var4') var5 = Dir('../build/var5') var6 = Dir('../build/var6') env = Environment(BUILD = 'build', SRC = 'src') BuildDir('build/var1', src) BuildDir(var2, src) BuildDir(var3, src, duplicate=0) env.BuildDir("$BUILD/var4", "$SRC", duplicate=0) BuildDir(var5, src, duplicate=0) BuildDir(var6, src) env = Environment(CPPPATH='#src', FORTRANPATH='#src') SConscript('build/var1/SConscript', "env") SConscript('build/var2/SConscript', "env") env = Environment(CPPPATH=src, FORTRANPATH=src) SConscript('build/var3/SConscript', "env") SConscript(File('SConscript', var4), "env") env = Environment(CPPPATH='.', FORTRANPATH='.') SConscript('../build/var5/SConscript', "env") SConscript('../build/var6/SConscript', "env") """) test.subdir(['work1', 'src']) test.write(['work1', 'src', 'SConscript'], """ import os import os.path def buildIt(target, source, env): if not os.path.exists('build'): os.mkdir('build') f1=open(str(source[0]), 'r') f2=open(str(target[0]), 'w') f2.write(f1.read()) f2.close() f1.close() return 0 Import("env") env.Command(target='f2.c', source='f2.in', action=buildIt) env.Program(target='foo2', source='f2.c') env.Program(target='foo1', source='f1.c') env.Command(target='f3.h', source='f3h.in', action=buildIt) env.Command(target='f4.h', source='f4h.in', action=buildIt) env.Command(target='f4.c', source='f4.in', action=buildIt) env2=env.Clone(CPPPATH='.') env2.Program(target='foo3', source='f3.c') env2.Program(target='foo4', source='f4.c') try: fortran = env.subst('$FORTRAN') except: fortran = None if fortran and env.Detect(fortran): env.Command(target='b2.f', source='b2.in', action=buildIt) env.Clone(LIBS = %s).Program(target='bar2', source='b2.f') env.Clone(LIBS = %s).Program(target='bar1', source='b1.f') """ % (fortran_runtime, fortran_runtime)) test.write(['work1', 'src', 'f1.c'], r""" #include <stdio.h> #include <stdlib.h> #include "f1.h" int main(int argc, char *argv[]) { argv[argc++] = "--"; printf(F1_STR); exit (0); } """) test.write(['work1', 'src', 'f2.in'], r""" #include <stdio.h> #include <stdlib.h> #include "f2.h" int main(int argc, char *argv[]) { argv[argc++] = "--"; printf(F2_STR); exit (0); } """) test.write(['work1', 'src', 'f3.c'], r""" #include <stdio.h> #include <stdlib.h> #include "f3.h" int main(int argc, char *argv[]) { argv[argc++] = "--"; printf(F3_STR); exit (0); } """) test.write(['work1', 'src', 'f4.in'], r""" #include <stdio.h> #include <stdlib.h> #include "f4.h" int main(int argc, char *argv[]) { argv[argc++] = "--"; printf(F4_STR); exit (0); } """) test.write(['work1', 'src', 'f1.h'], r""" #define F1_STR "f1.c\n" """) test.write(['work1', 'src', 'f2.h'], r""" #define F2_STR "f2.c\n" """) test.write(['work1', 'src', 'f3h.in'], r""" #define F3_STR "f3.c\n" """) test.write(['work1', 'src', 'f4h.in'], r""" #define F4_STR "f4.c\n" """) test.write(['work1', 'src', 'b1.f'], r""" PROGRAM FOO INCLUDE 'b1.for' STOP END """) test.write(['work1', 'src', 'b2.in'], r""" PROGRAM FOO INCLUDE 'b2.for' STOP END """) test.write(['work1', 'src', 'b1.for'], r""" PRINT *, 'b1.for' """) test.write(['work1', 'src', 'b2.for'], r""" PRINT *, 'b2.for' """) # Some releases of freeBSD seem to have library complaints about # tempnam(). Filter out these annoying messages before checking for # error output. def blank_output(err): if not err: return 1 stderrlines = filter(lambda l: l, string.split(err, '\n')) msg = "warning: tempnam() possibly used unsafely" stderrlines = filter(lambda l, msg=msg: string.find(l, msg) == -1, stderrlines) return len(stderrlines) == 0 test.run(chdir='work1', arguments = '. ../build', stderr=None) test.fail_test(not blank_output(test.stderr())) test.run(program = foo11, stdout = "f1.c\n") test.run(program = foo12, stdout = "f2.c\n") test.run(program = foo21, stdout = "f1.c\n") test.run(program = foo22, stdout = "f2.c\n") test.run(program = foo31, stdout = "f1.c\n") test.run(program = foo32, stdout = "f2.c\n") test.run(program = foo41, stdout = "f1.c\n") test.run(program = foo42, stdout = "f2.c\n") test.run(program = foo51, stdout = "f1.c\n") test.run(program = foo52, stdout = "f2.c\n") if fortran: test.run(program = bar11, stdout = " b1.for\n") test.run(program = bar12, stdout = " b2.for\n") test.run(program = bar21, stdout = " b1.for\n") test.run(program = bar22, stdout = " b2.for\n") test.run(program = bar31, stdout = " b1.for\n") test.run(program = bar32, stdout = " b2.for\n") test.run(program = bar41, stdout = " b1.for\n") test.run(program = bar42, stdout = " b2.for\n") test.run(program = bar51, stdout = " b1.for\n") test.run(program = bar52, stdout = " b2.for\n") test.run(chdir='work1', arguments='. ../build', stdout=test.wrap_stdout("""\ scons: `.' is up to date. scons: `%s' is up to date. """ % test.workpath('build'))) import os import stat def equal_stats(x,y): x = os.stat(x) y = os.stat(y) return (stat.S_IMODE(x[stat.ST_MODE]) == stat.S_IMODE(y[stat.ST_MODE]) and x[stat.ST_MTIME] == y[stat.ST_MTIME]) # Make sure we did duplicate the source files in build/var2, # and that their stats are the same: test.must_exist(['work1', 'build', 'var2', 'f1.c']) test.must_exist(['work1', 'build', 'var2', 'f2.in']) test.fail_test(not equal_stats(test.workpath('work1', 'build', 'var2', 'f1.c'), test.workpath('work1', 'src', 'f1.c'))) test.fail_test(not equal_stats(test.workpath('work1', 'build', 'var2', 'f2.in'), test.workpath('work1', 'src', 'f2.in'))) # Make sure we didn't duplicate the source files in build/var3. test.must_not_exist(['work1', 'build', 'var3', 'f1.c']) test.must_not_exist(['work1', 'build', 'var3', 'f2.in']) test.must_not_exist(['work1', 'build', 'var3', 'b1.f']) test.must_not_exist(['work1', 'build', 'var3', 'b2.in']) # Make sure we didn't duplicate the source files in build/var4. test.must_not_exist(['work1', 'build', 'var4', 'f1.c']) test.must_not_exist(['work1', 'build', 'var4', 'f2.in']) test.must_not_exist(['work1', 'build', 'var4', 'b1.f']) test.must_not_exist(['work1', 'build', 'var4', 'b2.in']) # Make sure we didn't duplicate the source files in build/var5. test.must_not_exist(['build', 'var5', 'f1.c']) test.must_not_exist(['build', 'var5', 'f2.in']) test.must_not_exist(['build', 'var5', 'b1.f']) test.must_not_exist(['build', 'var5', 'b2.in']) # verify that header files in the source directory are scanned properly: test.write(['work1', 'src', 'f1.h'], r""" #define F1_STR "f1.c 2\n" """) test.write(['work1', 'src', 'f3h.in'], r""" #define F3_STR "f3.c 2\n" """) test.write(['work1', 'src', 'f4h.in'], r""" #define F4_STR "f4.c 2\n" """) test.run(chdir='work1', arguments = '../build/var5', stderr=None) test.fail_test(not blank_output(test.stderr())) test.run(program = foo51, stdout = "f1.c 2\n") test.run(program = test.workpath('build', 'var5', 'foo3' + _exe), stdout = "f3.c 2\n") test.run(program = test.workpath('build', 'var5', 'foo4' + _exe), stdout = "f4.c 2\n") test.run(chdir='work1', arguments='../build/var5', stdout=test.wrap_stdout("""\ scons: `%s' is up to date. """ % test.workpath('build', 'var5'))) # test.write(['work2', 'SConstruct'], """\ env = Environment() env.Program('prog.c') """) test.write(['work2', 'prog.c'], r""" #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { argv[argc++] = "--"; printf("work2/prog.c\n"); exit (0); } """) test.run(chdir='work2', arguments='.') test.up_to_date(chdir='work2', arguments='.') # test.write(['work2', 'SConstruct'], """\ env = Environment() BuildDir('build', '.') Export('env') SConscript('build/SConscript') """) test.write(['work2', 'SConscript'], """\ Import('env') env.Program('prog.c') """) test.run(chdir='work2', arguments='.', stderr=None) test.fail_test(not blank_output(test.stderr())) test.run(chdir='work2', arguments='.', stdout=test.wrap_stdout("""\ scons: building associated BuildDir targets: build scons: `.' is up to date. """)) test.write( ['work3', 'SConstruct'], """\ SConscriptChdir(0) BuildDir('build', '.', duplicate=1 ) SConscript( 'build/SConscript' ) """) test.write( ['work3', 'SConscript'], """\ import sys headers = ['existing.h', 'non_existing.h'] for header in headers: h = File( header ) contents = h.get_contents() sys.stderr.write( '%s:%s\\n' % (header, contents)) """) test.write( ['work3', 'existing.h'], """\ /* a header file */\ """) test.run(chdir='work3', stdout=test.wrap_stdout("""\ scons: building associated BuildDir targets: build scons: `.' is up to date. """), stderr="""\ existing.h:/* a header file */ non_existing.h: """) test.pass_test()
"""The tests for Core components.""" # pylint: disable=protected-access import asyncio import unittest from unittest.mock import Mock, patch import yaml from homeassistant import config import homeassistant.components as comps from homeassistant.components.homeassistant import ( SERVICE_CHECK_CONFIG, SERVICE_RELOAD_CORE_CONFIG, ) from homeassistant.const import ( ATTR_ENTITY_ID, EVENT_CORE_CONFIG_UPDATE, SERVICE_HOMEASSISTANT_RESTART, SERVICE_HOMEASSISTANT_STOP, SERVICE_TOGGLE, SERVICE_TURN_OFF, SERVICE_TURN_ON, STATE_OFF, STATE_ON, ) import homeassistant.core as ha from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity import homeassistant.helpers.intent as intent from homeassistant.setup import async_setup_component from tests.common import ( async_capture_events, async_mock_service, get_test_home_assistant, mock_coro, mock_service, patch_yaml_files, ) def turn_on(hass, entity_id=None, **service_data): """Turn specified entity on if possible. This is a legacy helper method. Do not use it for new tests. """ if entity_id is not None: service_data[ATTR_ENTITY_ID] = entity_id hass.services.call(ha.DOMAIN, SERVICE_TURN_ON, service_data) def turn_off(hass, entity_id=None, **service_data): """Turn specified entity off. This is a legacy helper method. Do not use it for new tests. """ if entity_id is not None: service_data[ATTR_ENTITY_ID] = entity_id hass.services.call(ha.DOMAIN, SERVICE_TURN_OFF, service_data) def toggle(hass, entity_id=None, **service_data): """Toggle specified entity. This is a legacy helper method. Do not use it for new tests. """ if entity_id is not None: service_data[ATTR_ENTITY_ID] = entity_id hass.services.call(ha.DOMAIN, SERVICE_TOGGLE, service_data) def stop(hass): """Stop Home Assistant. This is a legacy helper method. Do not use it for new tests. """ hass.services.call(ha.DOMAIN, SERVICE_HOMEASSISTANT_STOP) def restart(hass): """Stop Home Assistant. This is a legacy helper method. Do not use it for new tests. """ hass.services.call(ha.DOMAIN, SERVICE_HOMEASSISTANT_RESTART) def check_config(hass): """Check the config files. This is a legacy helper method. Do not use it for new tests. """ hass.services.call(ha.DOMAIN, SERVICE_CHECK_CONFIG) def reload_core_config(hass): """Reload the core config. This is a legacy helper method. Do not use it for new tests. """ hass.services.call(ha.DOMAIN, SERVICE_RELOAD_CORE_CONFIG) class TestComponentsCore(unittest.TestCase): """Test homeassistant.components module.""" # pylint: disable=invalid-name def setUp(self): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() assert asyncio.run_coroutine_threadsafe( async_setup_component(self.hass, "homeassistant", {}), self.hass.loop ).result() self.hass.states.set("light.Bowl", STATE_ON) self.hass.states.set("light.Ceiling", STATE_OFF) # pylint: disable=invalid-name def tearDown(self): """Stop everything that was started.""" self.hass.stop() def test_is_on(self): """Test is_on method.""" assert comps.is_on(self.hass, "light.Bowl") assert not comps.is_on(self.hass, "light.Ceiling") assert comps.is_on(self.hass) assert not comps.is_on(self.hass, "non_existing.entity") def test_turn_on_without_entities(self): """Test turn_on method without entities.""" calls = mock_service(self.hass, "light", SERVICE_TURN_ON) turn_on(self.hass) self.hass.block_till_done() assert 0 == len(calls) def test_turn_on(self): """Test turn_on method.""" calls = mock_service(self.hass, "light", SERVICE_TURN_ON) turn_on(self.hass, "light.Ceiling") self.hass.block_till_done() assert 1 == len(calls) def test_turn_off(self): """Test turn_off method.""" calls = mock_service(self.hass, "light", SERVICE_TURN_OFF) turn_off(self.hass, "light.Bowl") self.hass.block_till_done() assert 1 == len(calls) def test_toggle(self): """Test toggle method.""" calls = mock_service(self.hass, "light", SERVICE_TOGGLE) toggle(self.hass, "light.Bowl") self.hass.block_till_done() assert 1 == len(calls) @patch("homeassistant.config.os.path.isfile", Mock(return_value=True)) def test_reload_core_conf(self): """Test reload core conf service.""" ent = entity.Entity() ent.entity_id = "test.entity" ent.hass = self.hass ent.schedule_update_ha_state() self.hass.block_till_done() state = self.hass.states.get("test.entity") assert state is not None assert state.state == "unknown" assert state.attributes == {} files = { config.YAML_CONFIG_FILE: yaml.dump( { ha.DOMAIN: { "latitude": 10, "longitude": 20, "customize": {"test.Entity": {"hello": "world"}}, } } ) } with patch_yaml_files(files, True): reload_core_config(self.hass) self.hass.block_till_done() assert self.hass.config.latitude == 10 assert self.hass.config.longitude == 20 ent.schedule_update_ha_state() self.hass.block_till_done() state = self.hass.states.get("test.entity") assert state is not None assert state.state == "unknown" assert state.attributes.get("hello") == "world" @patch("homeassistant.config.os.path.isfile", Mock(return_value=True)) @patch("homeassistant.components.homeassistant._LOGGER.error") @patch("homeassistant.config.async_process_ha_core_config") def test_reload_core_with_wrong_conf(self, mock_process, mock_error): """Test reload core conf service.""" files = {config.YAML_CONFIG_FILE: yaml.dump(["invalid", "config"])} with patch_yaml_files(files, True): reload_core_config(self.hass) self.hass.block_till_done() assert mock_error.called assert mock_process.called is False @patch("homeassistant.core.HomeAssistant.async_stop", return_value=mock_coro()) def test_stop_homeassistant(self, mock_stop): """Test stop service.""" stop(self.hass) self.hass.block_till_done() assert mock_stop.called @patch("homeassistant.core.HomeAssistant.async_stop", return_value=mock_coro()) @patch("homeassistant.config.async_check_ha_config_file", return_value=mock_coro()) def test_restart_homeassistant(self, mock_check, mock_restart): """Test stop service.""" restart(self.hass) self.hass.block_till_done() assert mock_restart.called assert mock_check.called @patch("homeassistant.core.HomeAssistant.async_stop", return_value=mock_coro()) @patch( "homeassistant.config.async_check_ha_config_file", side_effect=HomeAssistantError("Test error"), ) def test_restart_homeassistant_wrong_conf(self, mock_check, mock_restart): """Test stop service.""" restart(self.hass) self.hass.block_till_done() assert mock_check.called assert not mock_restart.called @patch("homeassistant.core.HomeAssistant.async_stop", return_value=mock_coro()) @patch("homeassistant.config.async_check_ha_config_file", return_value=mock_coro()) def test_check_config(self, mock_check, mock_stop): """Test stop service.""" check_config(self.hass) self.hass.block_till_done() assert mock_check.called assert not mock_stop.called async def test_turn_on_intent(hass): """Test HassTurnOn intent.""" result = await async_setup_component(hass, "homeassistant", {}) assert result hass.states.async_set("light.test_light", "off") calls = async_mock_service(hass, "light", SERVICE_TURN_ON) response = await intent.async_handle( hass, "test", "HassTurnOn", {"name": {"value": "test light"}} ) await hass.async_block_till_done() assert response.speech["plain"]["speech"] == "Turned test light on" assert len(calls) == 1 call = calls[0] assert call.domain == "light" assert call.service == "turn_on" assert call.data == {"entity_id": ["light.test_light"]} async def test_turn_off_intent(hass): """Test HassTurnOff intent.""" result = await async_setup_component(hass, "homeassistant", {}) assert result hass.states.async_set("light.test_light", "on") calls = async_mock_service(hass, "light", SERVICE_TURN_OFF) response = await intent.async_handle( hass, "test", "HassTurnOff", {"name": {"value": "test light"}} ) await hass.async_block_till_done() assert response.speech["plain"]["speech"] == "Turned test light off" assert len(calls) == 1 call = calls[0] assert call.domain == "light" assert call.service == "turn_off" assert call.data == {"entity_id": ["light.test_light"]} async def test_toggle_intent(hass): """Test HassToggle intent.""" result = await async_setup_component(hass, "homeassistant", {}) assert result hass.states.async_set("light.test_light", "off") calls = async_mock_service(hass, "light", SERVICE_TOGGLE) response = await intent.async_handle( hass, "test", "HassToggle", {"name": {"value": "test light"}} ) await hass.async_block_till_done() assert response.speech["plain"]["speech"] == "Toggled test light" assert len(calls) == 1 call = calls[0] assert call.domain == "light" assert call.service == "toggle" assert call.data == {"entity_id": ["light.test_light"]} async def test_turn_on_multiple_intent(hass): """Test HassTurnOn intent with multiple similar entities. This tests that matching finds the proper entity among similar names. """ result = await async_setup_component(hass, "homeassistant", {}) assert result hass.states.async_set("light.test_light", "off") hass.states.async_set("light.test_lights_2", "off") hass.states.async_set("light.test_lighter", "off") calls = async_mock_service(hass, "light", SERVICE_TURN_ON) response = await intent.async_handle( hass, "test", "HassTurnOn", {"name": {"value": "test lights"}} ) await hass.async_block_till_done() assert response.speech["plain"]["speech"] == "Turned test lights 2 on" assert len(calls) == 1 call = calls[0] assert call.domain == "light" assert call.service == "turn_on" assert call.data == {"entity_id": ["light.test_lights_2"]} async def test_turn_on_to_not_block_for_domains_without_service(hass): """Test if turn_on is blocking domain with no service.""" await async_setup_component(hass, "homeassistant", {}) async_mock_service(hass, "light", SERVICE_TURN_ON) hass.states.async_set("light.Bowl", STATE_ON) hass.states.async_set("light.Ceiling", STATE_OFF) # We can't test if our service call results in services being called # because by mocking out the call service method, we mock out all # So we mimic how the service registry calls services service_call = ha.ServiceCall( "homeassistant", "turn_on", {"entity_id": ["light.test", "sensor.bla", "light.bla"]}, ) service = hass.services._services["homeassistant"]["turn_on"] with patch( "homeassistant.core.ServiceRegistry.async_call", side_effect=lambda *args: mock_coro(), ) as mock_call: await service.func(service_call) assert mock_call.call_count == 2 assert mock_call.call_args_list[0][0] == ( "light", "turn_on", {"entity_id": ["light.bla", "light.test"]}, True, ) assert mock_call.call_args_list[1][0] == ( "sensor", "turn_on", {"entity_id": ["sensor.bla"]}, False, ) async def test_entity_update(hass): """Test being able to call entity update.""" await async_setup_component(hass, "homeassistant", {}) with patch( "homeassistant.helpers.entity_component.async_update_entity", return_value=mock_coro(), ) as mock_update: await hass.services.async_call( "homeassistant", "update_entity", {"entity_id": ["light.kitchen"]}, blocking=True, ) assert len(mock_update.mock_calls) == 1 assert mock_update.mock_calls[0][1][1] == "light.kitchen" async def test_setting_location(hass): """Test setting the location.""" await async_setup_component(hass, "homeassistant", {}) events = async_capture_events(hass, EVENT_CORE_CONFIG_UPDATE) # Just to make sure that we are updating values. assert hass.config.latitude != 30 assert hass.config.longitude != 40 await hass.services.async_call( "homeassistant", "set_location", {"latitude": 30, "longitude": 40}, blocking=True, ) assert len(events) == 1 assert hass.config.latitude == 30 assert hass.config.longitude == 40
# 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 threading import Thread import multiprocessing import psutil from abstracthealthstatisticspublisher import * from ..databridge.agent import * from config import CartridgeAgentConfiguration from ..util import cartridgeagentutils from exception import ThriftReceiverOfflineException import constants class HealthStatisticsPublisherManager(Thread): """ Read from an implementation of AbstractHealthStatisticsPublisher the value for memory usage and load average and publishes them as ThriftEvents to a CEP server """ STREAM_NAME = "cartridge_agent_health_stats" STREAM_VERSION = "1.0.0" STREAM_NICKNAME = "agent health stats" STREAM_DESCRIPTION = "agent health stats" def __init__(self, publish_interval): """ Initializes a new HealthStatistsPublisherManager with a given number of seconds as the interval :param int publish_interval: Number of seconds as the interval :return: void """ Thread.__init__(self) self.log = LogFactory().get_log(__name__) self.publish_interval = publish_interval """:type : int""" self.terminated = False self.publisher = HealthStatisticsPublisher() """:type : HealthStatisticsPublisher""" # TODO: load plugins for the reader self.stats_reader = DefaultHealthStatisticsReader() """:type : AbstractHealthStatisticsReader""" def run(self): while not self.terminated: time.sleep(self.publish_interval) try: cartridge_stats = self.stats_reader.stat_cartridge_health() self.log.debug("Publishing memory consumption: %r" % cartridge_stats.memory_usage) self.publisher.publish_memory_usage(cartridge_stats.memory_usage) self.log.debug("Publishing load average: %r" % cartridge_stats.load_avg) self.publisher.publish_load_average(cartridge_stats.load_avg) except ThriftReceiverOfflineException: self.log.error("Couldn't publish health statistics to CEP. Thrift Receiver offline. Reconnecting...") try: self.publisher = HealthStatisticsPublisher() except: self.log.error("Couldn't connect. CEP Offline.") self.publisher.publisher.disconnect() class HealthStatisticsPublisher: """ Publishes memory usage and load average to thrift server """ log = LogFactory().get_log(__name__) def __init__(self): self.ports = [] self.ports.append(CEPPublisherConfiguration.get_instance().server_port) self.cartridge_agent_config = CartridgeAgentConfiguration() cartridgeagentutils.wait_until_ports_active( CEPPublisherConfiguration.get_instance().server_ip, self.ports, int(self.cartridge_agent_config.read_property("port.check.timeout", critical=False))) cep_active = cartridgeagentutils.check_ports_active(CEPPublisherConfiguration.get_instance().server_ip, self.ports) if not cep_active: raise CEPPublisherException("CEP server not active. Health statistics publishing aborted.") self.stream_definition = HealthStatisticsPublisher.create_stream_definition() HealthStatisticsPublisher.log.debug("Stream definition created: %r" % str(self.stream_definition)) self.publisher = ThriftPublisher( CEPPublisherConfiguration.get_instance().server_ip, CEPPublisherConfiguration.get_instance().server_port, CEPPublisherConfiguration.get_instance().admin_username, CEPPublisherConfiguration.get_instance().admin_password, self.stream_definition) HealthStatisticsPublisher.log.debug("HealthStatisticsPublisher initialized") @staticmethod def create_stream_definition(): """ Create a StreamDefinition for publishing to CEP """ stream_def = StreamDefinition() stream_def.name = HealthStatisticsPublisherManager.STREAM_NAME stream_def.version = HealthStatisticsPublisherManager.STREAM_VERSION stream_def.nickname = HealthStatisticsPublisherManager.STREAM_NICKNAME stream_def.description = HealthStatisticsPublisherManager.STREAM_DESCRIPTION stream_def.add_payloaddata_attribute("cluster_id", StreamDefinition.STRING) stream_def.add_payloaddata_attribute("cluster_instance_id", StreamDefinition.STRING) stream_def.add_payloaddata_attribute("network_partition_id", StreamDefinition.STRING) stream_def.add_payloaddata_attribute("member_id", StreamDefinition.STRING) stream_def.add_payloaddata_attribute("partition_id", StreamDefinition.STRING) stream_def.add_payloaddata_attribute("health_description", StreamDefinition.STRING) stream_def.add_payloaddata_attribute("value", StreamDefinition.DOUBLE) return stream_def def publish_memory_usage(self, memory_usage): """ Publishes the given memory usage value to the thrift server as a ThriftEvent :param float memory_usage: memory usage """ event = ThriftEvent() event.payloadData.append(self.cartridge_agent_config.cluster_id) event.payloadData.append(self.cartridge_agent_config.cluster_instance_id) event.payloadData.append(self.cartridge_agent_config.network_partition_id) event.payloadData.append(self.cartridge_agent_config.member_id) event.payloadData.append(self.cartridge_agent_config.partition_id) event.payloadData.append(constants.MEMORY_CONSUMPTION) event.payloadData.append(memory_usage) HealthStatisticsPublisher.log.debug("Publishing cep event: [stream] %r [payload_data} %r [version] %r" % (self.stream_definition.name,event.payloadData, self.stream_definition.version)) self.publisher.publish(event) def publish_load_average(self, load_avg): """ Publishes the given load average value to the thrift server as a ThriftEvent :param float load_avg: load average value """ event = ThriftEvent() event.payloadData.append(self.cartridge_agent_config.cluster_id) event.payloadData.append(self.cartridge_agent_config.cluster_instance_id) event.payloadData.append(self.cartridge_agent_config.network_partition_id) event.payloadData.append(self.cartridge_agent_config.member_id) event.payloadData.append(self.cartridge_agent_config.partition_id) event.payloadData.append(constants.LOAD_AVERAGE) event.payloadData.append(load_avg) HealthStatisticsPublisher.log.debug("Publishing cep event: [stream] %r [version] %r" % (self.stream_definition.name, self.stream_definition.version)) self.publisher.publish(event) class DefaultHealthStatisticsReader(AbstractHealthStatisticsReader): """ Default implementation of the AbstractHealthStatisticsReader """ def __init__(self): self.log = LogFactory().get_log(__name__) def stat_cartridge_health(self): cartridge_stats = CartridgeHealthStatistics() cartridge_stats.memory_usage = DefaultHealthStatisticsReader.__read_mem_usage() cartridge_stats.load_avg = DefaultHealthStatisticsReader.__read_load_avg() self.log.debug("Memory read: %r, CPU read: %r" % (cartridge_stats.memory_usage, cartridge_stats.load_avg)) return cartridge_stats @staticmethod def __read_mem_usage(): return psutil.virtual_memory().percent @staticmethod def __read_load_avg(): (one, five, fifteen) = os.getloadavg() cores = multiprocessing.cpu_count() return (one/cores) * 100 class CEPPublisherConfiguration: """ TODO: Extract common functionality """ __instance = None log = LogFactory().get_log(__name__) @staticmethod def get_instance(): """ Singleton instance retriever :return: Instance :rtype : CEPPublisherConfiguration """ if CEPPublisherConfiguration.__instance is None: CEPPublisherConfiguration.__instance = CEPPublisherConfiguration() return CEPPublisherConfiguration.__instance def __init__(self): self.enabled = False self.server_ip = None self.server_port = None self.admin_username = None self.admin_password = None self.cartridge_agent_config = CartridgeAgentConfiguration() self.read_config() def read_config(self): self.enabled = True if self.cartridge_agent_config.read_property( constants.CEP_PUBLISHER_ENABLED, False).strip().lower() == "true" else False if not self.enabled: CEPPublisherConfiguration.log.info("CEP Publisher disabled") return CEPPublisherConfiguration.log.info("CEP Publisher enabled") self.server_ip = self.cartridge_agent_config.read_property( constants.CEP_RECEIVER_IP, False) if self.server_ip is None or self.server_ip.strip() == "": raise RuntimeError("System property not found: " + constants.CEP_RECEIVER_IP) self.server_port = self.cartridge_agent_config.read_property( constants.CEP_RECEIVER_PORT, False) if self.server_port is None or self.server_port.strip() == "": raise RuntimeError("System property not found: " + constants.CEP_RECEIVER_PORT) self.admin_username = self.cartridge_agent_config.read_property( constants.CEP_SERVER_ADMIN_USERNAME, False) if self.admin_username is None or self.admin_username.strip() == "": raise RuntimeError("System property not found: " + constants.CEP_SERVER_ADMIN_USERNAME) self.admin_password = self.cartridge_agent_config.read_property( constants.CEP_SERVER_ADMIN_PASSWORD, False) if self.admin_password is None or self.admin_password.strip() == "": raise RuntimeError("System property not found: " + constants.CEP_SERVER_ADMIN_PASSWORD) CEPPublisherConfiguration.log.info("CEP Publisher configuration initialized")
# 30.05.2007, c # last revision: 25.02.2008 from __future__ import absolute_import from sfepy import data_dir import six filename_mesh = data_dir + '/meshes/2d/square_unit_tri.mesh' material_1 = { 'name' : 'coef', 'values' : { 'val' : 1.0, }, } material_2 = { 'name' : 'm', 'values' : { 'K' : [[1.0, 0.0], [0.0, 1.0]], }, } field_1 = { 'name' : 'a_harmonic_field', 'dtype' : 'real', 'shape' : 'scalar', 'region' : 'Omega', 'approx_order' : 2, } variable_1 = { 'name' : 't', 'kind' : 'unknown field', 'field' : 'a_harmonic_field', 'order' : 0, } variable_2 = { 'name' : 's', 'kind' : 'test field', 'field' : 'a_harmonic_field', 'dual' : 't', } region_1000 = { 'name' : 'Omega', 'select' : 'all', } region_1 = { 'name' : 'Left', 'select' : 'vertices in (x < -0.499)', 'kind' : 'facet', } region_2 = { 'name' : 'Right', 'select' : 'vertices in (x > 0.499)', 'kind' : 'facet', } region_3 = { 'name' : 'Gamma', 'select' : 'vertices of surface', 'kind' : 'facet', } ebc_1 = { 'name' : 't_left', 'region' : 'Left', 'dofs' : {'t.0' : 5.0}, } ebc_2 = { 'name' : 't_right', 'region' : 'Right', 'dofs' : {'t.0' : 0.0}, } # 'Left' : ('T3', (30,), 'linear_y'), integral_1 = { 'name' : 'i', 'order' : 2, } equations = { 'Temperature' : """dw_laplace.i.Omega( coef.val, s, t ) = 0""" } solution = { 't' : '- 5.0 * (x - 0.5)', } solver_0 = { 'name' : 'ls', 'kind' : 'ls.scipy_direct', } solver_1 = { 'name' : 'newton', 'kind' : 'nls.newton', 'i_max' : 1, 'eps_a' : 1e-10, } lin_min, lin_max = 0.0, 2.0 ## # 31.05.2007, c def linear( bc, ts, coor, which ): vals = coor[:,which] min_val, max_val = vals.min(), vals.max() vals = (vals - min_val) / (max_val - min_val) * (lin_max - lin_min) + lin_min return vals ## # 31.05.2007, c def linear_x( bc, ts, coor ): return linear( bc, ts, coor, 0 ) def linear_y( bc, ts, coor ): return linear( bc, ts, coor, 1 ) def linear_z( bc, ts, coor ): return linear( bc, ts, coor, 2 ) from sfepy.base.testing import TestCommon ## # 30.05.2007, c class Test( TestCommon ): ## # 30.05.2007, c def from_conf( conf, options ): from sfepy.applications import solve_pde problem, state = solve_pde(conf, save_results=False) test = Test(problem=problem, state=state, conf=conf, options=options) return test from_conf = staticmethod( from_conf ) ## # 30.05.2007, c def test_solution( self ): sol = self.conf.solution vec = self.state() problem = self.problem variables = problem.get_variables() ok = True for var_name, expression in six.iteritems(sol): coor = variables[var_name].field.get_coor() ana_sol = self.eval_coor_expression( expression, coor ) num_sol = variables.get_state_part_view( vec, var_name ) ret = self.compare_vectors( ana_sol, num_sol, label1 = 'analytical %s' % var_name, label2 = 'numerical %s' % var_name ) if not ret: self.report( 'variable %s: failed' % var_name ) ok = ok and ret return ok ## # c: 30.05.2007, r: 19.02.2008 def test_boundary_fluxes( self ): import os.path as op from sfepy.linalg import rotation_matrix2d from sfepy.discrete import Material problem = self.problem angles = [0, 30, 45] region_names = ['Left', 'Right', 'Gamma'] values = [5.0, -5.0, 0.0] variables = problem.get_variables() get_state = variables.get_state_part_view state = self.state.copy(deep=True) problem.time_update(ebcs={}, epbcs={}) # problem.save_ebc( 'aux.vtk' ) state.apply_ebc() nls = problem.get_nls() aux = nls.fun(state()) field = variables['t'].field conf_m = problem.conf.get_item_by_name('materials', 'm') m = Material.from_conf(conf_m, problem.functions) name = op.join( self.options.out_dir, op.split( problem.domain.mesh.name )[1] + '_%02d.mesh' ) orig_coors = problem.get_mesh_coors().copy() ok = True for ia, angle in enumerate( angles ): self.report( '%d: mesh rotation %d degrees' % (ia, angle) ) problem.domain.mesh.transform_coors( rotation_matrix2d( angle ), ref_coors = orig_coors ) problem.set_mesh_coors(problem.domain.mesh.coors, update_fields=True) problem.domain.mesh.write( name % angle, io = 'auto' ) for ii, region_name in enumerate( region_names ): flux_term = 'd_surface_flux.i.%s( m.K, t )' % region_name val1 = problem.evaluate(flux_term, t=variables['t'], m=m) rvec = get_state( aux, 't', True ) reg = problem.domain.regions[region_name] nods = field.get_dofs_in_region(reg, merge=True) val2 = rvec[nods].sum() # Assume 1 dof per node. ok = ok and ((abs( val1 - values[ii] ) < 1e-10) and (abs( val2 - values[ii] ) < 1e-10)) self.report( ' %d. %s: %e == %e == %e'\ % (ii, region_name, val1, val2, values[ii]) ) # Restore original coordinates. problem.domain.mesh.transform_coors(rotation_matrix2d(0), ref_coors=orig_coors) problem.set_mesh_coors(problem.domain.mesh.coors, update_fields=True) return ok
# SOAPpy modules from Config import Config from Types import * from NS import NS from Utilities import * import string import fpconst import xml.sax from wstools.XMLname import fromXMLname try: from M2Crypto import SSL except: pass ident = '$Id: Parser.py 1497 2010-03-08 06:06:52Z pooryorick $' from version import __version__ ################################################################################ # SOAP Parser ################################################################################ class RefHolder: def __init__(self, name, frame): self.name = name self.parent = frame self.pos = len(frame) self.subpos = frame.namecounts.get(name, 0) def __repr__(self): return "<%s %s at %d>" % (self.__class__, self.name, id(self)) def __str__(self): return "<%s %s at %d>" % (self.__class__, self.name, id(self)) class SOAPParser(xml.sax.handler.ContentHandler): class Frame: def __init__(self, name, kind = None, attrs = {}, rules = {}): self.name = name self.kind = kind self.attrs = attrs self.rules = rules self.contents = [] self.names = [] self.namecounts = {} self.subattrs = [] def append(self, name, data, attrs): self.names.append(name) self.contents.append(data) self.subattrs.append(attrs) if self.namecounts.has_key(name): self.namecounts[name] += 1 else: self.namecounts[name] = 1 def _placeItem(self, name, value, pos, subpos = 0, attrs = None): self.contents[pos] = value if attrs: self.attrs.update(attrs) def __len__(self): return len(self.contents) def __repr__(self): return "<%s %s at %d>" % (self.__class__, self.name, id(self)) def __init__(self, rules = None): xml.sax.handler.ContentHandler.__init__(self) self.body = None self.header = None self.attrs = {} self._data = None self._next = "E" # Keeping state for message validity self._stack = [self.Frame('SOAP')] # Make two dictionaries to store the prefix <-> URI mappings, and # initialize them with the default self._prem = {NS.XML_T: NS.XML} self._prem_r = {NS.XML: NS.XML_T} self._ids = {} self._refs = {} self._rules = rules def startElementNS(self, name, qname, attrs): def toStr( name ): prefix = name[0] tag = name[1] if self._prem_r.has_key(prefix): tag = self._prem_r[name[0]] + ':' + name[1] elif prefix: tag = prefix + ":" + tag return tag # Workaround two sax bugs if name[0] == None and name[1][0] == ' ': name = (None, name[1][1:]) else: name = tuple(name) # First some checking of the layout of the message if self._next == "E": if name[1] != 'Envelope': raise Error, "expected `SOAP-ENV:Envelope', " \ "got `%s'" % toStr( name ) if name[0] != NS.ENV: raise faultType, ("%s:VersionMismatch" % NS.ENV_T, "Don't understand version `%s' Envelope" % name[0]) else: self._next = "HorB" elif self._next == "HorB": if name[0] == NS.ENV and name[1] in ("Header", "Body"): self._next = None else: raise Error, \ "expected `SOAP-ENV:Header' or `SOAP-ENV:Body', " \ "got `%s'" % toStr( name ) elif self._next == "B": if name == (NS.ENV, "Body"): self._next = None else: raise Error, "expected `SOAP-ENV:Body', " \ "got `%s'" % toStr( name ) elif self._next == "": raise Error, "expected nothing, " \ "got `%s'" % toStr( name ) if len(self._stack) == 2: rules = self._rules else: try: rules = self._stack[-1].rules[name[1]] except: rules = None if type(rules) not in (NoneType, DictType): kind = rules else: kind = attrs.get((NS.ENC, 'arrayType')) if kind != None: del attrs._attrs[(NS.ENC, 'arrayType')] i = kind.find(':') if i >= 0: try: kind = (self._prem[kind[:i]], kind[i + 1:]) except: kind = None else: kind = None self.pushFrame(self.Frame(name[1], kind, attrs._attrs, rules)) self._data = [] # Start accumulating def pushFrame(self, frame): self._stack.append(frame) def popFrame(self): return self._stack.pop() def endElementNS(self, name, qname): # Workaround two sax bugs if name[0] == None and name[1][0] == ' ': ns, name = None, name[1][1:] else: ns, name = tuple(name) name = fromXMLname(name) # convert to SOAP 1.2 XML name encoding if self._next == "E": raise Error, "didn't get SOAP-ENV:Envelope" if self._next in ("HorB", "B"): raise Error, "didn't get SOAP-ENV:Body" cur = self.popFrame() attrs = cur.attrs idval = None if attrs.has_key((None, 'id')): idval = attrs[(None, 'id')] if self._ids.has_key(idval): raise Error, "duplicate id `%s'" % idval del attrs[(None, 'id')] root = 1 if len(self._stack) == 3: if attrs.has_key((NS.ENC, 'root')): root = int(attrs[(NS.ENC, 'root')]) # Do some preliminary checks. First, if root="0" is present, # the element must have an id. Next, if root="n" is present, # n something other than 0 or 1, raise an exception. if root == 0: if idval == None: raise Error, "non-root element must have an id" elif root != 1: raise Error, "SOAP-ENC:root must be `0' or `1'" del attrs[(NS.ENC, 'root')] while 1: href = attrs.get((None, 'href')) if href: if href[0] != '#': raise Error, "Non-local hrefs are not yet suppported." if self._data != None and \ string.join(self._data, "").strip() != '': raise Error, "hrefs can't have data" href = href[1:] if self._ids.has_key(href): data = self._ids[href] else: data = RefHolder(name, self._stack[-1]) if self._refs.has_key(href): self._refs[href].append(data) else: self._refs[href] = [data] del attrs[(None, 'href')] break kind = None if attrs: for i in NS.XSI_L: if attrs.has_key((i, 'type')): kind = attrs[(i, 'type')] del attrs[(i, 'type')] if kind != None: i = kind.find(':') if i >= 0: try: kind = (self._prem[kind[:i]], kind[i + 1:]) except: kind = (None, kind) else: # XXX What to do here? (None, kind) is just going to fail in convertType #print "Kind with no NS:", kind kind = (None, kind) null = 0 if attrs: for i in (NS.XSI, NS.XSI2): if attrs.has_key((i, 'null')): null = attrs[(i, 'null')] del attrs[(i, 'null')] if attrs.has_key((NS.XSI3, 'nil')): null = attrs[(NS.XSI3, 'nil')] del attrs[(NS.XSI3, 'nil')] ## Check for nil # check for nil='true' if type(null) in (StringType, UnicodeType): if null.lower() == 'true': null = 1 # check for nil=1, but watch out for string values try: null = int(null) except ValueError, e: if not e[0].startswith("invalid literal for int()"): raise e null = 0 if null: if len(cur) or \ (self._data != None and string.join(self._data, "").strip() != ''): raise Error, "nils can't have data" data = None break if len(self._stack) == 2: if (ns, name) == (NS.ENV, "Header"): self.header = data = headerType(attrs = attrs) self._next = "B" break elif (ns, name) == (NS.ENV, "Body"): self.body = data = bodyType(attrs = attrs) self._next = "" break elif len(self._stack) == 3 and self._next == None: if (ns, name) == (NS.ENV, "Fault"): data = faultType() self._next = None # allow followons break #print "\n" #print "data=", self._data #print "kind=", kind #print "cur.kind=", cur.kind #print "cur.rules=", cur.rules #print "\n" if cur.rules != None: rule = cur.rules if type(rule) in (StringType, UnicodeType): rule = (None, rule) # none flags special handling elif type(rule) == ListType: rule = tuple(rule) #print "kind=",kind #print "rule=",rule # XXX What if rule != kind? if callable(rule): data = rule(string.join(self._data, "")) elif type(rule) == DictType: data = structType(name = (ns, name), attrs = attrs) elif rule[1][:9] == 'arrayType': data = self.convertType(cur.contents, rule, attrs) else: data = self.convertType(string.join(self._data, ""), rule, attrs) break #print "No rules, using kind or cur.kind..." if (kind == None and cur.kind != None) or \ (kind == (NS.ENC, 'Array')): kind = cur.kind if kind == None: kind = 'ur-type[%d]' % len(cur) else: kind = kind[1] if len(cur.namecounts) == 1: elemsname = cur.names[0] else: elemsname = None data = self.startArray((ns, name), kind, attrs, elemsname) break if len(self._stack) == 3 and kind == None and \ len(cur) == 0 and \ (self._data == None or string.join(self._data, "").strip() == ''): data = structType(name = (ns, name), attrs = attrs) break if len(cur) == 0 and ns != NS.URN: # Nothing's been added to the current frame so it must be a # simple type. # print "cur:", cur # print "ns:", ns # print "attrs:", attrs # print "kind:", kind if kind == None: # If the current item's container is an array, it will # have a kind. If so, get the bit before the first [, # which is the type of the array, therefore the type of # the current item. kind = self._stack[-1].kind if kind != None: i = kind[1].find('[') if i >= 0: kind = (kind[0], kind[1][:i]) elif ns != None: kind = (ns, name) if kind != None: try: data = self.convertType(string.join(self._data, ""), kind, attrs) except UnknownTypeError: data = None else: data = None if data == None: if self._data == None: data = '' else: data = string.join(self._data, "") if len(attrs) == 0: try: data = str(data) except: pass break data = structType(name = (ns, name), attrs = attrs) break if isinstance(data, compoundType): for i in range(len(cur)): v = cur.contents[i] data._addItem(cur.names[i], v, cur.subattrs[i]) if isinstance(v, RefHolder): v.parent = data if root: self._stack[-1].append(name, data, attrs) if idval != None: self._ids[idval] = data if self._refs.has_key(idval): for i in self._refs[idval]: i.parent._placeItem(i.name, data, i.pos, i.subpos, attrs) del self._refs[idval] self.attrs[id(data)] = attrs if isinstance(data, anyType): data._setAttrs(attrs) self._data = None # Stop accumulating def endDocument(self): if len(self._refs) == 1: raise Error, \ "unresolved reference " + self._refs.keys()[0] elif len(self._refs) > 1: raise Error, \ "unresolved references " + ', '.join(self._refs.keys()) def startPrefixMapping(self, prefix, uri): self._prem[prefix] = uri self._prem_r[uri] = prefix def endPrefixMapping(self, prefix): try: del self._prem_r[self._prem[prefix]] del self._prem[prefix] except: pass def characters(self, c): if self._data != None: self._data.append(c) arrayre = '^(?:(?P<ns>[^:]*):)?' \ '(?P<type>[^[]+)' \ '(?:\[(?P<rank>,*)\])?' \ '(?:\[(?P<asize>\d+(?:,\d+)*)?\])$' def startArray(self, name, kind, attrs, elemsname): if type(self.arrayre) == StringType: self.arrayre = re.compile (self.arrayre) offset = attrs.get((NS.ENC, "offset")) if offset != None: del attrs[(NS.ENC, "offset")] try: if offset[0] == '[' and offset[-1] == ']': offset = int(offset[1:-1]) if offset < 0: raise Exception else: raise Exception except: raise AttributeError, "invalid Array offset" else: offset = 0 try: m = self.arrayre.search(kind) if m == None: raise Exception t = m.group('type') if t == 'ur-type': return arrayType(None, name, attrs, offset, m.group('rank'), m.group('asize'), elemsname) elif m.group('ns') != None: return typedArrayType(None, name, (self._prem[m.group('ns')], t), attrs, offset, m.group('rank'), m.group('asize'), elemsname) else: return typedArrayType(None, name, (None, t), attrs, offset, m.group('rank'), m.group('asize'), elemsname) except: raise AttributeError, "invalid Array type `%s'" % kind # Conversion class DATETIMECONSTS: SIGNre = '(?P<sign>-?)' CENTURYre = '(?P<century>\d{2,})' YEARre = '(?P<year>\d{2})' MONTHre = '(?P<month>\d{2})' DAYre = '(?P<day>\d{2})' HOURre = '(?P<hour>\d{2})' MINUTEre = '(?P<minute>\d{2})' SECONDre = '(?P<second>\d{2}(?:\.\d*)?)' TIMEZONEre = '(?P<zulu>Z)|(?P<tzsign>[-+])(?P<tzhour>\d{2}):' \ '(?P<tzminute>\d{2})' BOSre = '^\s*' EOSre = '\s*$' __allres = {'sign': SIGNre, 'century': CENTURYre, 'year': YEARre, 'month': MONTHre, 'day': DAYre, 'hour': HOURre, 'minute': MINUTEre, 'second': SECONDre, 'timezone': TIMEZONEre, 'b': BOSre, 'e': EOSre} dateTime = '%(b)s%(sign)s%(century)s%(year)s-%(month)s-%(day)sT' \ '%(hour)s:%(minute)s:%(second)s(%(timezone)s)?%(e)s' % __allres timeInstant = dateTime timePeriod = dateTime time = '%(b)s%(hour)s:%(minute)s:%(second)s(%(timezone)s)?%(e)s' % \ __allres date = '%(b)s%(sign)s%(century)s%(year)s-%(month)s-%(day)s' \ '(%(timezone)s)?%(e)s' % __allres century = '%(b)s%(sign)s%(century)s(%(timezone)s)?%(e)s' % __allres gYearMonth = '%(b)s%(sign)s%(century)s%(year)s-%(month)s' \ '(%(timezone)s)?%(e)s' % __allres gYear = '%(b)s%(sign)s%(century)s%(year)s(%(timezone)s)?%(e)s' % \ __allres year = gYear gMonthDay = '%(b)s--%(month)s-%(day)s(%(timezone)s)?%(e)s' % __allres recurringDate = gMonthDay gDay = '%(b)s---%(day)s(%(timezone)s)?%(e)s' % __allres recurringDay = gDay gMonth = '%(b)s--%(month)s--(%(timezone)s)?%(e)s' % __allres month = gMonth recurringInstant = '%(b)s%(sign)s(%(century)s|-)(%(year)s|-)-' \ '(%(month)s|-)-(%(day)s|-)T' \ '(%(hour)s|-):(%(minute)s|-):(%(second)s|-)' \ '(%(timezone)s)?%(e)s' % __allres duration = '%(b)s%(sign)sP' \ '((?P<year>\d+)Y)?' \ '((?P<month>\d+)M)?' \ '((?P<day>\d+)D)?' \ '((?P<sep>T)' \ '((?P<hour>\d+)H)?' \ '((?P<minute>\d+)M)?' \ '((?P<second>\d*(?:\.\d*)?)S)?)?%(e)s' % \ __allres timeDuration = duration # The extra 31 on the front is: # - so the tuple is 1-based # - so months[month-1] is December's days if month is 1 months = (31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) def convertDateTime(self, value, kind): def getZoneOffset(d): zoffs = 0 try: if d['zulu'] == None: zoffs = 60 * int(d['tzhour']) + int(d['tzminute']) if d['tzsign'] != '-': zoffs = -zoffs except TypeError: pass return zoffs def applyZoneOffset(months, zoffs, date, minfield, posday = 1): if zoffs == 0 and (minfield > 4 or 0 <= date[5] < 60): return date if minfield > 5: date[5] = 0 if minfield > 4: date[4] = 0 if date[5] < 0: date[4] += int(date[5]) / 60 date[5] %= 60 date[4] += zoffs if minfield > 3 or 0 <= date[4] < 60: return date date[3] += date[4] / 60 date[4] %= 60 if minfield > 2 or 0 <= date[3] < 24: return date date[2] += date[3] / 24 date[3] %= 24 if minfield > 1: if posday and date[2] <= 0: date[2] += 31 # zoffs is at most 99:59, so the # day will never be less than -3 return date while 1: # The date[1] == 3 (instead of == 2) is because we're # going back a month, so we need to know if the previous # month is February, so we test if this month is March. leap = minfield == 0 and date[1] == 3 and \ date[0] % 4 == 0 and \ (date[0] % 100 != 0 or date[0] % 400 == 0) if 0 < date[2] <= months[date[1]] + leap: break date[2] += months[date[1] - 1] + leap date[1] -= 1 if date[1] > 0: break date[1] = 12 if minfield > 0: break date[0] -= 1 return date try: exp = getattr(self.DATETIMECONSTS, kind) except AttributeError: return None if type(exp) == StringType: exp = re.compile(exp) setattr (self.DATETIMECONSTS, kind, exp) m = exp.search(value) try: if m == None: raise Exception d = m.groupdict() f = ('century', 'year', 'month', 'day', 'hour', 'minute', 'second') fn = len(f) # Index of first non-None value r = [] if kind in ('duration', 'timeDuration'): if d['sep'] != None and d['hour'] == None and \ d['minute'] == None and d['second'] == None: raise Exception f = f[1:] for i in range(len(f)): s = d[f[i]] if s != None: if f[i] == 'second': s = float(s) else: try: s = int(s) except ValueError: s = long(s) if i < fn: fn = i r.append(s) if fn > len(r): # Any non-Nones? raise Exception if d['sign'] == '-': r[fn] = -r[fn] return tuple(r) if kind == 'recurringInstant': for i in range(len(f)): s = d[f[i]] if s == None or s == '-': if i > fn: raise Exception s = None else: if i < fn: fn = i if f[i] == 'second': s = float(s) else: try: s = int(s) except ValueError: s = long(s) r.append(s) s = r.pop(0) if fn == 0: r[0] += s * 100 else: fn -= 1 if fn < len(r) and d['sign'] == '-': r[fn] = -r[fn] cleanDate(r, fn) return tuple(applyZoneOffset(self.DATETIMECONSTS.months, getZoneOffset(d), r, fn, 0)) r = [0, 0, 1, 1, 0, 0, 0] for i in range(len(f)): field = f[i] s = d.get(field) if s != None: if field == 'second': s = float(s) else: try: s = int(s) except ValueError: s = long(s) if i < fn: fn = i r[i] = s if fn > len(r): # Any non-Nones? raise Exception s = r.pop(0) if fn == 0: r[0] += s * 100 else: fn -= 1 if d.get('sign') == '-': r[fn] = -r[fn] cleanDate(r, fn) zoffs = getZoneOffset(d) if zoffs: r = applyZoneOffset(self.DATETIMECONSTS.months, zoffs, r, fn) if kind == 'century': return r[0] / 100 s = [] for i in range(1, len(f)): if d.has_key(f[i]): s.append(r[i - 1]) if len(s) == 1: return s[0] return tuple(s) except Exception, e: raise Error, "invalid %s value `%s' - %s" % (kind, value, e) intlimits = \ { 'nonPositiveInteger': (0, None, 0), 'non-positive-integer': (0, None, 0), 'negativeInteger': (0, None, -1), 'negative-integer': (0, None, -1), 'long': (1, -9223372036854775808L, 9223372036854775807L), 'int': (0, -2147483648L, 2147483647L), 'short': (0, -32768, 32767), 'byte': (0, -128, 127), 'nonNegativeInteger': (0, 0, None), 'non-negative-integer': (0, 0, None), 'positiveInteger': (0, 1, None), 'positive-integer': (0, 1, None), 'unsignedLong': (1, 0, 18446744073709551615L), 'unsignedInt': (0, 0, 4294967295L), 'unsignedShort': (0, 0, 65535), 'unsignedByte': (0, 0, 255), } floatlimits = \ { 'float': (7.0064923216240861E-46, -3.4028234663852886E+38, 3.4028234663852886E+38), 'double': (2.4703282292062327E-324, -1.7976931348623158E+308, 1.7976931348623157E+308), } zerofloatre = '[1-9]' def convertType(self, d, t, attrs, config=Config): if t[0] is None and t[1] is not None: type = t[1].strip() if type[:9] == 'arrayType': index_eq = type.find('=') index_obr = type.find('[') index_cbr = type.find(']') elemtype = type[index_eq+1:index_obr] elemnum = type[index_obr+1:index_cbr] if elemtype=="ur-type": return(d) else: newarr = map( lambda(di): self.convertToBasicTypes(d=di, t = ( NS.XSD, elemtype), attrs=attrs, config=config), d) return newarr else: t = (NS.XSD, t[1]) return self.convertToBasicTypes(d, t, attrs, config) def convertToSOAPpyTypes(self, d, t, attrs, config=Config): pass def convertToBasicTypes(self, d, t, attrs, config=Config): dnn = d or '' #if Config.debug: #print "convertToBasicTypes:" #print " requested_type=", t #print " data=", d # print "convertToBasicTypes:" # print " requested_type=", t # print " data=", d # print " attrs=", attrs # print " t[0]=", t[0] # print " t[1]=", t[1] # print " in?", t[0] in NS.EXSD_L if t[0] in NS.EXSD_L: if t[1]=="integer": # unbounded integer type try: d = int(d) if len(attrs): d = long(d) except: d = long(d) return d if self.intlimits.has_key (t[1]): # range-bounded integer types l = self.intlimits[t[1]] try: d = int(d) except: d = long(d) if l[1] != None and d < l[1]: raise UnderflowError, "%s too small" % d if l[2] != None and d > l[2]: raise OverflowError, "%s too large" % d if l[0] or len(attrs): return long(d) return d if t[1] == "string": if len(attrs): return unicode(dnn) try: return str(dnn) except: return dnn if t[1] in ("bool", "boolean"): d = d.strip().lower() if d in ('0', 'false'): return False if d in ('1', 'true'): return True raise AttributeError, "invalid boolean value" if t[1] in ('double','float'): l = self.floatlimits[t[1]] s = d.strip().lower() # Explicitly check for NaN and Infinities if s == "nan": d = fpconst.NaN elif s[0:2]=="inf" or s[0:3]=="+inf": d = fpconst.PosInf elif s[0:3] == "-inf": d = fpconst.NegInf else : d = float(s) if config.strict_range: if fpconst.isNaN(d): if s[0:2] != 'nan': raise ValueError, "invalid %s: %s" % (t[1], s) elif fpconst.isNegInf(d): if s[0:3] != '-inf': raise UnderflowError, "%s too small: %s" % (t[1], s) elif fpconst.isPosInf(d): if s[0:2] != 'inf' and s[0:3] != '+inf': raise OverflowError, "%s too large: %s" % (t[1], s) elif d < 0 and d < l[1]: raise UnderflowError, "%s too small: %s" % (t[1], s) elif d > 0 and ( d < l[0] or d > l[2] ): raise OverflowError, "%s too large: %s" % (t[1], s) elif d == 0: if type(self.zerofloatre) == StringType: self.zerofloatre = re.compile(self.zerofloatre) if self.zerofloatre.search(s): raise UnderflowError, "invalid %s: %s" % (t[1], s) return d if t[1] in ("dateTime", "date", "timeInstant", "time"): return self.convertDateTime(d, t[1]) if t[1] == "decimal": return float(d) if t[1] in ("language", "QName", "NOTATION", "NMTOKEN", "Name", "NCName", "ID", "IDREF", "ENTITY"): return collapseWhiteSpace(d) if t[1] in ("IDREFS", "ENTITIES", "NMTOKENS"): d = collapseWhiteSpace(d) return d.split() if t[0] in NS.XSD_L: if t[1] in ("base64", "base64Binary"): if d: return base64.decodestring(d) else: return '' if t[1] == "hexBinary": if d: return decodeHexString(d) else: return if t[1] == "anyURI": return urllib.unquote(collapseWhiteSpace(d)) if t[1] in ("normalizedString", "token"): return collapseWhiteSpace(d) if t[0] == NS.ENC: if t[1] == "base64": if d: return base64.decodestring(d) else: return '' if t[0] == NS.XSD: if t[1] == "binary": try: e = attrs[(None, 'encoding')] if d: if e == 'hex': return decodeHexString(d) elif e == 'base64': return base64.decodestring(d) else: return '' except: pass raise Error, "unknown or missing binary encoding" if t[1] == "uri": return urllib.unquote(collapseWhiteSpace(d)) if t[1] == "recurringInstant": return self.convertDateTime(d, t[1]) if t[0] in (NS.XSD2, NS.ENC): if t[1] == "uriReference": return urllib.unquote(collapseWhiteSpace(d)) if t[1] == "timePeriod": return self.convertDateTime(d, t[1]) if t[1] in ("century", "year"): return self.convertDateTime(d, t[1]) if t[0] in (NS.XSD, NS.XSD2, NS.ENC): if t[1] == "timeDuration": return self.convertDateTime(d, t[1]) if t[0] == NS.XSD3: if t[1] == "anyURI": return urllib.unquote(collapseWhiteSpace(d)) if t[1] in ("gYearMonth", "gMonthDay"): return self.convertDateTime(d, t[1]) if t[1] == "gYear": return self.convertDateTime(d, t[1]) if t[1] == "gMonth": return self.convertDateTime(d, t[1]) if t[1] == "gDay": return self.convertDateTime(d, t[1]) if t[1] == "duration": return self.convertDateTime(d, t[1]) if t[0] in (NS.XSD2, NS.XSD3): if t[1] == "token": return collapseWhiteSpace(d) if t[1] == "recurringDate": return self.convertDateTime(d, t[1]) if t[1] == "month": return self.convertDateTime(d, t[1]) if t[1] == "recurringDay": return self.convertDateTime(d, t[1]) if t[0] == NS.XSD2: if t[1] == "CDATA": return collapseWhiteSpace(d) raise UnknownTypeError, "unknown type `%s'" % (str(t[0]) + ':' + t[1]) ################################################################################ # call to SOAPParser that keeps all of the info ################################################################################ def _parseSOAP(xml_str, rules = None): try: from cStringIO import StringIO except ImportError: from StringIO import StringIO parser = xml.sax.make_parser() t = SOAPParser(rules = rules) parser.setContentHandler(t) e = xml.sax.handler.ErrorHandler() parser.setErrorHandler(e) inpsrc = xml.sax.xmlreader.InputSource() inpsrc.setByteStream(StringIO(xml_str)) # turn on namespace mangeling parser.setFeature(xml.sax.handler.feature_namespaces,1) try: parser.parse(inpsrc) except xml.sax.SAXParseException, e: parser._parser = None raise e return t ################################################################################ # SOAPParser's more public interface ################################################################################ def parseSOAP(xml_str, attrs = 0): t = _parseSOAP(xml_str) if attrs: return t.body, t.attrs return t.body def parseSOAPRPC(xml_str, header = 0, body = 0, attrs = 0, rules = None): t = _parseSOAP(xml_str, rules = rules) p = t.body[0] # Empty string, for RPC this translates into a void if type(p) in (type(''), type(u'')) and p in ('', u''): name = "Response" for k in t.body.__dict__.keys(): if k[0] != "_": name = k p = structType(name) if header or body or attrs: ret = (p,) if header : ret += (t.header,) if body: ret += (t.body,) if attrs: ret += (t.attrs,) return ret else: return p
# Copyright 2013-2015 DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from cassandra.concurrent import execute_concurrent try: import unittest2 as unittest except ImportError: import unittest # noqa from cassandra import ConsistencyLevel from cassandra.query import (PreparedStatement, BoundStatement, SimpleStatement, BatchStatement, BatchType, dict_factory) from cassandra.cluster import Cluster from cassandra.policies import HostDistance from tests.integration import use_singledc, PROTOCOL_VERSION, BasicSharedKeyspaceUnitTestCase, get_server_versions import re def setup_module(): use_singledc() global CASS_SERVER_VERSION CASS_SERVER_VERSION = get_server_versions()[0] class QueryTests(unittest.TestCase): def test_query(self): cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() prepared = session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1, None)) self.assertIsInstance(bound, BoundStatement) self.assertEqual(2, len(bound.values)) session.execute(bound) self.assertEqual(bound.routing_key, b'\x00\x00\x00\x01') cluster.shutdown() def test_trace_prints_okay(self): """ Code coverage to ensure trace prints to string without error """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() query = "SELECT * FROM system.local" statement = SimpleStatement(query) rs = session.execute(statement, trace=True) # Ensure this does not throw an exception trace = rs.get_query_trace() self.assertTrue(trace.events) str(trace) for event in trace.events: str(event) cluster.shutdown() def test_trace_id_to_resultset(self): cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() future = session.execute_async("SELECT * FROM system.local", trace=True) # future should have the current trace rs = future.result() future_trace = future.get_query_trace() self.assertIsNotNone(future_trace) rs_trace = rs.get_query_trace() self.assertEqual(rs_trace, future_trace) self.assertTrue(rs_trace.events) self.assertEqual(len(rs_trace.events), len(future_trace.events)) self.assertListEqual([rs_trace], rs.get_all_query_traces()) cluster.shutdown() def test_trace_ignores_row_factory(self): cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() session.row_factory = dict_factory query = "SELECT * FROM system.local" statement = SimpleStatement(query) rs = session.execute(statement, trace=True) # Ensure this does not throw an exception trace = rs.get_query_trace() self.assertTrue(trace.events) str(trace) for event in trace.events: str(event) cluster.shutdown() def test_client_ip_in_trace(self): """ Test to validate that client trace contains client ip information. creates a simple query and ensures that the client trace information is present. This will only be the case if the c* version is 2.2 or greater @since 2.6.0 @jira_ticket PYTHON-235 @expected_result client address should be present in C* >= 2.2, otherwise should be none. @test_category tracing #The current version on the trunk doesn't have the version set to 2.2 yet. #For now we will use the protocol version. Once they update the version on C* trunk #we can use the C*. See below #self._cass_version, self._cql_version = get_server_versions() #if self._cass_version < (2, 2): # raise unittest.SkipTest("Client IP was not present in trace until C* 2.2") """ if PROTOCOL_VERSION < 4: raise unittest.SkipTest( "Protocol 4+ is required for client ip tracing, currently testing against %r" % (PROTOCOL_VERSION,)) cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() # Make simple query with trace enabled query = "SELECT * FROM system.local" statement = SimpleStatement(query) response_future = session.execute_async(statement, trace=True) response_future.result() # Fetch the client_ip from the trace. trace = response_future.get_query_trace(max_wait=2.0) client_ip = trace.client # Ip address should be in the local_host range pat = re.compile("127.0.0.\d{1,3}") # Ensure that ip is set self.assertIsNotNone(client_ip, "Client IP was not set in trace with C* >= 2.2") self.assertTrue(pat.match(client_ip), "Client IP from trace did not match the expected value") cluster.shutdown() class PreparedStatementTests(unittest.TestCase): def setUp(self): self.cluster = Cluster(protocol_version=PROTOCOL_VERSION) self.session = self.cluster.connect() def tearDown(self): self.cluster.shutdown() def test_routing_key(self): """ Simple code coverage to ensure routing_keys can be accessed """ prepared = self.session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1, None)) self.assertEqual(bound.routing_key, b'\x00\x00\x00\x01') def test_empty_routing_key_indexes(self): """ Ensure when routing_key_indexes are blank, the routing key should be None """ prepared = self.session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) prepared.routing_key_indexes = None self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1, None)) self.assertEqual(bound.routing_key, None) def test_predefined_routing_key(self): """ Basic test that ensures _set_routing_key() overrides the current routing key """ prepared = self.session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1, None)) bound._set_routing_key('fake_key') self.assertEqual(bound.routing_key, 'fake_key') def test_multiple_routing_key_indexes(self): """ Basic test that uses a fake routing_key_index """ prepared = self.session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) prepared.routing_key_indexes = [0, 1] bound = prepared.bind((1, 2)) self.assertEqual(bound.routing_key, b'\x00\x04\x00\x00\x00\x01\x00\x00\x04\x00\x00\x00\x02\x00') prepared.routing_key_indexes = [1, 0] bound = prepared.bind((1, 2)) self.assertEqual(bound.routing_key, b'\x00\x04\x00\x00\x00\x02\x00\x00\x04\x00\x00\x00\x01\x00') def test_bound_keyspace(self): """ Ensure that bound.keyspace works as expected """ prepared = self.session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1, 2)) self.assertEqual(bound.keyspace, 'test3rf') class PrintStatementTests(unittest.TestCase): """ Test that shows the format used when printing Statements """ def test_simple_statement(self): """ Highlight the format of printing SimpleStatements """ ss = SimpleStatement('SELECT * FROM test3rf.test', consistency_level=ConsistencyLevel.ONE) self.assertEqual(str(ss), '<SimpleStatement query="SELECT * FROM test3rf.test", consistency=ONE>') def test_prepared_statement(self): """ Highlight the difference between Prepared and Bound statements """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() prepared = session.prepare('INSERT INTO test3rf.test (k, v) VALUES (?, ?)') prepared.consistency_level = ConsistencyLevel.ONE self.assertEqual(str(prepared), '<PreparedStatement query="INSERT INTO test3rf.test (k, v) VALUES (?, ?)", consistency=ONE>') bound = prepared.bind((1, 2)) self.assertEqual(str(bound), '<BoundStatement query="INSERT INTO test3rf.test (k, v) VALUES (?, ?)", values=(1, 2), consistency=ONE>') cluster.shutdown() class BatchStatementTests(unittest.TestCase): def setUp(self): if PROTOCOL_VERSION < 2: raise unittest.SkipTest( "Protocol 2.0+ is required for BATCH operations, currently testing against %r" % (PROTOCOL_VERSION,)) self.cluster = Cluster(protocol_version=PROTOCOL_VERSION) if PROTOCOL_VERSION < 3: self.cluster.set_core_connections_per_host(HostDistance.LOCAL, 1) self.session = self.cluster.connect() self.session.execute("TRUNCATE test3rf.test") def tearDown(self): self.cluster.shutdown() def confirm_results(self): keys = set() values = set() # Assuming the test data is inserted at default CL.ONE, we need ALL here to guarantee we see # everything inserted results = self.session.execute(SimpleStatement("SELECT * FROM test3rf.test", consistency_level=ConsistencyLevel.ALL)) for result in results: keys.add(result.k) values.add(result.v) self.assertEqual(set(range(10)), keys, msg=results) self.assertEqual(set(range(10)), values, msg=results) def test_string_statements(self): batch = BatchStatement(BatchType.LOGGED) for i in range(10): batch.add("INSERT INTO test3rf.test (k, v) VALUES (%s, %s)", (i, i)) self.session.execute(batch) self.session.execute_async(batch).result() self.confirm_results() def test_simple_statements(self): batch = BatchStatement(BatchType.LOGGED) for i in range(10): batch.add(SimpleStatement("INSERT INTO test3rf.test (k, v) VALUES (%s, %s)"), (i, i)) self.session.execute(batch) self.session.execute_async(batch).result() self.confirm_results() def test_prepared_statements(self): prepared = self.session.prepare("INSERT INTO test3rf.test (k, v) VALUES (?, ?)") batch = BatchStatement(BatchType.LOGGED) for i in range(10): batch.add(prepared, (i, i)) self.session.execute(batch) self.session.execute_async(batch).result() self.confirm_results() def test_bound_statements(self): prepared = self.session.prepare("INSERT INTO test3rf.test (k, v) VALUES (?, ?)") batch = BatchStatement(BatchType.LOGGED) for i in range(10): batch.add(prepared.bind((i, i))) self.session.execute(batch) self.session.execute_async(batch).result() self.confirm_results() def test_no_parameters(self): batch = BatchStatement(BatchType.LOGGED) batch.add("INSERT INTO test3rf.test (k, v) VALUES (0, 0)") batch.add("INSERT INTO test3rf.test (k, v) VALUES (1, 1)", ()) batch.add(SimpleStatement("INSERT INTO test3rf.test (k, v) VALUES (2, 2)")) batch.add(SimpleStatement("INSERT INTO test3rf.test (k, v) VALUES (3, 3)"), ()) prepared = self.session.prepare("INSERT INTO test3rf.test (k, v) VALUES (4, 4)") batch.add(prepared) batch.add(prepared, ()) batch.add(prepared.bind([])) batch.add(prepared.bind([]), ()) batch.add("INSERT INTO test3rf.test (k, v) VALUES (5, 5)", ()) batch.add("INSERT INTO test3rf.test (k, v) VALUES (6, 6)", ()) batch.add("INSERT INTO test3rf.test (k, v) VALUES (7, 7)", ()) batch.add("INSERT INTO test3rf.test (k, v) VALUES (8, 8)", ()) batch.add("INSERT INTO test3rf.test (k, v) VALUES (9, 9)", ()) self.assertRaises(ValueError, batch.add, prepared.bind([]), (1)) self.assertRaises(ValueError, batch.add, prepared.bind([]), (1, 2)) self.assertRaises(ValueError, batch.add, prepared.bind([]), (1, 2, 3)) self.session.execute(batch) self.confirm_results() def test_no_parameters_many_times(self): for i in range(1000): self.test_no_parameters() self.session.execute("TRUNCATE test3rf.test") class SerialConsistencyTests(unittest.TestCase): def setUp(self): if PROTOCOL_VERSION < 2: raise unittest.SkipTest( "Protocol 2.0+ is required for Serial Consistency, currently testing against %r" % (PROTOCOL_VERSION,)) self.cluster = Cluster(protocol_version=PROTOCOL_VERSION) if PROTOCOL_VERSION < 3: self.cluster.set_core_connections_per_host(HostDistance.LOCAL, 1) self.session = self.cluster.connect() def tearDown(self): self.cluster.shutdown() def test_conditional_update(self): self.session.execute("INSERT INTO test3rf.test (k, v) VALUES (0, 0)") statement = SimpleStatement( "UPDATE test3rf.test SET v=1 WHERE k=0 IF v=1", serial_consistency_level=ConsistencyLevel.SERIAL) # crazy test, but PYTHON-299 # TODO: expand to check more parameters get passed to statement, and on to messages self.assertEqual(statement.serial_consistency_level, ConsistencyLevel.SERIAL) future = self.session.execute_async(statement) result = future.result() self.assertEqual(future.message.serial_consistency_level, ConsistencyLevel.SERIAL) self.assertTrue(result) self.assertFalse(result[0].applied) statement = SimpleStatement( "UPDATE test3rf.test SET v=1 WHERE k=0 IF v=0", serial_consistency_level=ConsistencyLevel.LOCAL_SERIAL) self.assertEqual(statement.serial_consistency_level, ConsistencyLevel.LOCAL_SERIAL) future = self.session.execute_async(statement) result = future.result() self.assertEqual(future.message.serial_consistency_level, ConsistencyLevel.LOCAL_SERIAL) self.assertTrue(result) self.assertTrue(result[0].applied) def test_conditional_update_with_prepared_statements(self): self.session.execute("INSERT INTO test3rf.test (k, v) VALUES (0, 0)") statement = self.session.prepare( "UPDATE test3rf.test SET v=1 WHERE k=0 IF v=2") statement.serial_consistency_level = ConsistencyLevel.SERIAL future = self.session.execute_async(statement) result = future.result() self.assertEqual(future.message.serial_consistency_level, ConsistencyLevel.SERIAL) self.assertTrue(result) self.assertFalse(result[0].applied) statement = self.session.prepare( "UPDATE test3rf.test SET v=1 WHERE k=0 IF v=0") bound = statement.bind(()) bound.serial_consistency_level = ConsistencyLevel.LOCAL_SERIAL future = self.session.execute_async(bound) result = future.result() self.assertEqual(future.message.serial_consistency_level, ConsistencyLevel.LOCAL_SERIAL) self.assertTrue(result) self.assertTrue(result[0].applied) def test_conditional_update_with_batch_statements(self): self.session.execute("INSERT INTO test3rf.test (k, v) VALUES (0, 0)") statement = BatchStatement(serial_consistency_level=ConsistencyLevel.SERIAL) statement.add("UPDATE test3rf.test SET v=1 WHERE k=0 IF v=1") self.assertEqual(statement.serial_consistency_level, ConsistencyLevel.SERIAL) future = self.session.execute_async(statement) result = future.result() self.assertEqual(future.message.serial_consistency_level, ConsistencyLevel.SERIAL) self.assertTrue(result) self.assertFalse(result[0].applied) statement = BatchStatement(serial_consistency_level=ConsistencyLevel.LOCAL_SERIAL) statement.add("UPDATE test3rf.test SET v=1 WHERE k=0 IF v=0") self.assertEqual(statement.serial_consistency_level, ConsistencyLevel.LOCAL_SERIAL) future = self.session.execute_async(statement) result = future.result() self.assertEqual(future.message.serial_consistency_level, ConsistencyLevel.LOCAL_SERIAL) self.assertTrue(result) self.assertTrue(result[0].applied) def test_bad_consistency_level(self): statement = SimpleStatement("foo") self.assertRaises(ValueError, setattr, statement, 'serial_consistency_level', ConsistencyLevel.ONE) self.assertRaises(ValueError, SimpleStatement, 'foo', serial_consistency_level=ConsistencyLevel.ONE) class LightweightTransactionTests(unittest.TestCase): def setUp(self): """ Test is skipped if run with cql version < 2 """ if PROTOCOL_VERSION < 2: raise unittest.SkipTest( "Protocol 2.0+ is required for Lightweight transactions, currently testing against %r" % (PROTOCOL_VERSION,)) self.cluster = Cluster(protocol_version=PROTOCOL_VERSION) self.session = self.cluster.connect() ddl = ''' CREATE TABLE test3rf.lwt ( k int PRIMARY KEY, v int )''' self.session.execute(ddl) def tearDown(self): """ Shutdown cluster """ self.session.execute("DROP TABLE test3rf.lwt") self.cluster.shutdown() def test_no_connection_refused_on_timeout(self): """ Test for PYTHON-91 "Connection closed after LWT timeout" Verifies that connection to the cluster is not shut down when timeout occurs. Number of iterations can be specified with LWT_ITERATIONS environment variable. Default value is 1000 """ insert_statement = self.session.prepare("INSERT INTO test3rf.lwt (k, v) VALUES (0, 0) IF NOT EXISTS") delete_statement = self.session.prepare("DELETE FROM test3rf.lwt WHERE k = 0 IF EXISTS") iterations = int(os.getenv("LWT_ITERATIONS", 1000)) # Prepare series of parallel statements statements_and_params = [] for i in range(iterations): statements_and_params.append((insert_statement, ())) statements_and_params.append((delete_statement, ())) received_timeout = False results = execute_concurrent(self.session, statements_and_params, raise_on_first_error=False) for (success, result) in results: if success: continue else: # In this case result is an exception if type(result).__name__ == "NoHostAvailable": self.fail("PYTHON-91: Disconnected from Cassandra: %s" % result.message) if type(result).__name__ == "WriteTimeout": received_timeout = True continue if type(result).__name__ == "WriteFailure": received_timeout = True continue if type(result).__name__ == "ReadTimeout": continue if type(result).__name__ == "ReadFailure": continue self.fail("Unexpected exception %s: %s" % (type(result).__name__, result.message)) # Make sure test passed self.assertTrue(received_timeout) class BatchStatementDefaultRoutingKeyTests(unittest.TestCase): # Test for PYTHON-126: BatchStatement.add() should set the routing key of the first added prepared statement def setUp(self): if PROTOCOL_VERSION < 2: raise unittest.SkipTest( "Protocol 2.0+ is required for BATCH operations, currently testing against %r" % (PROTOCOL_VERSION,)) self.cluster = Cluster(protocol_version=PROTOCOL_VERSION) self.session = self.cluster.connect() query = """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """ self.simple_statement = SimpleStatement(query, routing_key='ss_rk', keyspace='keyspace_name') self.prepared = self.session.prepare(query) def tearDown(self): self.cluster.shutdown() def test_rk_from_bound(self): """ batch routing key is inherited from BoundStatement """ bound = self.prepared.bind((1, None)) batch = BatchStatement() batch.add(bound) self.assertIsNotNone(batch.routing_key) self.assertEqual(batch.routing_key, bound.routing_key) def test_rk_from_simple(self): """ batch routing key is inherited from SimpleStatement """ batch = BatchStatement() batch.add(self.simple_statement) self.assertIsNotNone(batch.routing_key) self.assertEqual(batch.routing_key, self.simple_statement.routing_key) def test_inherit_first_rk_bound(self): """ compound batch inherits the first routing key of the first added statement (bound statement is first) """ bound = self.prepared.bind((100000000, None)) batch = BatchStatement() batch.add("ss with no rk") batch.add(bound) batch.add(self.simple_statement) for i in range(3): batch.add(self.prepared, (i, i)) self.assertIsNotNone(batch.routing_key) self.assertEqual(batch.routing_key, bound.routing_key) def test_inherit_first_rk_simple_statement(self): """ compound batch inherits the first routing key of the first added statement (Simplestatement is first) """ bound = self.prepared.bind((1, None)) batch = BatchStatement() batch.add("ss with no rk") batch.add(self.simple_statement) batch.add(bound) for i in range(10): batch.add(self.prepared, (i, i)) self.assertIsNotNone(batch.routing_key) self.assertEqual(batch.routing_key, self.simple_statement.routing_key) def test_inherit_first_rk_prepared_param(self): """ compound batch inherits the first routing key of the first added statement (prepared statement is first) """ bound = self.prepared.bind((2, None)) batch = BatchStatement() batch.add("ss with no rk") batch.add(self.prepared, (1, 0)) batch.add(bound) batch.add(self.simple_statement) self.assertIsNotNone(batch.routing_key) self.assertEqual(batch.routing_key, self.prepared.bind((1, 0)).routing_key) class MaterializedViewQueryTest(BasicSharedKeyspaceUnitTestCase): def setUp(self): if CASS_SERVER_VERSION < (3, 0): raise unittest.SkipTest("Materialized views require Cassandra 3.0+") def test_mv_filtering(self): """ Test to ensure that cql filtering where clauses are properly supported in the python driver. test_mv_filtering Tests that various complex MV where clauses produce the correct results. It also validates that these results and the grammar is supported appropriately. @since 3.0.0 @jira_ticket PYTHON-399 @expected_result Materialized view where clauses should produce the appropriate results. @test_category materialized_view """ create_table = """CREATE TABLE {0}.scores( user TEXT, game TEXT, year INT, month INT, day INT, score INT, PRIMARY KEY (user, game, year, month, day) )""".format(self.keyspace_name) self.session.execute(create_table) create_mv_alltime = """CREATE MATERIALIZED VIEW {0}.alltimehigh AS SELECT * FROM {0}.scores WHERE game IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND day IS NOT NULL PRIMARY KEY (game, score, user, year, month, day) WITH CLUSTERING ORDER BY (score DESC)""".format(self.keyspace_name) create_mv_dailyhigh = """CREATE MATERIALIZED VIEW {0}.dailyhigh AS SELECT * FROM {0}.scores WHERE game IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND day IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL PRIMARY KEY ((game, year, month, day), score, user) WITH CLUSTERING ORDER BY (score DESC)""".format(self.keyspace_name) create_mv_monthlyhigh = """CREATE MATERIALIZED VIEW {0}.monthlyhigh AS SELECT * FROM {0}.scores WHERE game IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND score IS NOT NULL AND user IS NOT NULL AND day IS NOT NULL PRIMARY KEY ((game, year, month), score, user, day) WITH CLUSTERING ORDER BY (score DESC)""".format(self.keyspace_name) create_mv_filtereduserhigh = """CREATE MATERIALIZED VIEW {0}.filtereduserhigh AS SELECT * FROM {0}.scores WHERE user in ('jbellis', 'pcmanus') AND game IS NOT NULL AND score IS NOT NULL AND year is NOT NULL AND day is not NULL and month IS NOT NULL PRIMARY KEY (game, score, user, year, month, day) WITH CLUSTERING ORDER BY (score DESC)""".format(self.keyspace_name) self.session.execute(create_mv_alltime) self.session.execute(create_mv_dailyhigh) self.session.execute(create_mv_monthlyhigh) self.session.execute(create_mv_filtereduserhigh) prepared_insert = self.session.prepare("""INSERT INTO {0}.scores (user, game, year, month, day, score) VALUES (?, ?, ? ,? ,?, ?)""".format(self.keyspace_name)) bound = prepared_insert.bind(('pcmanus', 'Coup', 2015, 5, 1, 4000)) self.session.execute(bound) bound = prepared_insert.bind(('jbellis', 'Coup', 2015, 5, 3, 1750)) self.session.execute(bound) bound = prepared_insert.bind(('yukim', 'Coup', 2015, 5, 3, 2250)) self.session.execute(bound) bound = prepared_insert.bind(('tjake', 'Coup', 2015, 5, 3, 500)) self.session.execute(bound) bound = prepared_insert.bind(('iamaleksey', 'Coup', 2015, 6, 1, 2500)) self.session.execute(bound) bound = prepared_insert.bind(('tjake', 'Coup', 2015, 6, 2, 1000)) self.session.execute(bound) bound = prepared_insert.bind(('pcmanus', 'Coup', 2015, 6, 2, 2000)) self.session.execute(bound) bound = prepared_insert.bind(('jmckenzie', 'Coup', 2015, 6, 9, 2700)) self.session.execute(bound) bound = prepared_insert.bind(('jbellis', 'Coup', 2015, 6, 20, 3500)) self.session.execute(bound) bound = prepared_insert.bind(('jbellis', 'Checkers', 2015, 6, 20, 1200)) self.session.execute(bound) bound = prepared_insert.bind(('jbellis', 'Chess', 2015, 6, 21, 3500)) self.session.execute(bound) bound = prepared_insert.bind(('pcmanus', 'Chess', 2015, 1, 25, 3200)) self.session.execute(bound) # Test simple statement and alltime high filtering query_statement = SimpleStatement("SELECT * FROM {0}.alltimehigh WHERE game='Coup'".format(self.keyspace_name), consistency_level=ConsistencyLevel.QUORUM) results = self.session.execute(query_statement) self.assertEquals(results[0].game, 'Coup') self.assertEquals(results[0].year, 2015) self.assertEquals(results[0].month, 5) self.assertEquals(results[0].day, 1) self.assertEquals(results[0].score, 4000) self.assertEquals(results[0].user, "pcmanus") # Test prepared statement and daily high filtering prepared_query = self.session.prepare("SELECT * FROM {0}.dailyhigh WHERE game=? AND year=? AND month=? and day=?".format(self.keyspace_name)) bound_query = prepared_query.bind(("Coup", 2015, 6, 2)) results = self.session.execute(bound_query) self.assertEquals(results[0].game, 'Coup') self.assertEquals(results[0].year, 2015) self.assertEquals(results[0].month, 6) self.assertEquals(results[0].day, 2) self.assertEquals(results[0].score, 2000) self.assertEquals(results[0].user, "pcmanus") self.assertEquals(results[1].game, 'Coup') self.assertEquals(results[1].year, 2015) self.assertEquals(results[1].month, 6) self.assertEquals(results[1].day, 2) self.assertEquals(results[1].score, 1000) self.assertEquals(results[1].user, "tjake") # Test montly high range queries prepared_query = self.session.prepare("SELECT * FROM {0}.monthlyhigh WHERE game=? AND year=? AND month=? and score >= ? and score <= ?".format(self.keyspace_name)) bound_query = prepared_query.bind(("Coup", 2015, 6, 2500, 3500)) results = self.session.execute(bound_query) self.assertEquals(results[0].game, 'Coup') self.assertEquals(results[0].year, 2015) self.assertEquals(results[0].month, 6) self.assertEquals(results[0].day, 20) self.assertEquals(results[0].score, 3500) self.assertEquals(results[0].user, "jbellis") self.assertEquals(results[1].game, 'Coup') self.assertEquals(results[1].year, 2015) self.assertEquals(results[1].month, 6) self.assertEquals(results[1].day, 9) self.assertEquals(results[1].score, 2700) self.assertEquals(results[1].user, "jmckenzie") self.assertEquals(results[2].game, 'Coup') self.assertEquals(results[2].year, 2015) self.assertEquals(results[2].month, 6) self.assertEquals(results[2].day, 1) self.assertEquals(results[2].score, 2500) self.assertEquals(results[2].user, "iamaleksey") # Test filtered user high scores query_statement = SimpleStatement("SELECT * FROM {0}.filtereduserhigh WHERE game='Chess'".format(self.keyspace_name), consistency_level=ConsistencyLevel.QUORUM) results = self.session.execute(query_statement) self.assertEquals(results[0].game, 'Chess') self.assertEquals(results[0].year, 2015) self.assertEquals(results[0].month, 6) self.assertEquals(results[0].day, 21) self.assertEquals(results[0].score, 3500) self.assertEquals(results[0].user, "jbellis") self.assertEquals(results[1].game, 'Chess') self.assertEquals(results[1].year, 2015) self.assertEquals(results[1].month, 1) self.assertEquals(results[1].day, 25) self.assertEquals(results[1].score, 3200) self.assertEquals(results[1].user, "pcmanus")
# coding=utf-8 """This module defines functions to read and write CSV files""" import collections import logging import os import pandas as pd import six import py_entitymatching.catalog.catalog_manager as cm from py_entitymatching.utils.validation_helper import validate_object_type logger = logging.getLogger(__name__) def read_csv_metadata(file_path, **kwargs): """ Reads a CSV (comma-separated values) file into a pandas DataFrame and update the catalog with the metadata. The CSV files typically contain data for the input tables or a candidate set. Specifically, this function first reads the CSV file from the given file path into a pandas DataFrame, by using pandas' in-built 'read_csv' method. Then, it updates the catalog with the metadata. There are three ways to update the metadata: (1) using a metadata file, (2) using the key-value parameters supplied in the function, and (3) using both metadata file and key-value parameters. To update the metadata in the catalog using the metadata file, the function will look for a file in the same directory with same file name but with a specific extension. This extension can be optionally given by the user (defaults to '.metadata'). If the metadata file is present, the function will read and update the catalog appropriately. If the metadata file is not present, the function will issue a warning that the metadata file is not present. The metadata information can also be given as parameters to the function (see description of arguments for more details). If given, the function will update the catalog with the given information. Further, the metadata can partly reside in the metdata file and partly as supplied parameters. The function will take a union of the two and update the catalog appropriately. If the same metadata is given in both the metadata file and the function, then the metadata in the function takes precedence over the metadata given in the file. Args: file_path(string): The CSV file path kwargs(dictionary): A Python dictionary containing key-value arguments. There are a few key-value pairs that are specific to read_csv_metadata and all the other key-value pairs are passed to pandas read_csv method Returns: A pandas DataFrame read from the input CSV file. Raises: AssertionError: If `file_path` is not of type string. AssertionError: If a file does not exist in the given `file_path`. Examples: *Example 1:* Read from CSV file and set metadata >>> A = em.read_csv_metadata('path_to_csv_file', key='id') >>> em.get_key(A) # 'id' *Example 2:* Read from CSV file (with metadata file in the same directory Let the metadata file contain the following contents: #key = id >>> A = em.read_csv_metadata('path_to_csv_file') >>> em.get_key(A) # 'id' See Also: :meth:`~py_entitymatching.to_csv_metadata` """ # Validate the input parameters. validate_object_type(file_path, six.string_types, error_prefix='Input file path') # # Check if the given path is valid. if not os.path.exists(file_path): logger.error('File does not exist at path %s' % file_path) raise AssertionError('File does not exist at path %s' % file_path) # Check if the user has specified the metadata file's extension. extension = kwargs.pop('metadata_extn', None) # If the extension is not specified then set the extension to .metadata'. if extension is None: extension = '.metadata' # Format the extension to include a '.' in front if the user has not # given one. if not extension.startswith('.'): extension = '.' + extension # If the file is present, then update metadata from file. if _is_metadata_file_present(file_path, extension=extension): file_name, _ = os.path.splitext(file_path) file_name = ''.join([file_name, extension]) metadata, _ = _get_metadata_from_file(file_name) # Else issue a warning that the metadata file is not present else: logger.warning('Metadata file is not present in the given path; ' 'proceeding to read the csv file.') metadata = {} # Update the metadata with the key-value pairs given in the command. The # function _update_metadata_for_read_cmd takes care of updating the # metadata with only the key-value pairs specific to read_csv_metadata # method metadata, kwargs = _update_metadata_for_read_cmd(metadata, **kwargs) # Validate the metadata. _check_metadata_for_read_cmd(metadata) # Read the csv file using pandas read_csv method. data_frame = pd.read_csv(file_path, **kwargs) # Get the value for 'key' property and update the catalog. key = metadata.pop('key', None) if key is not None: cm.set_key(data_frame, key) fk_ltable = metadata.pop('fk_ltable', None) if fk_ltable is not None: cm.set_fk_ltable(data_frame, fk_ltable) fk_rtable = metadata.pop('fk_rtable', None) if fk_ltable is not None: cm.set_fk_rtable(data_frame, fk_rtable) # Update the catalog with other properties. for property_name, property_value in six.iteritems(metadata): cm.set_property(data_frame, property_name, property_value) if not cm.is_dfinfo_present(data_frame): cm.init_properties(data_frame) # Return the DataFrame return data_frame def to_csv_metadata(data_frame, file_path, **kwargs): """ Writes the DataFrame contents to a CSV file and the DataFrame's metadata (to a separate text file). This function writes the DataFrame contents to a CSV file in the given file path. It uses 'to_csv' method from pandas to write the CSV file. The metadata contents are written to the same directory derived from the file path but with the different extension. This extension can be optionally given by the user (with the default value set to .metadata). Args: data_frame (DataFrame): The DataFrame that should be written to disk. file_path (string): The file path to which the DataFrame contents should be written. Metadata is written with the same file name with the extension given by the user (defaults to '.metadata'). kwargs (dictionary): A Python dictionary containing key-value pairs. There is one key-value pair that is specific to to_csv_metadata: metadata_extn. All the other key-value pairs are passed to pandas to_csv function. Here the metadata_extn is the metadata extension (defaults to '.metadata'), with which the metadata file must be written. Returns: A Boolean value of True is returned if the files were written successfully. Raises: AssertionError: If `data_frame` is not of type pandas DataFrame. AssertionError: If `file_path` is not of type string. AssertionError: If DataFrame cannot be written to the given `file_path`. Examples: >>> import pandas as pd >>> A = pd.DataFrame({'id' : [1, 2], 'colA':['a', 'b'], 'colB' : [10, 20]}) >>> em.set_key(A, 'id') >>> em.to_csv_metadata(A, 'path_to_csv_file') See Also: :meth:`~py_entitymatching.read_csv_metadata` """ # Validate input parameters validate_object_type(data_frame, pd.DataFrame) validate_object_type(file_path, six.string_types, error_prefix='Input file path') # Check if the user has specified the metadata file's extension. extension = kwargs.pop('metadata_extn', None) if extension is None: extension = '.metadata' if not extension.startswith('.'): extension = '.' + extension # If the user has not specified whether the index should be written, # we explicitly set it to be false. The reason is writing the index # along makes the CSV file cumbersome to view and later read back into a # DataFrame. index = kwargs.pop('index', None) if index is None: kwargs['index'] = False # retrieve the file name and the extension from the given file path. file_name, _ = os.path.splitext(file_path) metadata_filename = file_name + extension # check if we access privileges to write a file in the given file path, # and also check if a file already exists in the file path. can_write, file_exists = _check_file_path(file_path) if can_write: # check if the file already exists. If so issue a warning and # overwrite the file. if file_exists: logger.warning('File already exists at %s; Overwriting it', file_path) data_frame.to_csv(file_path, **kwargs) else: data_frame.to_csv(file_path, **kwargs) else: # If we cannot write in the given file path, raise an exception. logger.error('Cannot write in the file path %s; Exiting' % file_path) raise AssertionError('Cannot write in the file path %s' % file_path) # repeat the process (as writing the DataFrame) to write the metadata. # check for access privileges and file existence. can_write, file_exists = _check_file_path(metadata_filename) if can_write: if file_exists: logger.warning('Metadata file already exists at %s. Overwriting ' 'it', metadata_filename) _write_metadata(data_frame, metadata_filename) else: _write_metadata(data_frame, metadata_filename) else: # If we cannot write in the given file path, raise an exception. logger.error('Cannot write in the file path %s; Exiting' % file_path) raise AssertionError('Cannot write in the file path %s' % file_path) return True def _write_metadata(data_frame, file_path): """ Write metadata contents to disk. """ # Initialize a metadata dictionary to store the metadata. metadata_dict = collections.OrderedDict() # Get all the properties for the input data frame if cm.is_dfinfo_present(data_frame) is True: properties = cm.get_all_properties(data_frame) else: # If the data_frame is not in the catalog, then return immedidately. return False # If the properties are present in the catalog, then write properties to # disk if len(properties) > 0: for property_name, property_value in six.iteritems(properties): # If the property value is not of type string, then just write it # as 'POINTER'. This will be useful while writing the candidate # sets to disk. The candidate set will have properties such as # ltable and rtable which are DataFrames. We do not have a simple # way to write them to disk and link them back the candidate set # while reading back from disk. So to get around this problem we # will use 'POINTER' as the special value to indicate objects # other than strings. if isinstance(property_value, six.string_types) is False: metadata_dict[property_name] = 'POINTER' else: metadata_dict[property_name] = property_value # Write the properties to a file in disk. The file will one property # per line. We follow a special syntax to write the properties. The # syntax is: # #property_name=property_value with open(file_path, 'w') as file_handler: for property_name, property_value in six.iteritems(metadata_dict): file_handler.write('#%s=%s\n' % (property_name, property_value)) return True def _is_metadata_file_present(file_path, extension='.metadata'): """ Check if the metadata file is present. """ # Get the file name and the extension from the file path. file_name, _ = os.path.splitext(file_path) # Create a file name with the given extension. file_name = ''.join([file_name, extension]) # Check if the file already exists. return os.path.exists(file_name) def _get_metadata_from_file(file_path): """ Get the metadata information from the file. """ # Initialize a dictionary to store the metadata read from the file. metadata = dict() # Get the number of lines from the file num_lines = sum(1 for _ in open(file_path)) # If there are some contents in the file (i.e num_lines > 0), # read its contents. if num_lines > 0: with open(file_path) as file_handler: for _ in range(num_lines): line = next(file_handler) # Consider only the lines that are starting with '#' if line.startswith('#'): # Remove the leading '#' line = line.lstrip('#') # Split the line with '=' as the delimiter tokens = line.split('=') # Based on the special syntax we use, there should be # exactly two tokens after we split using '=' assert len(tokens) is 2, 'Error in file, he num tokens ' \ 'is not 2' # Retrieve the property_names and values. property_name = tokens[0].strip() property_value = tokens[1].strip() # If the property value is not 'POINTER' then store it in # the metadata dictionary. if property_value is not 'POINTER': metadata[property_name] = property_value # Return the metadata dictionary and the number of lines in the file. return metadata, num_lines def _update_metadata_for_read_cmd(metadata, **kwargs): """ Update metadata for read_csv_metadata method. """ # Create a copy of incoming metadata. We will update the incoming # metadata dict with kwargs. copy_metadata = metadata.copy() # The updation is going to happen in two steps: (1) overriding the # properties in metadata dict using kwargs, and (2) adding the properties # to metadata dict from kwargs. # Step 1 # We will override the properties in the metadata dict with the # properties from kwargs. # Get the property from metadata dict. for property_name in copy_metadata.keys(): # If the same property is present in kwargs, then override it in the # metadata dict. if property_name in kwargs: property_value = kwargs.pop(property_name) if property_value is not None: metadata[property_name] = property_value else: # Warn the users if the metadata dict had a valid value, # but the kwargs sets it to None. logger.warning( '%s key had a value (%s)in file but input arg is set to ' 'None' % (property_name, metadata[property_name])) # Remove the property from the dictionary. metadata.pop(property_name) # remove the key-value pair # Step 2 # Add the properties from kwargs. # We should be careful here. The kwargs contains the key-value pairs that # are used by read_csv method (of pandas). We will just pick the # properties that we expect from the read_csv_metadata method. properties = ['key', 'ltable', 'rtable', 'fk_ltable', 'fk_rtable'] # For the properties that we expect, read from kwargs and update the # metadata dict. for property_name in properties: if property_name in kwargs: property_value = kwargs.pop(property_name) if property_value is not None: metadata[property_name] = property_value else: # Warn the users if the properties in the kwargs is set to None. logger.warning('Metadata %s is set to None', property_name) # Remove the property from the metadata dict. metadata.pop(property_name, None) return metadata, kwargs def _check_metadata_for_read_cmd(metadata): """ Check the metadata for read_csv_metadata command """ # Do basic validation checks for the metadata. # We require consistency of properties given for the canidate set. We # expect the user to provide all the required properties for the # candidate set. required_properties = ['ltable', 'rtable', 'fk_ltable', 'fk_rtable'] # Check what the user has given given_properties = set(required_properties).intersection(metadata.keys()) # Check if all the required properties are given if len(given_properties) > 0: # Check the lengths are same. If not, this means that the user is # missing something. So, raise an error. if len(given_properties) is not len(required_properties): logger.error( 'Dataframe requires all valid ltable, rtable, fk_ltable, ' 'fk_rtable parameters set') raise AssertionError( 'Dataframe requires all valid ltable, rtable, fk_ltable, ' 'fk_rtable parameters set') # ltable is expected to be of type pandas DataFrame. If not raise an # error. if not isinstance(metadata['ltable'], pd.DataFrame): logger.error('The parameter ltable must be set to valid Dataframe') raise AssertionError( 'The parameter ltable must be set to valid Dataframe') # rtable is expected to be of type pandas DataFrame. If not raise an # error. if not isinstance(metadata['rtable'], pd.DataFrame): logger.error('The parameter rtable must be set to valid Dataframe') raise AssertionError( 'The parameter rtable must be set to valid Dataframe') # If the length of comman properties is 0, it will fall out to return # True, which is ok. return True def _check_file_path(file_path): """ Check validity (access privileges and existence of a file already)of the given file path. """ # returns a tuple can_write, file_exists if os.path.exists(file_path): # the file is there return True, True elif os.access(os.path.dirname(file_path), os.W_OK): return True, False # the file does not exists but write privileges are given else: return False, False
# Copyright IBM Corp. 2016 All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import re import time import datetime import Queue import subprocess import devops_pb2 import fabric_pb2 import chaincode_pb2 import ab_pb2 import bdd_test_util import bdd_grpc_util from grpc.beta import implementations from grpc.framework.interfaces.face.face import NetworkError from grpc.framework.interfaces.face.face import AbortionError from grpc.beta.interfaces import StatusCode class StreamHelper: def __init__(self, ordererStub): self.streamClosed = False self.ordererStub = ordererStub self.sendQueue = Queue.Queue() self.receivedMessages = [] self.replyGenerator = None def setReplyGenerator(self, replyGenerator): assert self.replyGenerator == None, "reply generator already set!!" self.replyGenerator = replyGenerator def createSendGenerator(self, firstMsg, timeout = 2): yield firstMsg while True: try: nextMsg = self.sendQueue.get(True, timeout) if nextMsg: yield nextMsg else: #None indicates desire to close send return except Queue.Empty: return def readMessages(self, expectedCount): msgsReceived = [] counter = 0 try: for reply in self.replyGenerator: counter += 1 print("{0} received reply: {1}, counter = {2}".format("DeliverStreamHelper", reply, counter)) msgsReceived.append(reply) if counter == int(expectedCount): break except AbortionError as networkError: self.handleNetworkError(networkError) return msgsReceived def handleNetworkError(self, networkError): if networkError.code == StatusCode.OUT_OF_RANGE and networkError.details == "EOF": print("Error received and ignored: {0}".format(networkError)) print() self.streamClosed = True else: raise Exception("Unexpected NetworkError: {0}".format(networkError)) class DeliverStreamHelper(StreamHelper): def __init__(self, ordererStub, sendAck, Start, SpecifiedNumber, WindowSize, timeout = 1): StreamHelper.__init__(self, ordererStub) #Set the ack flag trueOptions = ['true', 'True','yes','Yes'] falseOptions = ['false', 'False', 'no', 'No'] assert sendAck in trueOptions + falseOptions, "sendAck of '{0}' not recognized, expected one of '{1}'".format(sendAck, trueOptions + falseOptions) self.sendAck = sendAck in trueOptions # Set the UpdateMessage and start the stream self.deliverUpdateMsg = createDeliverUpdateMsg(Start, SpecifiedNumber, WindowSize) sendGenerator = self.createSendGenerator(self.deliverUpdateMsg, timeout) replyGenerator = ordererStub.Deliver(sendGenerator, timeout + 1) self.replyGenerator = replyGenerator def seekToBlock(self, blockNum): deliverUpdateMsg = ab_pb2.DeliverUpdate() deliverUpdateMsg.CopyFrom(self.deliverUpdateMsg) deliverUpdateMsg.Seek.SpecifiedNumber = blockNum self.sendQueue.put(deliverUpdateMsg) def sendAcknowledgment(self, blockNum): deliverUpdateMsg = ab_pb2.DeliverUpdate(Acknowledgement = ab_pb2.Acknowledgement(Number = blockNum)) self.sendQueue.put(deliverUpdateMsg) def getWindowSize(self): return self.deliverUpdateMsg.Seek.WindowSize def readDeliveredMessages(self, expectedCount): 'Read the expected number of messages, being sure to supply the ACK if sendAck is True' if not self.sendAck: return self.readMessages(expectedCount) else: # This block assumes the expectedCount is a multiple of the windowSize msgsRead = [] while len(msgsRead) < expectedCount and self.streamClosed == False: numToRead = self.getWindowSize() if self.getWindowSize() < expectedCount else expectedCount msgsRead.extend(self.readMessages(numToRead)) # send the ack self.sendAcknowledgment(msgsRead[-1].Block.Number) print('SentACK!!') print('') return msgsRead class UserRegistration: def __init__(self, secretMsg, composeService): self.enrollId = secretMsg['enrollId'] self.secretMsg = secretMsg self.composeService = composeService self.tags = {} # Dictionary of composeService->atomic broadcast grpc Stub self.atomicBroadcastStubsDict = {} # composeService->StreamHelper self.abDeliversStreamHelperDict = {} def getUserName(self): return self.secretMsg['enrollId'] def connectToDeliverFunction(self, context, sendAck, start, SpecifiedNumber, WindowSize, composeService): 'Connect to the deliver function and drain messages to associated orderer queue' assert not composeService in self.abDeliversStreamHelperDict, "Already connected to deliver stream on {0}".format(composeService) streamHelper = DeliverStreamHelper(self.getABStubForComposeService(context, composeService), sendAck, start, SpecifiedNumber, WindowSize) self.abDeliversStreamHelperDict[composeService] = streamHelper return streamHelper def getDelivererStreamHelper(self, context, composeService): assert composeService in self.abDeliversStreamHelperDict, "NOT connected to deliver stream on {0}".format(composeService) return self.abDeliversStreamHelperDict[composeService] def broadcastMessages(self, context, numMsgsToBroadcast, composeService): abStub = self.getABStubForComposeService(context, composeService) replyGenerator = abStub.Broadcast(generateBroadcastMessages(int(numMsgsToBroadcast)),2) counter = 0 try: for reply in replyGenerator: counter += 1 print("{0} received reply: {1}, counter = {2}".format(self.enrollId, reply, counter)) if counter == int(numMsgsToBroadcast): break except Exception as e: print("Got error: {0}".format(e) ) print("Got error") print("Done") assert counter == int(numMsgsToBroadcast), "counter = {0}, expected {1}".format(counter, numMsgsToBroadcast) def getABStubForComposeService(self, context, composeService): 'Return a Stub for the supplied composeService, will cache' if composeService in self.atomicBroadcastStubsDict: return self.atomicBroadcastStubsDict[composeService] # Get the IP address of the server that the user registered on ipAddress = bdd_test_util.ipFromContainerNamePart(composeService, context.compose_containers) channel = getGRPCChannel(ipAddress) newABStub = ab_pb2.beta_create_AtomicBroadcast_stub(channel) self.atomicBroadcastStubsDict[composeService] = newABStub return newABStub # Registerses a user on a specific composeService def registerUser(context, secretMsg, composeService): userName = secretMsg['enrollId'] if 'ordererUsers' in context: pass else: context.ordererUsers = {} if userName in context.ordererUsers: raise Exception("Orderer user already registered: {0}".format(userName)) userRegistration = UserRegistration(secretMsg, composeService) context.ordererUsers[userName] = userRegistration return userRegistration def getUserRegistration(context, enrollId): userRegistration = None if 'ordererUsers' in context: pass else: ordererContext.ordererUsers = {} if enrollId in context.ordererUsers: userRegistration = context.ordererUsers[enrollId] else: raise Exception("Orderer user has not been registered: {0}".format(enrollId)) return userRegistration def createDeliverUpdateMsg(Start, SpecifiedNumber, WindowSize): seek = ab_pb2.SeekInfo() startVal = seek.__getattribute__(Start) seekInfo = ab_pb2.SeekInfo(Start = startVal, SpecifiedNumber = SpecifiedNumber, WindowSize = WindowSize) deliverUpdateMsg = ab_pb2.DeliverUpdate(Seek = seekInfo) return deliverUpdateMsg def generateBroadcastMessages(numToGenerate = 1, timeToHoldOpen = 1): messages = [] for i in range(0, numToGenerate): messages.append(ab_pb2.BroadcastMessage(Data = str("BDD test: {0}".format(datetime.datetime.utcnow())))) for msg in messages: yield msg time.sleep(timeToHoldOpen) def getGRPCChannel(ipAddress): channel = implementations.insecure_channel(ipAddress, 5005) print("Returning GRPC for address: {0}".format(ipAddress)) return channel
#!/usr/bin/python # coding=utf-8 from distutils.spawn import find_executable from flask import Flask, render_template, request, jsonify, redirect, Response from kvirt.config import Kconfig from kvirt.common import print_info, get_free_port from kvirt.baseconfig import Kbaseconfig from kvirt.containerconfig import Kcontainerconfig from kvirt.defaults import IMAGES, WEBSOCKIFYCERT from kvirt import nameutils import os from time import sleep from threading import Thread app = Flask(__name__) try: app.config.from_object('settings') config = app.config except ImportError: config = {'PORT': os.environ.get('PORT', 9000)} debug = config['DEBUG'] if 'DEBUG' in list(config) else True port = int(config['PORT']) if 'PORT' in list(config) else 9000 # VMS @app.route('/vmstable') def vmstable(): """ retrieves all vms in table """ config = Kconfig() k = config.k vms = [] for vm in k.list(): vm['info'] = print_info(vm, output='plain', pretty=True) vms.append(vm) return render_template('vmstable.html', vms=vms) @app.route("/") @app.route('/vms') def vms(): """ :return: """ baseconfig = Kbaseconfig() return render_template('vms.html', title='Home', client=baseconfig.client) @app.route('/vmcreate') def vmcreate(): """ create vm """ config = Kconfig() images = [os.path.basename(v) for v in config.k.volumes()] disks = [] for disk in config.disks: if isinstance(disk, int): disks.append(str(disk)) else: disks.append(str(disk['size'])) disks = ','.join(disks) nets = [] for net in config.nets: if isinstance(net, str): nets.append(net) else: nets.append(net['name']) nets = ','.join(nets) parameters = {'memory': config.memory, 'numcpus': config.numcpus, 'disks': disks, 'nets': nets} return render_template('vmcreate.html', title='CreateVm', images=images, parameters=parameters, client=config.client) @app.route('/vmprofilestable') def vmprofilestable(): """ retrieves vm profiles in table """ baseconfig = Kbaseconfig() profiles = baseconfig.list_profiles() return render_template('vmprofilestable.html', profiles=profiles) @app.route('/vmprofiles') def vmprofiles(): """ :return: """ baseconfig = Kbaseconfig() return render_template('vmprofiles.html', title='VmProfiles', client=baseconfig.client) @app.route("/diskaction", methods=['POST']) def diskaction(): """ add/delete disk to vm """ config = Kconfig() k = config.k if 'action' in request.form: action = request.form['action'] if action not in ['create', 'delete']: result = {'result': 'failure', 'reason': "Incorrect action"} response = jsonify(result) response.status_code = 400 else: if action == 'add': name = request.form['name'] size = int(request.form['size']) pool = request.form['pool'] result = k.add_disk(name, size, pool) elif action == 'delete': name = request.form['name'] diskname = request.form['disk'] result = k.delete_disk(name, diskname) response = jsonify(result) response.status_code = 200 else: failure = {'result': 'failure', 'reason': "Invalid Data"} response = jsonify(failure) response.status_code = 400 return response @app.route("/nicaction", methods=['POST']) def nicaction(): """ add/delete nic to vm """ config = Kconfig() k = config.k if 'action' in request.form: action = request.form['action'] if action not in ['create', 'delete']: result = {'result': 'failure', 'reason': "Incorrect action"} response = jsonify(result) response.status_code = 400 else: if action == 'add': name = request.form['name'] network = request.form['network'] result = k.add_nic(name, network) elif action == 'delete': name = request.form['name'] nicname = request.form['nic'] result = k.delete_nic(name, nicname) response = jsonify(result) response.status_code = 200 else: failure = {'result': 'failure', 'reason': "Invalid Data"} response = jsonify(failure) response.status_code = 400 return response # CONTAINERS @app.route('/containercreate') def containercreate(): """ create container """ baseconfig = Kbaseconfig() profiles = baseconfig.list_containerprofiles() return render_template('containercreate.html', title='CreateContainer', profiles=profiles, client=baseconfig.client) # POOLS @app.route('/poolcreate') def poolcreate(): """ pool form """ config = Kconfig() return render_template('poolcreate.html', title='CreatePool', client=config.client) @app.route("/poolaction", methods=['POST']) def poolaction(): """ create/delete pool """ config = Kconfig() k = config.k if 'pool' in request.form: pool = request.form['pool'] action = request.form['action'] if action not in ['create', 'delete']: result = {'result': 'failure', 'reason': "Incorrect action"} response = jsonify(result) response.status_code = 400 else: if action == 'create': path = request.form['path'] pooltype = request.form['type'] result = k.create_pool(name=pool, poolpath=path, pooltype=pooltype) elif action == 'delete': result = k.delete_pool(name=pool) response = jsonify(result) response.status_code = 200 else: result = {'result': 'failure', 'reason': "Invalid Data"} response = jsonify(result) response.status_code = 400 return response # REPOS @app.route("/repoaction", methods=['POST']) def repoaction(): """ create/delete repo """ config = Kconfig() if 'repo' in request.form: repo = request.form['repo'] action = request.form['action'] if action not in ['create', 'delete', 'update']: result = {'result': 'failure', 'reason': "Incorrect action"} response = jsonify(result) response.status_code = 400 else: if action == 'create': url = request.form['url'] if url == '': failure = {'result': 'failure', 'reason': "Invalid Data"} response = jsonify(failure) response.status_code = 400 else: result = config.create_repo(repo, url) elif action == 'update': result = config.update_repo(repo) elif action == 'delete': result = config.delete_repo(repo) response = jsonify(result) response.status_code = 200 else: failure = {'result': 'failure', 'reason': "Invalid Data"} response = jsonify(failure) response.status_code = 400 return response # NETWORKS @app.route('/networkcreate') def networkcreate(): """ network form """ config = Kconfig() return render_template('networkcreate.html', title='CreateNetwork', client=config.client) @app.route("/networkaction", methods=['POST']) def networkaction(): """ create/delete network """ config = Kconfig() k = config.k if 'network' in request.form: network = request.form['network'] action = request.form['action'] if action not in ['create', 'delete']: result = {'result': 'failure', 'reason': "Incorrect action"} response = jsonify(result) response.status_code = 400 else: if action == 'create': cidr = request.form['cidr'] dhcp = bool(request.form['dhcp']) isolated = bool(request.form['isolated']) nat = not isolated result = k.create_network(name=network, cidr=cidr, dhcp=dhcp, nat=nat) elif action == 'delete': result = k.delete_network(name=network) response = jsonify(result) response.status_code = 200 else: result = {'result': 'failure', 'reason': "Invalid Data"} response = jsonify(result) response.status_code = 400 return response # PLANS @app.route('/plancreate') def plancreate(): """ create plan """ config = Kconfig() return render_template('plancreate.html', title='CreatePlan', client=config.client) @app.route("/vmaction", methods=['POST']) def vmaction(): """ start/stop/delete/create vm """ config = Kconfig() k = config.k if 'name' in request.form: name = request.form['name'] action = request.form['action'] if action not in ['start', 'stop', 'delete', 'create']: result = {'result': 'failure', 'reason': "Invalid Action"} response = jsonify(result) response.status_code = 400 else: if action == 'start': result = k.start(name) elif action == 'stop': result = k.stop(name) elif action == 'delete': result = k.delete(name) elif action == 'create' and 'profile' in request.form: profile = request.form['profile'] parameters = {} for p in request.form: if p.startswith('parameters'): value = request.form[p] key = p.replace('parameters[', '').replace(']', '') parameters[key] = value parameters['nets'] = parameters['nets'].split(',') parameters['disks'] = [int(disk) for disk in parameters['disks'].split(',')] if name == '': name = nameutils.get_random_name() result = config.create_vm(name, profile, overrides=parameters) response = jsonify(result) response.status_code = 200 else: result = {'result': 'failure', 'reason': "Invalid Data"} response = jsonify(result) response.status_code = 400 return jsonify(result) # HOSTS @app.route("/hostaction", methods=['POST']) def hostaction(): """ enable/disable/default host """ baseconfig = Kbaseconfig() if 'name' in request.form: name = request.form['name'] action = request.form['action'] if action not in ['enable', 'disable', 'switch']: result = {'result': 'failure', 'reason': "Invalid Action"} response = jsonify(result) response.status_code = 400 else: if action == 'enable': result = baseconfig.enable_host(name) elif action == 'disable': result = baseconfig.disable_host(name) elif action == 'switch': result = baseconfig.switch_host(name) response = jsonify(result) response.status_code = 200 else: result = {'result': 'failure', 'reason': "Invalid Data"} response = jsonify(result) response.status_code = 400 return response @app.route("/snapshotaction", methods=['POST']) def snapshotaction(): """ create/delete/revert snapshot """ config = Kconfig() k = config.k if 'name' in request.form: name = request.form['name'] action = request.form['action'] if action not in ['list', 'revert', 'delete', 'create']: result = {'result': 'failure', 'reason': "Invalid Action"} response = jsonify(result) response.status_code = 400 else: if action == 'list': result = k.snapshot(None, name, listing=True) elif action == 'create': snapshot = request.form['snapshot'] result = k.snapshot(snapshot, name) elif action == 'delete': snapshot = request.form['snapshot'] result = k.snapshot(snapshot, name, delete=True) elif action == 'revert': snapshot = request.form['snapshot'] name = request.form['name'] result = k.snapshot(snapshot, name, revert=True) response = jsonify(result) response.status_code = 200 else: result = {'result': 'failure', 'reason': "Invalid Data"} response = jsonify(result) response.status_code = 400 return response @app.route("/planaction", methods=['POST']) def planaction(): """ start/stop/delete plan """ config = Kconfig() if 'name' in request.form: plan = request.form['name'] action = request.form['action'] if action not in ['start', 'stop', 'delete', 'create']: result = {'result': 'failure', 'reason': "Invalid Action"} response = jsonify(result) response.status_code = 400 else: if action == 'start': result = config.start_plan(plan) elif action == 'stop': result = config.stop_plan(plan) elif action == 'delete': result = config.delete_plan(plan) elif action == 'create': print(request.form) url = request.form['url'] if plan == '': plan = nameutils.get_random_name() result = config.plan(plan, url=url) response = jsonify(result) response.status_code = 200 else: result = {'result': 'failure', 'reason': "Invalid Data"} response = jsonify(result) response.status_code = 400 return response @app.route('/containerstable') def containerstable(): """ retrieves all containers in table """ config = Kconfig() cont = Kcontainerconfig(config).cont containers = cont.list_containers() return render_template('containerstable.html', containers=containers) @app.route('/containers') def containers(): """ retrieves all containers """ config = Kconfig() return render_template('containers.html', title='Containers', client=config.client) @app.route('/networkstable') def networkstable(): """ retrieves all networks in table """ config = Kconfig() k = config.k networks = k.list_networks() return render_template('networkstable.html', networks=networks) @app.route('/networks') def networks(): """ retrieves all networks """ config = Kconfig() return render_template('networks.html', title='Networks', client=config.client) @app.route('/poolstable') def poolstable(): """ retrieves all pools in table """ config = Kconfig() k = config.k pools = [] for pool in k.list_pools(): poolpath = k.get_pool_path(pool) pools.append([pool, poolpath]) return render_template('poolstable.html', pools=pools) @app.route('/pools') def pools(): """ retrieves all pools """ config = Kconfig() return render_template('pools.html', title='Pools', client=config.client) # REPOS @app.route('/repostable') def repostable(): """ retrieves all repos in table """ config = Kconfig() repos = [] repoinfo = config.list_repos() for repo in repoinfo: url = repoinfo[repo] repos.append([repo, url]) return render_template('repostable.html', repos=repos) @app.route('/repos') def repos(): """ :return: """ config = Kconfig() return render_template('repos.html', title='Repos', client=config.client) @app.route('/repocreate') def repocreate(): """ repo form """ config = Kconfig() return render_template('repocreate.html', title='CreateRepo', client=config.client) # PRODUCTS @app.route('/productstable') def productstable(): """ retrieves all products in table """ baseconfig = Kbaseconfig() products = [] for product in baseconfig.list_products(): repo = product['repo'] group = product.get('group', 'None') name = product['name'] description = product.get('description', 'N/A') numvms = product.get('numvms', 'N/A') products.append([repo, group, name, description, numvms]) return render_template('productstable.html', products=products) @app.route('/products') def products(): """ :return: """ baseconfig = Kbaseconfig() return render_template('products.html', title='Products', client=baseconfig.client) @app.route('/productcreate/<prod>') def productcreate(prod): """ product form """ config = Kbaseconfig() productinfo = config.info_product(prod, web=True) parameters = productinfo.get('parameters', {}) description = parameters.get('description', '') info = parameters.get('info', '') return render_template('productcreate.html', title='CreateProduct', client=config.client, product=prod, parameters=parameters, description=description, info=info) @app.route("/productaction", methods=['POST']) def productaction(): """ create product """ config = Kconfig() if 'product' in request.form: product = request.form['product'] action = request.form['action'] if action == 'create' and 'plan' in request.form: plan = request.form['plan'] parameters = {} for p in request.form: if p.startswith('parameters'): value = request.form[p] key = p.replace('parameters[', '').replace(']', '') parameters[key] = value if plan == '': plan = None result = config.create_product(product, plan=plan, overrides=parameters) else: result = {'result': 'failure', 'reason': "Invalid Action"} response = jsonify(result) response.status_code = 400 response = jsonify(result) response.status_code = 200 else: result = {'result': 'failure', 'reason': "Invalid Data"} response = jsonify(result) response.status_code = 400 return response # KUBE @app.route('/kubegenericcreate') def kubegenericcreate(): """ create generic kube """ config = Kconfig() parameters = config.info_kube_generic(quiet=True, web=True) _type = 'generic' return render_template('kubecreate.html', title='CreateGenericKube', client=config.client, parameters=parameters, _type=_type) @app.route('/kubeopenshiftcreate') def kubeopenshiftcreate(): """ create openshift kube """ config = Kconfig() parameters = config.info_kube_openshift(quiet=True, web=True) _type = 'openshift' return render_template('kubecreate.html', title='CreateOpenshiftKube', client=config.client, parameters=parameters, _type=_type) @app.route("/kubeaction", methods=['POST']) def kubeaction(): """ create kube """ config = Kconfig() if 'cluster' in request.form: cluster = request.form['cluster'] _type = request.form['type'] action = request.form['action'] if action == 'create': parameters = {} for p in request.form: if p.startswith('parameters'): value = request.form[p] if value == 'None': value = None elif value.isdigit(): value = int(value) elif value == 'False': value = False elif value == 'True': value = True key = p.replace('parameters[', '').replace(']', '') parameters[key] = value del parameters['cluster'] if _type == 'generic': thread = Thread(target=config.create_kube_generic, kwargs={'cluster': cluster, 'overrides': parameters}) elif _type == 'openshift': thread = Thread(target=config.create_kube_openshift, kwargs={'cluster': cluster, 'overrides': parameters}) thread.start() result = {'result': 'success'} response = jsonify(result) response.status_code = 200 else: result = {'result': 'failure', 'reason': "Invalid Action"} response = jsonify(result) response.status_code = 400 else: failure = {'result': 'failure', 'reason': "Invalid Data"} response = jsonify(failure) response.status_code = 400 return response @app.route('/hoststable') def hoststable(): """ retrieves all clients in table """ baseconfig = Kbaseconfig() clients = [] for client in sorted(baseconfig.clients): enabled = baseconfig.ini[client].get('enabled', True) _type = baseconfig.ini[client].get('type', 'kvm') if client == baseconfig.client: clients.append([client, _type, enabled, 'X']) else: clients.append([client, _type, enabled, '']) return render_template('hoststable.html', clients=clients) @app.route('/hosts') def hosts(): """ retrieves all hosts """ config = Kconfig() return render_template('hosts.html', title='Hosts', client=config.client) @app.route('/planstable') def planstable(): """ retrieves all plans in table """ config = Kconfig() return render_template('planstable.html', plans=config.list_plans()) @app.route('/plans') def plans(): """ :return: """ config = Kconfig() return render_template('plans.html', title='Plans', client=config.client) @app.route('/kubestable') def kubestable(): """ retrieves all kubes in table """ config = Kconfig() kubes = config.list_kubes() return render_template('kubestable.html', kubes=kubes) @app.route('/kubes') def kubes(): """ :return: """ config = Kconfig() return render_template('kubes.html', title='Kubes', client=config.client) @app.route("/containeraction", methods=['POST']) def containeraction(): """ start/stop/delete container """ config = Kconfig() cont = Kcontainerconfig(config).cont k = config.k if 'name' in request.form: name = request.form['name'] action = request.form['action'] if action not in ['start', 'stop', 'delete', 'create']: result = {'result': 'failure', 'reason': "Invalid Action"} response = jsonify(result) response.status_code = 400 else: if action == 'start': result = cont.start_container(name) elif action == 'stop': result = cont.stop_container(name) elif action == 'delete': result = cont.delete_container(name) elif action == 'create' and 'profile' in request.form: profile = [prof for prof in config.list_containerprofiles() if prof[0] == request.form['profile']][0] if name is None: name = nameutils.get_random_name() image, nets, ports, volumes, cmd = profile[1:] result = cont.create_container(k, name=name, image=image, nets=nets, cmds=[cmd], ports=ports, volumes=volumes) result = cont.create_container(name, profile) response = jsonify(result) response.status_code = 200 else: result = {'result': 'failure', 'reason': "Invalid Data"} response = jsonify(result) response.status_code = 400 return response @app.route('/imagestable') def imagestable(): """ retrieves images in table """ config = Kconfig() k = config.k images = k.volumes() return render_template('imagestable.html', images=images) @app.route('/images') def images(): """ :return: """ config = Kconfig() return render_template('images.html', title='Images', client=config.client) @app.route('/imagecreate') def imagecreate(): """ create image """ config = Kconfig() k = config.k pools = k.list_pools() return render_template('imagecreate.html', title='CreateImage', pools=pools, images=sorted(IMAGES), client=config.client) @app.route("/imageaction", methods=['POST']) def imageaction(): """ create/delete image """ config = Kconfig() if 'pool' in request.form: pool = request.form['pool'] action = request.form['action'] if action == 'create' and 'pool' in request.form and 'image' in request.form: pool = request.form['pool'] image = request.form['image'] url = request.form['url'] cmd = request.form['cmd'] if url == '': url = None if cmd == '': cmd = None result = config.handle_host(pool=pool, image=image, download=True, url=url, cmd=cmd) response = jsonify(result) response.status_code = 200 else: result = {'result': 'failure', 'reason': "Invalid Action"} response = jsonify(result) response.status_code = 400 else: result = {'result': 'failure', 'reason': "Invalid Data"} response = jsonify(result) response.status_code = 400 return response @app.route('/isostable') def isostable(): """ retrieves isos in table """ config = Kconfig() k = config.k isos = k.volumes(iso=True) return render_template('isostable.html', isos=isos) @app.route('/isos') def isos(): """ :return: """ config = Kconfig() return render_template('isos.html', title='Isos', client=config.client) @app.route('/containerprofilestable') def containerprofilestable(): """ retrieves container profiles in table """ baseconfig = Kbaseconfig() profiles = baseconfig.list_containerprofiles() return render_template('containerprofilestable.html', profiles=profiles) @app.route('/containerprofiles') def containerprofiles(): """ retrieves all containerprofiles """ baseconfig = Kbaseconfig() return render_template('containerprofiles.html', title='ContainerProfiles', client=baseconfig.client) @app.route('/vmconsole/<string:name>') def vmconsole(name): """ Get url for console """ config = Kconfig() k = config.k password = '' scheme = 'ws://' if find_executable('websockify') is None: return Response(status=404) consoleurl = k.console(name, tunnel=config.tunnel, web=True) if consoleurl.startswith('spice') or consoleurl.startswith('vnc'): protocol = 'spice' if consoleurl.startswith('spice') else 'vnc' websocketport = get_free_port() host, port = consoleurl.replace('%s://' % protocol, '').split(':') websocketcommand = "websockify %s -vD --idle-timeout=30 %s:%s" % (websocketport, host, port) if config.type == 'ovirt': port, password = port.split('+') if protocol == 'spice': scheme = 'ws://' cert = os.path.expanduser('~/.kcli/websockify.pem') if not os.path.exists(cert): with open(cert, 'w') as f: f.write(WEBSOCKIFYCERT) websocketcommand = "websockify %s -vD --idle-timeout=30 --cert %s --ssl-target %s:%s" % (websocketport, cert, host, port) else: websocketcommand = "websockify %s -vD --idle-timeout=30 %s:%s" % (websocketport, host, port) os.popen(websocketcommand) sleep(5) return render_template('%s.html' % protocol, title='Vm console', port=websocketport, password=password, scheme=scheme) elif consoleurl is not None: return redirect(consoleurl) else: return Response(status=404) def run(): """ """ app.run(host='0.0.0.0', port=port, debug=debug) if __name__ == '__main__': run()
# # Copyright (c) 2009-2015, Jack Poulson # All rights reserved. # # This file is part of Elemental and is under the BSD 2-Clause License, # which can be found in the LICENSE file in the root directory, or at # http://opensource.org/licenses/BSD-2-Clause # from ..core import * import ctypes lib.ElPermutationMetaSet.argtypes = [c_void_p,c_void_p,c_void_p] lib.ElPermutationMetaClear.argtypes = [c_void_p] lib.ElPermutationMetaTotalSend.argtypes = [c_void_p,POINTER(c_int)] lib.ElPermutationMetaTotalRecv.argtypes = [c_void_p,POINTER(c_int)] lib.ElPermutationMetaScaleUp.argtypes = [c_void_p,iType] lib.ElPermutationMetaScaleDown.argtypes = [c_void_p,iType] class PermutationMeta(ctypes.Structure): _fields_ = [("align",iType),("comm",mpi.Comm), ("sendCounts",POINTER(iType)),("sendDispls",POINTER(iType)), ("recvCounts",POINTER(iType)),("recvDispls",POINTER(iType)), ("numSendIdx",iType), ("numRecvIdx",iType), ("sendIdx",POINTER(iType)), ("sendRanks",POINTER(iType)), ("recvIdx",POINTER(iType)), ("recvRanks",POINTER(iType))] def __init__(self,p,pInv): if type(p) is not DistMatrix or type(pInv) is not DistMatrix: raise Exception('Types of p and pInv must be DistMatrix') if p.tag != iTag or pInv.tag != iTag: raise Exception('p and pInv must be integral') lib.ElPermutationMetaSet(p.obj,pInv.obj,pointer(self)) def Set(self,p,pInv): if type(p) is not DistMatrix or type(pInv) is not DistMatrix: raise Exception('Types of p and pInv must be DistMatrix') if p.tag != iTag or pInv.tag != iTag: raise Exception('p and pInv must be integral') lib.ElPermutationMetaSet(p.obj,pInv.obj,pointer(self)) def Clear(self,p,pInv): lib.ElPermutationMetaClear(pointer(self)) def TotalSend(self): total = c_int() lib.ElPermutationMetaTotalSend(pointer(self),pointer(total)) return total def TotalRecv(self): total = c_int() lib.ElPermutationMetaTotalRecv(pointer(self),pointer(total)) return total def ScaleUp(self,length): lib.ElPermutationMetaScaleUp(pointer(self),length) def ScaleDown(self,length): lib.ElPermutationMetaScaleDown(pointer(self),length) class Permutation(object): lib.ElPermutationCreate.argtypes = [POINTER(c_void_p)] def __init__(self): self.obj = c_void_p() lib.ElPermutationCreate(pointer(self.obj)) lib.ElPermutationDestroy.argtypes = [c_void_p] def Destroy(self): lib.ElPermutationDestroy(self.obj) lib.ElPermutationEmpty.argtypes = [c_void_p] def Empty(self): lib.ElPermutationEmpty(self.obj) lib.ElPermutationMakeIdentity.argtypes = [c_void_p,iType] def MakeIdentity(self,size): lib.ElPermutationMakeIdentity(self.obj,size) lib.ElPermutationReserveSwaps.argtypes = [c_void_p,iType] def ReserveSwaps(self,maxSwaps): lib.ElPermutationReserveSwaps(self.obj,maxSwaps) lib.ElPermutationMakeArbitrary.argtypes = [c_void_p] def MakeArbitrary(self): lib.ElPermutationMakeArbitrary(self.obj) lib.ElPermutationRowSwap.argtypes = [c_void_p,iType,iType] def RowSwap(self,origin,dest): lib.ElPermutationRowSwap(self.obj,origin,dest) lib.ElPermutationRowSwapSequence.argtypes = [c_void_p,c_void_p,iType] def RowSwapSequence(self,PAppend,offset=0): lib.ElPermutationRowSwapSequence(self.obj,PAppend.obj,offset) lib.ElPermutationSetImage.argtypes = [c_void_p,iType,iType] def SetImage(self,origin,dest): lib.ElPermutationSetImage(self.obj,origin,dest) lib.ElPermutationHeight.argtypes = [c_void_p,POINTER(iType)] def Height(self): height = iType() lib.ElPermutationHeight(self.obj,pointer(height)) return height.value lib.ElPermutationWidth.argtypes = [c_void_p,POINTER(iType)] def Width(self): width = iType() lib.ElPermutationWidth(self.obj,pointer(width)) return width.value lib.ElPermutationParity.argtypes = [c_void_p,POINTER(bType)] def Parity(self): parity = bType() lib.ElPermutationParity(self.obj,pointer(parity)) return parity.value lib.ElPermutationIsSwapSequence.argtypes = [c_void_p,POINTER(bType)] def IsSwapSequence(self): isSwap = bType() lib.ElPermutationIsSwapSequence(self.obj,pointer(isSwap)) return isSwap.value lib.ElPermutationIsImplicitSwapSequence.argtypes = [c_void_p,POINTER(bType)] def IsImplicitSwapSequence(self): isImplicit = bType() lib.ElPermutationIsImplicitSwapSequence(self.obj,pointer(isImplicit)) return isImplicit.value lib.ElPermutationPermuteCols_i.argtypes = \ lib.ElPermutationPermuteCols_s.argtypes = \ lib.ElPermutationPermuteCols_d.argtypes = \ lib.ElPermutationPermuteCols_c.argtypes = \ lib.ElPermutationPermuteCols_z.argtypes = \ [c_void_p,c_void_p,iType] def PermuteCols(A,offset=0): if type(A) is not Matrix: raise Exception('Expected A to be a Matrix') args = [self.obj,A.obj,offset] if A.tag == iTag: lib.ElPermutationPermuteCols_i(*args) elif A.tag == sTag: lib.ElPermutationPermuteCols_s(*args) elif A.tag == dTag: lib.ElPermutationPermuteCols_d(*args) elif A.tag == cTag: lib.ElPermutationPermuteCols_c(*args) elif A.tag == zTag: lib.ElPermutationPermuteCols_z(*args) else: DataExcept() lib.ElPermutationPermuteRows_i.argtypes = \ lib.ElPermutationPermuteRows_s.argtypes = \ lib.ElPermutationPermuteRows_d.argtypes = \ lib.ElPermutationPermuteRows_c.argtypes = \ lib.ElPermutationPermuteRows_z.argtypes = \ [c_void_p,c_void_p,iType] def PermuteRows(A,offset=0): if type(A) is not Matrix: raise Exception('Expected A to be a Matrix') args = [self.obj,A.obj,offset] if A.tag == iTag: lib.ElPermutationPermuteRows_i(*args) elif A.tag == sTag: lib.ElPermutationPermuteRows_s(*args) elif A.tag == dTag: lib.ElPermutationPermuteRows_d(*args) elif A.tag == cTag: lib.ElPermutationPermuteRows_c(*args) elif A.tag == zTag: lib.ElPermutationPermuteRows_z(*args) else: DataExcept() lib.ElPermutationPermuteSymmetrically_i.argtypes = \ lib.ElPermutationPermuteSymmetrically_s.argtypes = \ lib.ElPermutationPermuteSymmetrically_d.argtypes = \ [c_void_p,c_uint,c_void_p,iType] lib.ElPermutationPermuteSymmetrically_c.argtypes = \ lib.ElPermutationPermuteSymmetrically_z.argtypes = \ [c_void_p,c_uint,c_void_p,bType,iType] def PermuteSymmetrically(A,uplo=LOWER,conjugate=True,offset=0): if type(A) is not Matrix: raise Exception('Expected A to be a Matrix') args = [self.obj,uplo,A.obj,offset] argsCpx = [self.obj,uplo,A.obj,conjugate,offset] if A.tag == iTag: lib.ElPermutationPermuteSymmetrically_i(*args) elif A.tag == sTag: lib.ElPermutationPermuteSymmetrically_s(*args) elif A.tag == dTag: lib.ElPermutationPermuteSymmetrically_d(*args) elif A.tag == cTag: lib.ElPermutationPermuteSymmetrically_c(*argsCpx) elif A.tag == zTag: lib.ElPermutationPermuteSymmetrically_z(*argsCpx) else: DataExcept() lib.ElPermutationExplicitVector.argtypes = [c_void_p,c_void_p] def ExplicitVector(self): p = Matrix(iTag) lib.ElPermutationExplicitVector(self.obj,p.obj) return p lib.ElPermutationExplicitMatrix.argtypes = [c_void_p,c_void_p] def ExplicitMatrix(self): P = Matrix(iTag) lib.ElPermutationExplicitMatrix(self.obj,P.obj) return P class DistPermutation(object): lib.ElDistPermutationCreate.argtypes = [POINTER(c_void_p),c_void_p] def __init__(self,grid): self.obj = c_void_p() lib.ElDistPermutationCreate(pointer(self.obj),grid.obj) lib.ElDistPermutationDestroy.argtypes = [c_void_p] def Destroy(self): lib.ElDistPermutationDestroy(self.obj) lib.ElDistPermutationEmpty.argtypes = [c_void_p] def Empty(self): lib.ElDistPermutationEmpty(self.obj) lib.ElDistPermutationMakeIdentity.argtypes = [c_void_p,iType] def MakeIdentity(self,size): lib.ElDistPermutationMakeIdentity(self.obj,size) lib.ElDistPermutationReserveSwaps.argtypes = [c_void_p,iType] def ReserveSwaps(self,maxSwaps): lib.ElDistPermutationReserveSwaps(self.obj,maxSwaps) lib.ElDistPermutationMakeArbitrary.argtypes = [c_void_p] def MakeArbitrary(self): lib.ElDistPermutationMakeArbitrary(self.obj) lib.ElDistPermutationRowSwap.argtypes = [c_void_p,iType,iType] def RowSwap(self,origin,dest): lib.ElDistPermutationRowSwap(self.obj,origin,dest) lib.ElDistPermutationRowSwapSequence.argtypes = [c_void_p,c_void_p,iType] def RowSwapSequence(self,PAppend,offset=0): lib.ElDistPermutationRowSwapSequence(self.obj,PAppend.obj,offset) lib.ElDistPermutationSetImage.argtypes = [c_void_p,iType,iType] def SetImage(self,origin,dest): lib.ElDistPermutationSetImage(self.obj,origin,dest) lib.ElDistPermutationHeight.argtypes = [c_void_p,POINTER(iType)] def Height(self): height = iType() lib.ElDistPermutationHeight(self.obj,pointer(height)) return height.value lib.ElDistPermutationWidth.argtypes = [c_void_p,POINTER(iType)] def Width(self): width = iType() lib.ElDistPermutationWidth(self.obj,pointer(width)) return width.value lib.ElDistPermutationParity.argtypes = [c_void_p,POINTER(bType)] def Parity(self): parity = bType() lib.ElDistPermutationParity(self.obj,pointer(parity)) return parity.value lib.ElDistPermutationIsSwapSequence.argtypes = [c_void_p,POINTER(bType)] def IsSwapSequence(self): isSwap = bType() lib.ElDistPermutationIsSwapSequence(self.obj,pointer(isSwap)) return isSwap.value lib.ElDistPermutationIsImplicitSwapSequence.argtypes = \ [c_void_p,POINTER(bType)] def IsImplicitSwapSequence(self): isImplicit = bType() lib.ElDistPermutationIsImplicitSwapSequence(self.obj,pointer(isImplicit)) return isImplicit.value lib.ElDistPermutationPermuteCols_i.argtypes = \ lib.ElDistPermutationPermuteCols_s.argtypes = \ lib.ElDistPermutationPermuteCols_d.argtypes = \ lib.ElDistPermutationPermuteCols_c.argtypes = \ lib.ElDistPermutationPermuteCols_z.argtypes = \ [c_void_p,c_void_p,iType] def PermuteCols(A,offset=0): if type(A) is not DistMatrix: raise Exception('Expected A to be a DistMatrix') args = [self.obj,A.obj,offset] if A.tag == iTag: lib.ElDistPermutationPermuteCols_i(*args) elif A.tag == sTag: lib.ElDistPermutationPermuteCols_s(*args) elif A.tag == dTag: lib.ElDistPermutationPermuteCols_d(*args) elif A.tag == cTag: lib.ElDistPermutationPermuteCols_c(*args) elif A.tag == zTag: lib.ElDistPermutationPermuteCols_z(*args) else: DataExcept() lib.ElDistPermutationPermuteRows_i.argtypes = \ lib.ElDistPermutationPermuteRows_s.argtypes = \ lib.ElDistPermutationPermuteRows_d.argtypes = \ lib.ElDistPermutationPermuteRows_c.argtypes = \ lib.ElDistPermutationPermuteRows_z.argtypes = \ [c_void_p,c_void_p,iType] def PermuteRows(A,offset=0): if type(A) is not DistMatrix: raise Exception('Expected A to be a DistMatrix') args = [self.obj,A.obj,offset] if A.tag == iTag: lib.ElDistPermutationPermuteRows_i(*args) elif A.tag == sTag: lib.ElDistPermutationPermuteRows_s(*args) elif A.tag == dTag: lib.ElDistPermutationPermuteRows_d(*args) elif A.tag == cTag: lib.ElDistPermutationPermuteRows_c(*args) elif A.tag == zTag: lib.ElDistPermutationPermuteRows_z(*args) else: DataExcept() lib.ElDistPermutationPermuteSymmetrically_i.argtypes = \ lib.ElDistPermutationPermuteSymmetrically_s.argtypes = \ lib.ElDistPermutationPermuteSymmetrically_d.argtypes = \ [c_void_p,c_uint,c_void_p,iType] lib.ElDistPermutationPermuteSymmetrically_c.argtypes = \ lib.ElDistPermutationPermuteSymmetrically_z.argtypes = \ [c_void_p,c_uint,c_void_p,bType,iType] def PermuteSymmetrically(A,uplo=LOWER,conjugate=True,offset=0): if type(A) is not DistMatrix: raise Exception('Expected A to be a DistMatrix') args = [self.obj,uplo,A.obj,offset] argsCpx = [self.obj,uplo,A.obj,conjugate,offset] if A.tag == iTag: lib.ElDistPermutationPermuteSymmetrically_i(*args) elif A.tag == sTag: lib.ElDistPermutationPermuteSymmetrically_s(*args) elif A.tag == dTag: lib.ElDistPermutationPermuteSymmetrically_d(*args) elif A.tag == cTag: lib.ElDistPermutationPermuteSymmetrically_c(*argsCpx) elif A.tag == zTag: lib.ElDistPermutationPermuteSymmetrically_z(*argsCpx) else: DataExcept() lib.ElDistPermutationExplicitVector.argtypes = [c_void_p,c_void_p] def ExplicitVector(self): p = DistMatrix(iTag,VC,STAR) lib.ElDistPermutationExplicitVector(self.obj,p.obj) return p lib.ElDistPermutationExplicitMatrix.argtypes = [c_void_p,c_void_p] def ExplicitMatrix(self): P = DistMatrix(iTag,VC,STAR) lib.ElDistPermutationExplicitMatrix(self.obj,P.obj) return P
import os import numpy as np #import tensorflow as tf import random from unittest.mock import MagicMock def _print_success_message(): return print('Tests Passed') def test_folder_path(cifar10_dataset_folder_path): assert cifar10_dataset_folder_path is not None,\ 'Cifar-10 data folder not set.' assert cifar10_dataset_folder_path[-1] != '/',\ 'The "/" shouldn\'t be added to the end of the path.' assert os.path.exists(cifar10_dataset_folder_path),\ 'Path not found.' assert os.path.isdir(cifar10_dataset_folder_path),\ '{} is not a folder.'.format(os.path.basename(cifar10_dataset_folder_path)) train_files = [cifar10_dataset_folder_path + '/data_batch_' + str(batch_id) for batch_id in range(1, 6)] other_files = [cifar10_dataset_folder_path + '/batches.meta', cifar10_dataset_folder_path + '/test_batch'] missing_files = [path for path in train_files + other_files if not os.path.exists(path)] assert not missing_files,\ 'Missing files in directory: {}'.format(missing_files) print('All files found!') def test_normalize(normalize): test_shape = (np.random.choice(range(1000)), 32, 32, 3) test_numbers = np.random.choice(range(256), test_shape) normalize_out = normalize(test_numbers) assert type(normalize_out).__module__ == np.__name__,\ 'Not Numpy Object' assert normalize_out.shape == test_shape,\ 'Incorrect Shape. {} shape found'.format(normalize_out.shape) assert normalize_out.max() <= 1 and normalize_out.min() >= 0,\ 'Incorect Range. {} to {} found'.format(normalize_out.min(), normalize_out.max()) _print_success_message() def test_one_hot_encode(one_hot_encode): test_shape = np.random.choice(range(1000)) test_numbers = np.random.choice(range(10), test_shape) one_hot_out = one_hot_encode(test_numbers) assert type(one_hot_out).__module__ == np.__name__,\ 'Not Numpy Object' assert one_hot_out.shape == (test_shape, 10),\ 'Incorrect Shape. {} shape found'.format(one_hot_out.shape) n_encode_tests = 5 test_pairs = list(zip(test_numbers, one_hot_out)) test_indices = np.random.choice(len(test_numbers), n_encode_tests) labels = [test_pairs[test_i][0] for test_i in test_indices] enc_labels = np.array([test_pairs[test_i][1] for test_i in test_indices]) new_enc_labels = one_hot_encode(labels) assert np.array_equal(enc_labels, new_enc_labels),\ 'Encodings returned different results for the same numbers.\n' \ 'For the first call it returned:\n' \ '{}\n' \ 'For the second call it returned\n' \ '{}\n' \ 'Make sure you save the map of labels to encodings outside of the function.'.format(enc_labels, new_enc_labels) for one_hot in new_enc_labels: assert (one_hot==1).sum() == 1,\ 'Each one-hot-encoded value should include the number 1 exactly once.\n' \ 'Found {}\n'.format(one_hot) assert (one_hot==0).sum() == len(one_hot)-1,\ 'Each one-hot-encoded value should include zeros in all but one position.\n' \ 'Found {}\n'.format(one_hot) _print_success_message() def test_nn_image_inputs(neural_net_image_input): image_shape = (32, 32, 3) nn_inputs_out_x = neural_net_image_input(image_shape) assert nn_inputs_out_x.get_shape().as_list() == [None, image_shape[0], image_shape[1], image_shape[2]],\ 'Incorrect Image Shape. Found {} shape'.format(nn_inputs_out_x.get_shape().as_list()) assert nn_inputs_out_x.op.type == 'Placeholder',\ 'Incorrect Image Type. Found {} type'.format(nn_inputs_out_x.op.type) assert nn_inputs_out_x.name == 'x:0', \ 'Incorrect Name. Found {}'.format(nn_inputs_out_x.name) print('Image Input Tests Passed.') def test_nn_label_inputs(neural_net_label_input): n_classes = 10 nn_inputs_out_y = neural_net_label_input(n_classes) assert nn_inputs_out_y.get_shape().as_list() == [None, n_classes],\ 'Incorrect Label Shape. Found {} shape'.format(nn_inputs_out_y.get_shape().as_list()) assert nn_inputs_out_y.op.type == 'Placeholder',\ 'Incorrect Label Type. Found {} type'.format(nn_inputs_out_y.op.type) assert nn_inputs_out_y.name == 'y:0', \ 'Incorrect Name. Found {}'.format(nn_inputs_out_y.name) print('Label Input Tests Passed.') def test_nn_keep_prob_inputs(neural_net_keep_prob_input): nn_inputs_out_k = neural_net_keep_prob_input() assert nn_inputs_out_k.get_shape().ndims is None,\ 'Too many dimensions found for keep prob. Found {} dimensions. It should be a scalar (0-Dimension Tensor).'.format(nn_inputs_out_k.get_shape().ndims) assert nn_inputs_out_k.op.type == 'Placeholder',\ 'Incorrect keep prob Type. Found {} type'.format(nn_inputs_out_k.op.type) assert nn_inputs_out_k.name == 'keep_prob:0', \ 'Incorrect Name. Found {}'.format(nn_inputs_out_k.name) print('Keep Prob Tests Passed.') def test_con_pool(conv2d_maxpool): test_x = tf.placeholder(tf.float32, [None, 32, 32, 5]) test_num_outputs = 10 test_con_k = (2, 2) test_con_s = (4, 4) test_pool_k = (2, 2) test_pool_s = (2, 2) conv2d_maxpool_out = conv2d_maxpool(test_x, test_num_outputs, test_con_k, test_con_s, test_pool_k, test_pool_s) assert conv2d_maxpool_out.get_shape().as_list() == [None, 4, 4, 10],\ 'Incorrect Shape. Found {} shape'.format(conv2d_maxpool_out.get_shape().as_list()) _print_success_message() def test_flatten(flatten): test_x = tf.placeholder(tf.float32, [None, 10, 30, 6]) flat_out = flatten(test_x) assert flat_out.get_shape().as_list() == [None, 10*30*6],\ 'Incorrect Shape. Found {} shape'.format(flat_out.get_shape().as_list()) _print_success_message() def test_fully_conn(fully_conn): test_x = tf.placeholder(tf.float32, [None, 128]) test_num_outputs = 40 fc_out = fully_conn(test_x, test_num_outputs) assert fc_out.get_shape().as_list() == [None, 40],\ 'Incorrect Shape. Found {} shape'.format(fc_out.get_shape().as_list()) _print_success_message() def test_output(output): test_x = tf.placeholder(tf.float32, [None, 128]) test_num_outputs = 40 output_out = output(test_x, test_num_outputs) assert output_out.get_shape().as_list() == [None, 40],\ 'Incorrect Shape. Found {} shape'.format(output_out.get_shape().as_list()) _print_success_message() def test_conv_net(conv_net): test_x = tf.placeholder(tf.float32, [None, 32, 32, 3]) test_k = tf.placeholder(tf.float32) logits_out = conv_net(test_x, test_k) assert logits_out.get_shape().as_list() == [None, 10],\ 'Incorrect Model Output. Found {}'.format(logits_out.get_shape().as_list()) print('Neural Network Built!') def test_train_nn(train_neural_network): mock_session = tf.Session() test_x = np.random.rand(128, 32, 32, 3) test_y = np.random.rand(128, 10) test_k = np.random.rand(1) test_optimizer = tf.train.AdamOptimizer() mock_session.run = MagicMock() train_neural_network(mock_session, test_optimizer, test_k, test_x, test_y) assert mock_session.run.called, 'Session not used' _print_success_message()
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import re from libs.mock import * from runner.sensei import Sensei from runner.writeln_decorator import WritelnDecorator from runner.mockable_test_result import MockableTestResult class AboutParrots: pass class AboutLumberjacks: pass class AboutTennis: pass class AboutTheKnightsWhoSayNi: pass class AboutMrGumby: pass class AboutMessiahs: pass class AboutGiantFeet: pass class AboutTrebuchets: pass class AboutFreemasons: pass error_assertion_with_message = """Traceback (most recent call last): File "/Users/Greg/hg/python_koans/koans/about_exploding_trousers.py", line 43, in test_durability self.assertEqual("Steel","Lard", "Another fine mess you've got me into Stanley...") AssertionError: Another fine mess you've got me into Stanley...""" error_assertion_equals = """ Traceback (most recent call last): File "/Users/Greg/hg/python_koans/koans/about_exploding_trousers.py", line 49, in test_math self.assertEqual(4,99) AssertionError: 4 != 99 """ error_assertion_true = """Traceback (most recent call last): File "/Users/Greg/hg/python_koans/koans/about_armories.py", line 25, in test_weoponary self.assertTrue("Pen" > "Sword") AssertionError """ error_mess = """ Traceback (most recent call last): File "contemplate_koans.py", line 5, in <module> from runner.mountain import Mountain File "/Users/Greg/hg/python_koans/runner/mountain.py", line 7, in <module> import path_to_enlightenment File "/Users/Greg/hg/python_koans/runner/path_to_enlightenment.py", line 8, in <module> from koans import * File "/Users/Greg/hg/python_koans/koans/about_asserts.py", line 20 self.assertTrue(eoe"Pen" > "Sword", "nhnth") ^ SyntaxError: invalid syntax""" error_with_list = """Traceback (most recent call last): File "/Users/Greg/hg/python_koans/koans/about_armories.py", line 84, in test_weoponary self.assertEqual([1, 9], [1, 2]) AssertionError: Lists differ: [1, 9] != [1, 2] First differing element 1: 9 2 - [1, 9] ? ^ + [1, 2] ? ^ """ class TestSensei(unittest.TestCase): def setUp(self): self.sensei = Sensei(WritelnDecorator(Mock())) def test_that_failures_are_handled_in_the_base_class(self): with patch('runner.mockable_test_result.MockableTestResult.addFailure', Mock()): self.sensei.addFailure(Mock(), Mock()) self.assertTrue(MockableTestResult.addFailure.called) def test_that_it_successes_only_count_if_passes_are_currently_allowed(self): with patch('runner.mockable_test_result.MockableTestResult.addSuccess', Mock()): self.sensei.passesCount = Mock() self.sensei.addSuccess(Mock()) self.assertTrue(self.sensei.passesCount.called) def test_that_it_passes_on_add_successes_message(self): with patch('runner.mockable_test_result.MockableTestResult.addSuccess', Mock()): self.sensei.addSuccess(Mock()) self.assertTrue(MockableTestResult.addSuccess.called) def test_that_it_increases_the_passes_on_every_success(self): with patch('runner.mockable_test_result.MockableTestResult.addSuccess', Mock()): pass_count = self.sensei.pass_count self.sensei.addSuccess(Mock()) self.assertEqual(pass_count + 1, self.sensei.pass_count) def test_that_nothing_is_returned_as_a_first_result_if_there_are_no_failures(self): self.sensei.failures = [] self.assertEqual(None, self.sensei.firstFailure()) def test_that_nothing_is_returned_as_sorted_result_if_there_are_no_failures(self): self.sensei.failures = [] self.assertEqual(None, self.sensei.sortFailures("AboutLife")) def test_that_nothing_is_returned_as_sorted_result_if_there_are_no_relevent_failures(self): self.sensei.failures = [ (AboutTheKnightsWhoSayNi(),"File 'about_the_knights_whn_say_ni.py', line 24"), (AboutMessiahs(),"File 'about_messiahs.py', line 43"), (AboutMessiahs(),"File 'about_messiahs.py', line 844") ] self.assertEqual(None, self.sensei.sortFailures("AboutLife")) def test_that_nothing_is_returned_as_sorted_result_if_there_are_3_shuffled_results(self): self.sensei.failures = [ (AboutTennis(),"File 'about_tennis.py', line 299"), (AboutTheKnightsWhoSayNi(),"File 'about_the_knights_whn_say_ni.py', line 24"), (AboutTennis(),"File 'about_tennis.py', line 30"), (AboutMessiahs(),"File 'about_messiahs.py', line 43"), (AboutTennis(),"File 'about_tennis.py', line 2"), (AboutMrGumby(),"File 'about_mr_gumby.py', line odd"), (AboutMessiahs(),"File 'about_messiahs.py', line 844") ] expected = [ (AboutTennis(),"File 'about_tennis.py', line 2"), (AboutTennis(),"File 'about_tennis.py', line 30"), (AboutTennis(),"File 'about_tennis.py', line 299") ] results = self.sensei.sortFailures("AboutTennis") self.assertEqual(3, len(results)) self.assertEqual(2, results[0][0]) self.assertEqual(30, results[1][0]) self.assertEqual(299, results[2][0]) def test_that_it_will_choose_not_find_anything_with_non_standard_error_trace_string(self): self.sensei.failures = [ (AboutMrGumby(),"File 'about_mr_gumby.py', line MISSING"), ] self.assertEqual(None, self.sensei.sortFailures("AboutMrGumby")) def test_that_it_will_choose_correct_first_result_with_lines_9_and_27(self): self.sensei.failures = [ (AboutTrebuchets(),"File 'about_trebuchets.py', line 27"), (AboutTrebuchets(),"File 'about_trebuchets.py', line 9"), (AboutTrebuchets(),"File 'about_trebuchets.py', line 73v") ] self.assertEqual("File 'about_trebuchets.py', line 9", self.sensei.firstFailure()[1]) def test_that_it_will_choose_correct_first_result_with_multiline_test_classes(self): self.sensei.failures = [ (AboutGiantFeet(),"File 'about_giant_feet.py', line 999"), (AboutGiantFeet(),"File 'about_giant_feet.py', line 44"), (AboutFreemasons(),"File 'about_freemasons.py', line 1"), (AboutFreemasons(),"File 'about_freemasons.py', line 11") ] self.assertEqual("File 'about_giant_feet.py', line 44", self.sensei.firstFailure()[1]) def test_that_error_report_features_the_assertion_error(self): self.sensei.scrapeAssertionError = Mock() self.sensei.firstFailure = Mock() self.sensei.firstFailure.return_value = (Mock(), "FAILED") self.sensei.errorReport() self.assertTrue(self.sensei.scrapeAssertionError.called) def test_that_error_report_features_a_stack_dump(self): self.sensei.scrapeInterestingStackDump = Mock() self.sensei.firstFailure = Mock() self.sensei.firstFailure.return_value = (Mock(), "FAILED") self.sensei.errorReport() self.assertTrue(self.sensei.scrapeInterestingStackDump.called) def test_that_scraping_the_assertion_error_with_nothing_gives_you_a_blank_back(self): self.assertEqual("", self.sensei.scrapeAssertionError(None)) def test_that_scraping_the_assertion_error_with_messaged_assert(self): self.assertEqual(" AssertionError: Another fine mess you've got me into Stanley...", self.sensei.scrapeAssertionError(error_assertion_with_message)) def test_that_scraping_the_assertion_error_with_assert_equals(self): self.assertEqual(" AssertionError: 4 != 99", self.sensei.scrapeAssertionError(error_assertion_equals)) def test_that_scraping_the_assertion_error_with_assert_true(self): self.assertEqual(" AssertionError", self.sensei.scrapeAssertionError(error_assertion_true)) def test_that_scraping_the_assertion_error_with_syntax_error(self): self.assertEqual(" SyntaxError: invalid syntax", self.sensei.scrapeAssertionError(error_mess)) def test_that_scraping_the_assertion_error_with_list_error(self): self.assertEqual(""" AssertionError: Lists differ: [1, 9] != [1, 2] First differing element 1: 9 2 - [1, 9] ? ^ + [1, 2] ? ^""", self.sensei.scrapeAssertionError(error_with_list)) def test_that_scraping_a_non_existent_stack_dump_gives_you_nothing(self): self.assertEqual("", self.sensei.scrapeInterestingStackDump(None)) def test_that_if_there_are_no_failures_say_the_final_zenlike_remark(self): self.sensei.failures = None words = self.sensei.say_something_zenlike() m = re.search("Spanish Inquisition", words) self.assertTrue(m and m.group(0)) def test_that_if_there_are_0_successes_it_will_say_the_first_zen_of_python_koans(self): self.sensei.pass_count = 0 self.sensei.failures = Mock() words = self.sensei.say_something_zenlike() m = re.search("Beautiful is better than ugly", words) self.assertTrue(m and m.group(0)) def test_that_if_there_is_1_success_it_will_say_the_second_zen_of_python_koans(self): self.sensei.pass_count = 1 self.sensei.failures = Mock() words = self.sensei.say_something_zenlike() m = re.search("Explicit is better than implicit", words) self.assertTrue(m and m.group(0)) def test_that_if_there_are_10_successes_it_will_say_the_sixth_zen_of_python_koans(self): self.sensei.pass_count = 10 self.sensei.failures = Mock() words = self.sensei.say_something_zenlike() m = re.search("Sparse is better than dense", words) self.assertTrue(m and m.group(0)) def test_that_if_there_are_36_successes_it_will_say_the_final_zen_of_python_koans(self): self.sensei.failures = Mock() self.sensei.pass_count = 36 words = self.sensei.say_something_zenlike() m = re.search("Namespaces are one honking great idea", words) self.assertTrue(m and m.group(0)) def test_that_if_there_are_37_successes_it_will_say_the_first_zen_of_python_koans_again(self): self.sensei.pass_count = 37 self.sensei.failures = Mock() words = self.sensei.say_something_zenlike() m = re.search("Beautiful is better than ugly", words) self.assertTrue(m and m.group(0)) def test_that_total_lessons_return_7_if_there_are_7_lessons(self): self.sensei.filter_all_lessons = Mock() self.sensei.filter_all_lessons.return_value = [1,2,3,4,5,6,7] self.assertEqual(7, self.sensei.total_lessons()) def test_that_total_lessons_return_0_if_all_lessons_is_none(self): self.sensei.filter_all_lessons = Mock() self.sensei.filter_all_lessons.return_value = None self.assertEqual(0, self.sensei.total_lessons()) def test_total_koans_return_43_if_there_are_43_test_cases(self): self.sensei.tests.countTestCases = Mock() self.sensei.tests.countTestCases.return_value = 43 self.assertEqual(43, self.sensei.total_koans()) def test_filter_all_lessons_will_discover_test_classes_if_none_have_been_discovered_yet(self): self.sensei.all_lessons = 0 self.assertTrue(len(self.sensei.filter_all_lessons()) > 10) self.assertTrue(len(self.sensei.all_lessons) > 10)
# 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. # ============================================================================== """Updates generated docs from Python doc comments.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import os.path import sys import tensorflow as tf from tensorflow.contrib import ffmpeg from tensorflow.python.client import client_lib from tensorflow.python.framework import constant_op from tensorflow.python.framework import docs from tensorflow.python.framework import framework_lib tf.flags.DEFINE_string("out_dir", None, "Directory to which docs should be written.") tf.flags.DEFINE_boolean("print_hidden_regex", False, "Dump a regular expression matching any hidden symbol") FLAGS = tf.flags.FLAGS PREFIX_TEXT = """ Note: Functions taking `Tensor` arguments can also take anything accepted by [`tf.convert_to_tensor`](framework.md#convert_to_tensor). """ def module_names(): return [ "tf", "tf.errors", "tf.image", "tf.nn", "tf.nn.rnn_cell", "tf.train", "tf.python_io", "tf.summary", "tf.test", "tf.contrib.bayesflow.entropy", "tf.contrib.bayesflow.monte_carlo", "tf.contrib.bayesflow.stochastic_graph", "tf.contrib.bayesflow.stochastic_tensor", "tf.contrib.bayesflow.variational_inference", "tf.contrib.copy_graph", "tf.contrib.crf", "tf.contrib.distributions", "tf.contrib.distributions.bijector", "tf.contrib.ffmpeg", "tf.contrib.framework", "tf.contrib.graph_editor", "tf.contrib.integrate", "tf.contrib.layers", "tf.contrib.learn", "tf.contrib.learn.monitors", "tf.contrib.linalg", "tf.contrib.losses", "tf.contrib.metrics", "tf.contrib.rnn", "tf.contrib.solvers", "tf.contrib.training", "tf.contrib.util", ] def find_module(base_module, name): if name == "tf": return base_module # Special case for ffmpeg is needed since it's not linked in by default due # to size concerns. elif name == "tf.contrib.ffmpeg": return ffmpeg elif name.startswith("tf."): subname = name[3:] subnames = subname.split(".") parent_module = base_module for s in subnames: if not hasattr(parent_module, s): raise ValueError( "Module not found: {}. Submodule {} not found in parent module {}." " Possible candidates are {}".format( name, s, parent_module.__name__, dir(parent_module))) parent_module = getattr(parent_module, s) return parent_module else: raise ValueError( "Invalid module name: {}. Module names must start with 'tf.'".format( name)) def get_module_to_name(names): return collections.OrderedDict([(find_module(tf, x), x) for x in names]) def all_libraries(module_to_name, members, documented): """Make a list of the individual files that we want to create. Args: module_to_name: Dictionary mapping modules to short names. members: Dictionary mapping member name to (fullname, member). documented: Set of documented names to update. Returns: List of (filename, docs.Library) pairs. """ def library(name, title, module=None, **args): if module is None: module = sys.modules["tensorflow.python.ops." + name] return (name + ".md", docs.Library(title=title, module_to_name=module_to_name, members=members, documented=documented, module=module, **args)) return collections.OrderedDict([ # Splits of module 'tf'. library("framework", "Building Graphs", framework_lib), library("check_ops", "Asserts and boolean checks."), library("constant_op", "Constants, Sequences, and Random Values", constant_op, prefix=PREFIX_TEXT), library("state_ops", "Variables", exclude_symbols=["create_partitioned_variables"], prefix=PREFIX_TEXT), library("array_ops", "Tensor Transformations", exclude_symbols=["list_diff"], prefix=PREFIX_TEXT), library("math_ops", "Math", exclude_symbols=["sparse_matmul", "arg_min", "arg_max", "lin_space", "sparse_segment_mean_grad"], prefix=PREFIX_TEXT), library("string_ops", "Strings", prefix=PREFIX_TEXT), library("histogram_ops", "Histograms"), library("control_flow_ops", "Control Flow", prefix=PREFIX_TEXT), library("functional_ops", "Higher Order Functions", prefix=PREFIX_TEXT), library("tensor_array_ops", "TensorArray Operations", prefix=PREFIX_TEXT), library("session_ops", "Tensor Handle Operations", prefix=PREFIX_TEXT), library("image", "Images", tf.image, exclude_symbols=["ResizeMethod"], prefix=PREFIX_TEXT), library("sparse_ops", "Sparse Tensors", exclude_symbols=["serialize_sparse", "serialize_many_sparse", "deserialize_many_sparse"], prefix=PREFIX_TEXT), library("io_ops", "Inputs and Readers", exclude_symbols=["LookupTableBase", "HashTable", "initialize_all_tables", "parse_single_sequence_example", "string_to_hash_bucket"], prefix=PREFIX_TEXT), library("python_io", "Data IO (Python functions)", tf.python_io), library("nn", "Neural Network", tf.nn, exclude_symbols=["conv2d_backprop_input", "conv2d_backprop_filter", "avg_pool_grad", "max_pool_grad", "max_pool_grad_with_argmax", "batch_norm_with_global_normalization_grad", "lrn_grad", "relu6_grad", "softplus_grad", "softsign_grad", "xw_plus_b", "relu_layer", "lrn", "batch_norm_with_global_normalization", "batch_norm_with_global_normalization_grad", "all_candidate_sampler", "seq2seq"], prefix=PREFIX_TEXT), library("rnn_cell", "Neural Network RNN Cells", tf.nn.rnn_cell), library("client", "Running Graphs", client_lib), library("train", "Training", tf.train, exclude_symbols=["Feature", "Features", "BytesList", "FloatList", "Int64List", "Example", "InferenceExample", "FeatureList", "FeatureLists", "RankingExample", "SequenceExample"]), library("script_ops", "Wraps python functions", prefix=PREFIX_TEXT), library("summary", "Summary Operations", tf.summary), library("test", "Testing", tf.test), library("contrib.bayesflow.entropy", "BayesFlow Entropy (contrib)", tf.contrib.bayesflow.entropy), library("contrib.bayesflow.monte_carlo", "BayesFlow Monte Carlo (contrib)", tf.contrib.bayesflow.monte_carlo), library("contrib.bayesflow.stochastic_graph", "BayesFlow Stochastic Graph (contrib)", tf.contrib.bayesflow.stochastic_graph), library("contrib.bayesflow.stochastic_tensor", "BayesFlow Stochastic Tensors (contrib)", tf.contrib.bayesflow.stochastic_tensor), library("contrib.bayesflow.variational_inference", "BayesFlow Variational Inference (contrib)", tf.contrib.bayesflow.variational_inference), library("contrib.crf", "CRF (contrib)", tf.contrib.crf), library("contrib.distributions", "Statistical Distributions (contrib)", tf.contrib.distributions), library("contrib.distributions.bijector", "Random variable transformations (contrib)", tf.contrib.distributions.bijector), library("contrib.ffmpeg", "FFmpeg (contrib)", ffmpeg), library("contrib.framework", "Framework (contrib)", tf.contrib.framework), library("contrib.graph_editor", "Graph Editor (contrib)", tf.contrib.graph_editor), library("contrib.integrate", "Integrate (contrib)", tf.contrib.integrate), library("contrib.layers", "Layers (contrib)", tf.contrib.layers), library("contrib.learn", "Learn (contrib)", tf.contrib.learn), library("contrib.learn.monitors", "Monitors (contrib)", tf.contrib.learn.monitors), library("contrib.linalg", "Linear Algebra (contrib)", tf.contrib.linalg), library("contrib.losses", "Losses (contrib)", tf.contrib.losses), library("contrib.rnn", "RNN (contrib)", tf.contrib.rnn), library("contrib.metrics", "Metrics (contrib)", tf.contrib.metrics), library("contrib.training", "Training (contrib)", tf.contrib.training), library("contrib.util", "Utilities (contrib)", tf.contrib.util), library("contrib.copy_graph", "Copying Graph Elements (contrib)", tf.contrib.copy_graph), ]) _hidden_symbols = ["Event", "LogMessage", "Summary", "SessionLog", "xrange", "HistogramProto", "ConfigProto", "NodeDef", "GraphDef", "GPUOptions", "GraphOptions", "RunOptions", "RunMetadata", "SessionInterface", "BaseSession", "NameAttrList", "AttrValue", "OptimizerOptions", "CollectionDef", "MetaGraphDef", "QueueRunnerDef", "SaverDef", "VariableDef", "TestCase", "GrpcServer", "ClusterDef", "JobDef", "ServerDef"] # TODO(skleinfeld, deannarubin) Address shortname # conflict between tf.contrib.learn.NanLossDuringTrainingError and # tf.contrib.learn.monitors.NanLossDuringTrainingError, arising due # to imports in learn/python/learn/__init__.py # TODO(wicke): Remove contrib.layers.relu* after shortnames are # disabled. These conflict with tf.nn.relu* EXCLUDE = frozenset(["tf.contrib.learn.monitors.NanLossDuringTrainingError", "tf.contrib.layers.relu", "tf.contrib.layers.relu6", "tf.contrib.framework.assert_global_step", "tf.contrib.framework.get_global_step", "tf.contrib.learn.NanLossDuringTrainingError", "tf.contrib.layers.stack"]) def main(unused_argv): if not FLAGS.out_dir: tf.logging.error("out_dir not specified") return -1 # Document libraries documented = set() module_to_name = get_module_to_name(module_names()) members = docs.collect_members(module_to_name, exclude=EXCLUDE) libraries = all_libraries(module_to_name, members, documented).items() # Define catch_all library before calling write_libraries to avoid complaining # about generically hidden symbols. catch_all = docs.Library(title="Catch All", module=None, exclude_symbols=_hidden_symbols, module_to_name=module_to_name, members=members, documented=documented) # Write docs to files docs.write_libraries(FLAGS.out_dir, libraries) # Make it easy to search for hidden symbols if FLAGS.print_hidden_regex: hidden = set(_hidden_symbols) for _, lib in libraries: hidden.update(lib.exclude_symbols) print(r"hidden symbols regex = r'\b(%s)\b'" % "|".join(sorted(hidden))) # Verify that all symbols are mentioned in some library doc. catch_all.assert_no_leftovers() # Generate index with open(os.path.join(FLAGS.out_dir, "index.md"), "w") as f: docs.Index(module_to_name, members, libraries, "../../api_docs/python/").write_markdown_to_file(f) if __name__ == "__main__": tf.app.run()
# pylint:disable=isinstance-second-argument-not-valid-type import weakref from typing import Set, Optional, Any, Tuple, Union, TYPE_CHECKING from collections import defaultdict import logging import claripy import ailment import pyvex from ... import sim_options from ...storage.memory_mixins import LabeledMemory from ...errors import SimMemoryMissingError from ...code_location import CodeLocation # pylint:disable=unused-import from .. import register_analysis from ..analysis import Analysis from ..forward_analysis import ForwardAnalysis, FunctionGraphVisitor, SingleNodeGraphVisitor from .engine_vex import SimEnginePropagatorVEX from .engine_ail import SimEnginePropagatorAIL from .prop_value import PropValue if TYPE_CHECKING: from angr.storage import SimMemoryObject _l = logging.getLogger(name=__name__) class PropagatorState: """ Describes the base state used in Propagator. """ __slots__ = ('arch', 'gpr_size', '_prop_count', '_only_consts', '_replacements', '_equivalence', 'project', '_store_tops', '__weakref__', ) _tops = {} def __init__(self, arch, project=None, replacements=None, only_consts=False, prop_count=None, equivalence=None, store_tops=True): self.arch = arch self.gpr_size = arch.bits // arch.byte_width # size of the general-purpose registers # propagation count of each expression self._prop_count = defaultdict(int) if prop_count is None else prop_count self._only_consts = only_consts self._replacements = defaultdict(dict) if replacements is None else replacements self._equivalence: Set[Equivalence] = equivalence if equivalence is not None else set() self._store_tops = store_tops self.project = project def __repr__(self): return "<PropagatorState>" def _get_weakref(self): return weakref.proxy(self) @staticmethod def _mo_cmp(mo_self: 'SimMemoryObject', mo_other: 'SimMemoryObject', addr: int, size: int): # pylint:disable=unused-argument # comparing bytes from two sets of memory objects # we don't need to resort to byte-level comparison. object-level is good enough. if mo_self.object.symbolic or mo_other.object.symbolic: return mo_self.object is mo_other.object return None @staticmethod def top(bits: int) -> claripy.ast.Base: """ Get a TOP value. :param size: Width of the TOP value (in bits). :return: The TOP value. """ if bits in PropagatorState._tops: return PropagatorState._tops[bits] r = claripy.BVS("TOP", bits, explicit_name=True) PropagatorState._tops[bits] = r return r @staticmethod def is_top(expr) -> bool: """ Check if the given expression is a TOP value. :param expr: The given expression. :return: True if the expression is TOP, False otherwise. """ if isinstance(expr, claripy.ast.Base): if expr.op == "BVS" and expr.args[0] == "TOP": return True if "TOP" in expr.variables: return True return False def copy(self) -> 'PropagatorState': raise NotImplementedError() def merge(self, *others): state = self.copy() merge_occurred = False for o in others: for loc, vars_ in o._replacements.items(): if loc not in state._replacements: state._replacements[loc] = vars_.copy() merge_occurred = True else: for var, repl in vars_.items(): if var not in state._replacements[loc]: state._replacements[loc][var] = repl merge_occurred = True else: if self.is_top(repl) or self.is_top(state._replacements[loc][var]): t = self.top(repl.bits if isinstance(repl, ailment.Expression) else repl.size()) state._replacements[loc][var] = t merge_occurred = True elif state._replacements[loc][var] != repl: t = self.top(repl.bits if isinstance(repl, ailment.Expression) else repl.size()) state._replacements[loc][var] = t merge_occurred = True if state._equivalence != o._equivalence: merge_occurred = True state._equivalence |= o._equivalence return state, merge_occurred def add_replacement(self, codeloc, old, new): """ Add a replacement record: Replacing expression `old` with `new` at program location `codeloc`. If the self._only_consts flag is set to true, only constant values will be set. :param CodeLocation codeloc: The code location. :param old: The expression to be replaced. :param new: The expression to replace with. :return: None """ if self.is_top(new): return if self._only_consts: if isinstance(new, int) or self.is_top(new): self._replacements[codeloc][old] = new else: self._replacements[codeloc][old] = new def filter_replacements(self): pass # VEX state class PropagatorVEXState(PropagatorState): """ Describes the state used in the VEX engine of Propagator. """ __slots__ = ('_registers', '_stack_variables', 'do_binops', ) def __init__(self, arch, project=None, registers=None, local_variables=None, replacements=None, only_consts=False, prop_count=None, do_binops=True, store_tops=True): super().__init__(arch, project=project, replacements=replacements, only_consts=only_consts, prop_count=prop_count, store_tops=store_tops) self.do_binops = do_binops self._registers = LabeledMemory( memory_id='reg', top_func=self.top, page_kwargs={'mo_cmp': self._mo_cmp}) \ if registers is None else registers self._stack_variables = LabeledMemory( memory_id='mem', top_func=self.top, page_kwargs={'mo_cmp': self._mo_cmp}) \ if local_variables is None else local_variables self._registers.set_state(self) self._stack_variables.set_state(self) def __repr__(self): return "<PropagatorVEXState>" def copy(self) -> 'PropagatorVEXState': cp = PropagatorVEXState( self.arch, project=self.project, registers=self._registers.copy(), local_variables=self._stack_variables.copy(), replacements=self._replacements.copy(), prop_count=self._prop_count.copy(), only_consts=self._only_consts, do_binops=self.do_binops, store_tops=self._store_tops, ) return cp def merge(self, *others: 'PropagatorVEXState') -> Tuple['PropagatorVEXState',bool]: state = self.copy() merge_occurred = state._registers.merge([o._registers for o in others], None) merge_occurred |= state._stack_variables.merge([o._stack_variables for o in others], None) return state, merge_occurred def store_local_variable(self, offset, size, value, endness): # pylint:disable=unused-argument # TODO: Handle size self._stack_variables.store(offset, value, size=size, endness=endness) def load_local_variable(self, offset, size, endness): # pylint:disable=unused-argument # TODO: Handle size try: return self._stack_variables.load(offset, size=size, endness=endness) except SimMemoryMissingError: return self.top(size * self.arch.byte_width) def store_register(self, offset, size, value): self._registers.store(offset, value, size=size) def load_register(self, offset, size): # TODO: Fix me if size != self.gpr_size: return self.top(size * self.arch.byte_width) try: return self._registers.load(offset, size=size) except SimMemoryMissingError: return self.top(size * self.arch.byte_width) # AIL state class Equivalence: """ Describes an equivalence relationship between two atoms. """ __slots__ = ('codeloc', 'atom0', 'atom1',) def __init__(self, codeloc, atom0, atom1): self.codeloc = codeloc self.atom0 = atom0 self.atom1 = atom1 def __repr__(self): return "<Eq@%r: %r==%r>" % (self.codeloc, self.atom0, self.atom1) def __eq__(self, other): return type(other) is Equivalence \ and other.codeloc == self.codeloc \ and other.atom0 == self.atom0 \ and other.atom1 == self.atom1 def __hash__(self): return hash((Equivalence, self.codeloc, self.atom0, self.atom1)) class PropagatorAILState(PropagatorState): """ Describes the state used in the AIL engine of Propagator. """ __slots__ = ('_registers', '_stack_variables', '_tmps', '_inside_call_stmt', 'last_store') def __init__(self, arch, project=None, replacements=None, only_consts=False, prop_count=None, equivalence=None, stack_variables=None, registers=None): super().__init__(arch, project=project, replacements=replacements, only_consts=only_consts, prop_count=prop_count, equivalence=equivalence) self._stack_variables = LabeledMemory(memory_id='mem', top_func=self.top, page_kwargs={'mo_cmp': self._mo_cmp}) \ if stack_variables is None else stack_variables self._registers = LabeledMemory(memory_id='reg', top_func=self.top, page_kwargs={'mo_cmp': self._mo_cmp}) \ if registers is None else registers self._tmps = {} self._inside_call_stmt = False # temporary variable that is only used internally self._registers.set_state(self) self._stack_variables.set_state(self) self.last_store = None def __repr__(self): return "<PropagatorAILState>" def copy(self): rd = PropagatorAILState( self.arch, project=self.project, replacements=self._replacements.copy(), prop_count=self._prop_count.copy(), only_consts=self._only_consts, equivalence=self._equivalence.copy(), stack_variables=self._stack_variables.copy(), registers=self._registers.copy(), # drop tmps ) return rd def merge(self, *others) -> Tuple['PropagatorAILState',bool]: state, merge_occurred = super().merge(*others) state: 'PropagatorAILState' merge_occurred |= state._registers.merge([o._registers for o in others], None) merge_occurred |= state._stack_variables.merge([o._stack_variables for o in others], None) return state, merge_occurred def store_temp(self, tmp_idx: int, value: PropValue): self._tmps[tmp_idx] = value def load_tmp(self, tmp_idx: int) -> Optional[PropValue]: return self._tmps.get(tmp_idx, None) def store_register(self, reg: ailment.Expr.Register, value: PropValue) -> None: if isinstance(value, ailment.Expr.Expression) and value.has_atom(reg, identity=False): return for offset, chopped_value, size, label in value.value_and_labels(): self._registers.store(reg.reg_offset + offset, chopped_value, size=size, label=label) def store_stack_variable(self, sp_offset: int, new: PropValue, endness=None) -> None: # pylint:disable=unused-argument # normalize sp_offset to handle negative offsets sp_offset += 0x65536 sp_offset &= (1 << self.arch.bits) - 1 for offset, value, size, label in new.value_and_labels(): self._stack_variables.store(sp_offset + offset, value, size=size, endness=endness, label=label) def load_register(self, reg: ailment.Expr.Register) -> Optional[PropValue]: try: value, labels = self._registers.load_with_labels(reg.reg_offset, size=reg.size) except SimMemoryMissingError: # value does not exist return None prop_value = PropValue.from_value_and_labels(value, labels) return prop_value def load_stack_variable(self, sp_offset: int, size, endness=None) -> Optional[PropValue]: # normalize sp_offset to handle negative offsets sp_offset += 0x65536 sp_offset &= (1 << self.arch.bits) - 1 try: value, labels = self._stack_variables.load_with_labels(sp_offset, size=size, endness=endness) except SimMemoryMissingError as ex: # the stack variable does not exist - however, maybe some portion of it exists! if ex.missing_addr > sp_offset: # some data exist. load again try: value, labels = self._stack_variables.load_with_labels(sp_offset, size=ex.missing_addr - sp_offset, endness=endness) # then we zero-extend both the value and labels if value is not None and len(labels) == 1 and labels[0][0] == 0: value = claripy.ZeroExt(ex.missing_size * self.arch.byte_width, value) offset, offset_in_expr, size, label = labels[0] labels = ((offset, offset_in_expr, size + ex.missing_size, label),) except SimMemoryMissingError: # failed again... welp return None else: return None prop_value = PropValue.from_value_and_labels(value, labels) return prop_value def add_replacement(self, codeloc, old, new): # do not replace anything with a call expression if isinstance(new, ailment.statement.Call): return else: from .call_expr_finder import CallExprFinder # pylint:disable=import-outside-toplevel callexpr_finder = CallExprFinder() callexpr_finder.walk_expression(new) if callexpr_finder.has_call: return if self.is_top(new): # eliminate the past propagation of this expression if codeloc in self._replacements and old in self._replacements[codeloc]: self._replacements[codeloc][old] = self.top(1) # placeholder return prop_count = 0 if not isinstance(old, ailment.Expr.Tmp) and isinstance(new, ailment.Expr.Expression) \ and not isinstance(new, ailment.Expr.Const): self._prop_count[new] += 1 prop_count = self._prop_count[new] if prop_count <= 1 or isinstance(new, ailment.Expr.StackBaseOffset) or ( isinstance(old, ailment.Expr.Register) and self.arch.is_artificial_register(old.reg_offset, old.size)): # we can propagate this expression super().add_replacement(codeloc, old, new) else: # eliminate the past propagation of this expression for codeloc_ in self._replacements: if old in self._replacements[codeloc_]: self._replacements[codeloc_][old] = self.top(1) def filter_replacements(self): to_remove = set() for old, new in self._replacements.items(): if isinstance(new, ailment.Expr.Expression) and not isinstance(new, ailment.Expr.Const): if self._prop_count[new] > 1: # do not propagate this expression to_remove.add(old) for old in to_remove: del self._replacements[old] def add_equivalence(self, codeloc, old, new): eq = Equivalence(codeloc, old, new) self._equivalence.add(eq) class PropagatorAnalysis(ForwardAnalysis, Analysis): # pylint:disable=abstract-method """ PropagatorAnalysis propagates values (either constant values or variables) and expressions inside a block or across a function. PropagatorAnalysis supports both VEX and AIL. The VEX propagator only performs constant propagation. The AIL propagator performs both constant propagation and copy propagation of depth-N expressions. PropagatorAnalysis performs certain arithmetic operations between constants, including but are not limited to: - addition - subtraction - multiplication - division - xor It also performs the following memory operations: - Loading values from a known address - Writing values to a stack variable """ def __init__(self, func=None, block=None, func_graph=None, base_state=None, max_iterations=3, load_callback=None, stack_pointer_tracker=None, only_consts=False, completed_funcs=None, do_binops=True, store_tops=True, vex_cross_insn_opt=False): if func is not None: if block is not None: raise ValueError('You cannot specify both "func" and "block".') # traversing a function graph_visitor = FunctionGraphVisitor(func, func_graph) elif block is not None: # traversing a block graph_visitor = SingleNodeGraphVisitor(block) else: raise ValueError('Unsupported analysis target.') ForwardAnalysis.__init__(self, order_jobs=True, allow_merging=True, allow_widening=False, graph_visitor=graph_visitor) self._base_state = base_state self._function = func self._max_iterations = max_iterations self._load_callback = load_callback self._stack_pointer_tracker = stack_pointer_tracker # only used when analyzing AIL functions self._only_consts = only_consts self._completed_funcs = completed_funcs self._do_binops = do_binops self._store_tops = store_tops self._vex_cross_insn_opt = vex_cross_insn_opt self._node_iterations = defaultdict(int) self._states = {} self.replacements: Optional[defaultdict] = None self.equivalence: Set[Equivalence] = set() self._engine_vex = SimEnginePropagatorVEX(project=self.project, arch=self.project.arch) self._engine_ail = SimEnginePropagatorAIL( arch=self.project.arch, stack_pointer_tracker=self._stack_pointer_tracker, # We only propagate tmps within the same block. This is because the lifetime of tmps is one block only. propagate_tmps=block is not None, ) # optimization: skip state copying for the initial state self._initial_state = None self._analyze() # # Main analysis routines # def _node_key(self, node: Union[ailment.Block,pyvex.IRSB]) -> Any: if type(node) is ailment.Block: return node.addr, node.idx elif type(node) is pyvex.IRSB: return node.addr # fallback return node def _pre_analysis(self): pass def _pre_job_handling(self, job): pass def _initial_abstract_state(self, node): if isinstance(node, ailment.Block): # AIL state = PropagatorAILState(self.project.arch, project=self.project, only_consts=self._only_consts) ail = True else: # VEX state = PropagatorVEXState(self.project.arch, project=self.project, only_consts=self._only_consts, do_binops=self._do_binops, store_tops=self._store_tops) spoffset_var = self._engine_vex.sp_offset(0) ail = False state.store_register(self.project.arch.sp_offset, self.project.arch.bytes, spoffset_var, ) if self.project.arch.name == "MIPS64": if self._function is not None: if ail: state.store_register(ailment.Expr.Register(None, None, self.project.arch.registers['t9'][0], self.project.arch.registers['t9'][0]), PropValue(claripy.BVV(self._function.addr, 64)), ) else: state.store_register(self.project.arch.registers['t9'][0], # pylint:disable=too-many-function-args self.project.arch.registers['t9'][1], claripy.BVV(self._function.addr, 64), ) self._initial_state = state return state def _merge_states(self, node, *states: PropagatorState): merged_state, merge_occurred = states[0].merge(*states[1:]) return merged_state, not merge_occurred def _run_on_node(self, node, state): if isinstance(node, ailment.Block): block = node block_key = (node.addr, node.idx) engine = self._engine_ail else: block = self.project.factory.block(node.addr, node.size, opt_level=1, cross_insn_opt=self._vex_cross_insn_opt) block_key = node.addr engine = self._engine_vex if block.size == 0: # maybe the block is not decodeable return False, state if state is not self._initial_state: # make a copy of the state if it's not the initial state state = state.copy() else: # clear self._initial_state so that we *do not* run this optimization again! self._initial_state = None # Suppress spurious output if self._base_state is not None: self._base_state.options.add(sim_options.SYMBOL_FILL_UNCONSTRAINED_REGISTERS) self._base_state.options.add(sim_options.SYMBOL_FILL_UNCONSTRAINED_MEMORY) state = engine.process(state, block=block, project=self.project, base_state=self._base_state, load_callback=self._load_callback, fail_fast=self._fail_fast) state.filter_replacements() self._node_iterations[block_key] += 1 self._states[block_key] = state if self.replacements is None: self.replacements = state._replacements else: self.replacements.update(state._replacements) self.equivalence |= state._equivalence # TODO: Clear registers according to calling conventions if self._node_iterations[block_key] < self._max_iterations: return True, state else: return False, state def _intra_analysis(self): pass def _check_func_complete(self, func): """ Checks if a function is completely created by the CFG. Completed functions are passed to the Propagator at initialization. Defaults to being empty if no pass is initiated. :param func: Function to check (knowledge_plugins.functions.function.Function) :return: Bool """ complete = False if self._completed_funcs is None: return complete if func.addr in self._completed_funcs: complete = True return complete def _post_analysis(self): """ Post Analysis of Propagation(). We add the current propagation replacements result to the kb if the function has already been completed in cfg creation. """ # Filter replacements and remove all TOP values if self.replacements is not None: for codeloc in list(self.replacements.keys()): rep = dict((k, v) for k, v in self.replacements[codeloc].items() if not PropagatorState.is_top(v)) self.replacements[codeloc] = rep if self._function is not None: if self._check_func_complete(self._function): func_loc = CodeLocation(self._function.addr, None) self.kb.propagations.update(func_loc, self.replacements) def _check_prop_kb(self): """ Checks, and gets, stored propagations from the KB for the current Propagation state. :return: None or Dict of replacements """ replacements = None if self._function is not None: func_loc = CodeLocation(self._function.addr, None) replacements = self.kb.propagations.get(func_loc) return replacements def _analyze(self): """ The main analysis for Propagator. Overwritten to include an optimization to stop analysis if we have already analyzed the entire function once. """ self._pre_analysis() # optimization check stored_replacements = self._check_prop_kb() if stored_replacements is not None: if self.replacements is not None: self.replacements.update(stored_replacements) else: self.replacements = stored_replacements # normal analysis execution elif self._graph_visitor is None: # There is no base graph that we can rely on. The analysis itself should generate successors for the # current job. # An example is the CFG recovery. self._analysis_core_baremetal() else: # We have a base graph to follow. Just handle the current job. self._analysis_core_graph() self._post_analysis() register_analysis(PropagatorAnalysis, "Propagator")
# -*- coding: utf-8 -*- # # Copyright (c) 2017 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from unittest import TestCase from mock import patch, call, Mock from contextlib import nested from managesf.tests import dummy_conf from managesf.model.yamlbkd.resources.storyboard import StoryboardOps class StoryboardOpsTest(TestCase): def test_is_activated(self): conf = dummy_conf() s = StoryboardOps(conf, None) project = {'issue-tracker': 'SFStoryboard'} self.assertTrue(s.is_activated(**project)) project = {'issue-tracker': ''} self.assertFalse(s.is_activated(**project)) conf.services.remove('SFStoryboard') project = {'issue-tracker': 'SFStoryboard'} self.assertFalse(s.is_activated(**project)) def test_extra_validation(self): conf = dummy_conf() s = StoryboardOps(conf, None) project = { 'name': 'project1', 'source-repositories': ['repo1', 'repo2'] } logs = s.extra_validations(**project) self.assertTrue(len(logs) == 0) project = { 'name': 'project2', 'source-repositories': ['repo', '-hjook'] } logs = s.extra_validations(**project) self.assertTrue('Minimal len is 5' in logs[0]) self.assertTrue('should match the RE' in logs[1]) def test_update_project(self): class FakeItem(object): def __init__(self, name, id): self.name = name self.id = id conf = dummy_conf() s = StoryboardOps(conf, None) patches = [ patch('storyboardclient.v1.projects.ProjectsManager.get_all'), patch('storyboardclient.v1.projects.ProjectsManager.update'), patch('storyboardclient.v1.projects.ProjectsManager.create')] with nested(*patches) as (get_all, update, create): get_all.return_value = [FakeItem('project1', 1)] s.update_project('project1', 'A desc') self.assertTrue(get_all.called) self.assertTrue(update.called) self.assertFalse(create.called) with nested(*patches) as (get_all, update, create): get_all.return_value = [FakeItem('project1', 1)] s.update_project('project2', 'A desc') self.assertTrue(get_all.called) self.assertFalse(update.called) self.assertTrue(create.called) def test_update_project_group(self): class FakeItem(object): def __init__(self, name, id): self.name = name self.id = id conf = dummy_conf() patches = [ patch('storyboardclient.v1.project_groups.' 'ProjectGroupsManager.get_all'), patch('storyboardclient.v1.project_groups.' 'ProjectGroupsManager.create'), patch.object(StoryboardOps, 'update_project'), patch('storyboardclient.v1.project_groups.' 'ProjectGroupsManager.get'), patch('storyboardclient.v1.project_groups.' 'ProjectGroupsManager.update'), patch('storyboardclient.v1.projects.' 'ProjectsManager.get_all')] with nested(*patches) as (get_all, create, update_project, get, update, p_get_all): new = { 'resources': { 'repos': { 'project1': {'description': 'A desc'}, 'project2': {'description': 'A desc'} } } } s = StoryboardOps(conf, new) get_all.return_value = [FakeItem('pg1', 1)] fake_subprojects = [ FakeItem('project1', 1), FakeItem('project2', 2)] mput = Mock() mdelete = Mock() class fprojects(): def get_all(self): return fake_subprojects def put(self, id): mput(id) def delete(self, id): mdelete(id) class NestedProjects(): def __init__(self): self.projects = fprojects() get.return_value = NestedProjects() update.return_value = NestedProjects() p_get_all.return_value = fake_subprojects # Here projects are already included in the project # group so nothing will be added/removed in the project # group. Just projects will be updated. s.update_project_groups( **{'name': 'pg1', 'source-repositories': ['project1', 'project2']}) self.assertFalse(mput.called) self.assertFalse(mdelete.called) self.assertTrue(len(update_project.mock_calls), 2) # Here project1 and project2 are already included but # the resources project decription only defines the # project2 to be included. So we make sure the delete # is called with id 1. mput.reset_mock() mdelete.reset_mock() update_project.reset_mock() s.update_project_groups( **{'name': 'pg1', 'source-repositories': ['project2']}) self.assertFalse(mput.called) self.assertTrue(mdelete.called) self.assertListEqual(mdelete.call_args_list, [call(1)]) self.assertTrue(len(update_project.mock_calls), 1) # Here only project1 is already included but # the resources project decription defines the # project1 and project2 to be included. So we make sure # the put is called with id 2. mput.reset_mock() mdelete.reset_mock() update_project.reset_mock() fake_subprojects = [ FakeItem('project1', 1)] s.update_project_groups( **{'name': 'pg1', 'source-repositories': ['project1', 'project2']}) self.assertTrue(mput.called) self.assertListEqual(mput.call_args_list, [call(2)]) self.assertFalse(mdelete.called) self.assertTrue(len(update_project.mock_calls), 1) # Here the project group does not exist. So we verify # it is created and provisionned with two projects # included. get_all.return_value = [] p_get_all.return_value = [ FakeItem('project1', 1), FakeItem('project2', 2)] fake_subprojects = [] get.return_value = NestedProjects() update.return_value = NestedProjects() mput.reset_mock() mdelete.reset_mock() update_project.reset_mock() s.update_project_groups( **{'name': 'pg1', 'source-repositories': ['project1', 'project2']}) self.assertTrue(create.called) self.assertTrue(len(update_project.mock_calls), 2) self.assertTrue(len(mput.mock_calls), 2) self.assertFalse(mdelete.called) def test_delete_project_group(self): class FakeItem(object): def __init__(self, name, id): self.name = name self.id = id conf = dummy_conf() patches = [ patch('storyboardclient.v1.project_groups.' 'ProjectGroupsManager.get_all'), patch('storyboardclient.v1.project_groups.' 'ProjectGroupsManager.get'), patch('storyboardclient.v1.project_groups.' 'ProjectGroupsManager.update'), patch('storyboardclient.v1.project_groups.' 'ProjectGroupsManager.delete')] with nested(*patches) as (get_all, get, update, delete): s = StoryboardOps(conf, None) get_all.return_value = [FakeItem('pg1', 3)] mdelete = Mock() fake_subprojects = [ FakeItem('project1', 1), FakeItem('project2', 2)] class fprojects(): def get_all(self): return fake_subprojects def delete(self, id): mdelete(id) class NestedProjects(): def __init__(self): self.projects = fprojects() get.return_value = NestedProjects() update.return_value = NestedProjects() s.delete_project_groups(**{'name': 'pg1'}) self.assertEqual(len(mdelete.call_args_list), 2) self.assertIn(call(1), mdelete.call_args_list) self.assertIn(call(2), mdelete.call_args_list) self.assertListEqual(delete.call_args_list, [call(id=3)])
#!/usr/bin/env python import os, optparse from sys import stdout, stderr from string import punctuation import utils, chpl_platform, chpl_comm, chpl_compiler from utils import memoize class argument_map(object): # intel does not support amd archs... it may be worth testing setting the # equivalent intel arch, but I don't have any good way to do this as of now intel = { 'native': 'native', 'core2': 'core2', 'nehalem': 'corei7', 'westmere': 'corei7', 'sandybridge': 'corei7-avx', 'ivybridge': 'core-avx-i', 'haswell': 'core-avx2', 'broadwell': 'core-avx2', 'knc': 'knc', 'k8': 'none', 'k8sse3': 'none', 'barcelona': 'none', 'bdver1': 'none', 'bdver2': 'none', 'bdver3': 'none', 'bdver4': 'none', } gcc43 = { 'native': 'native', 'core2': 'core2', 'nehalem': 'core2', 'westmere': 'core2', 'sandybridge': 'core2', 'ivybridge': 'core2', 'haswell': 'core2', 'broadwell': 'core2', 'knc': 'none', 'k8': 'k8', 'k8sse3': 'k8-sse3', 'barcelona': 'barcelona', 'bdver1': 'barcelona', 'bdver2': 'barcelona', 'bdver3': 'barcelona', 'bdver4': 'barcelona', } gcc47 = { 'native': 'native', 'core2': 'core2', 'nehalem': 'corei7', 'westmere': 'corei7', 'sandybridge': 'corei7-avx', 'ivybridge': 'core-avx-i', 'haswell': 'core-avx2', 'broadwell': 'core-avx2', 'knc': 'none', 'k8': 'k8', 'k8sse3': 'k8-sse3', 'barcelona': 'barcelona', 'bdver1': 'bdver1', 'bdver2': 'bdver2', 'bdver3': 'bdver2', 'bdver4': 'bdver2', } gcc49 = { 'native': 'native', 'core2': 'core2', 'nehalem': 'nehalem', 'westmere': 'westmere', 'sandybridge': 'sandybridge', 'ivybridge': 'ivybridge', 'haswell': 'haswell', 'broadwell': 'broadwell', 'knc': 'none', 'k8': 'k8', 'k8sse3': 'k8-sse3', 'barcelona': 'barcelona', 'bdver1': 'bdver1', 'bdver2': 'bdver2', 'bdver3': 'bdver3', 'bdver4': 'bdver4', } clang = gcc47 @classmethod def find(cls, arch, compiler, version): if arch == 'unknown' or arch == '': return 'unknown' elif arch == 'none': return 'none' arg_value = cls._get(arch, compiler, version) if not arg_value: stderr.write('Warning: No valid option found: arch="{0}" ' 'compiler="{1}" version="{2}"\n'.format(arch, compiler, version)) return arg_value @classmethod def _get(cls, arch, compiler, version): if arch == 'unknown': return arch if compiler == 'gnu': if version >= 4.9: return cls.gcc49.get(arch, '') if version >= 4.7: return cls.gcc47.get(arch, '') if version >= 4.3: return cls.gcc43.get(arch, '') else: stderr.write('Warning: Argument map not found for GCC version: "{0}"\n'.format(version)) return '' elif compiler == 'intel': return cls.intel.get(arch, '') elif compiler == 'clang': return cls.clang.get(arch, '') else: stderr.write('Warning: Unknown compiler: "{0}"\n'.format(compiler)) return '' class feature_sets(object): core2 = ['mmx', 'sse', 'sse2', 'sse3', 'ssse3'] nehalem = core2 + ['sse41', 'sse42', 'popcnt'] westmere = nehalem + ['aes', 'pclmulqdq'] sandybridge = westmere + ['avx'] ivybridge = sandybridge + ['rdrand', 'f16c'] haswell = ivybridge + ['movbe', 'avx2', 'fma', 'bmi', 'bmi2'] broadwell = haswell + ['rdseed', 'adx'] intel = [ ('core2', core2), ('nehalem', nehalem), ('westmere', westmere), ('sandybridge', sandybridge), ('ivybridge', ivybridge), ('haswell', haswell), ('broadwell', broadwell), ] k8 = ['mmx', 'sse', 'sse2'] k8sse3 = k8 + ['sse3'] barcelona = k8sse3 + ['sse4a', 'abm'] bdver1 = barcelona + ['fma4', 'avx', 'xop', 'lwp', 'aes', 'pclmul', 'cx16', 'sse41', 'sse42'] bdver2 = bdver1 + ['bmi', 'tbm', 'f16c', 'fma'] bdver3 = bdver2 + ['fsgsbase'] bdver4 = bdver3 + ['bmi2', 'avx2', 'movbe'] amd = [ ('k8', k8), ('k8sse3', k8sse3), ('barcelona', barcelona), ('bdver1', bdver1), ('bdver2', bdver2), ('bdver3', bdver3), ('bdver4', bdver4), ] combined = intel + amd @classmethod def subset(sets, a, b): def check(lst, a, b): def list_in(x, y): if len(x) > len(y): return False for val in x: if val not in y: return False return True a_features = [] b_features = [] for k, v in lst: if k == a: a_features = v if k == b: b_features = v return a_features != [] and list_in(a_features, b_features) return check(sets.combined, a, b) @classmethod def find(sets, vendor, features): # remove all punctuation and split into a list system_features = features.lower().translate(None, punctuation).split() options = [] if "genuineintel" == vendor.lower(): options = sets.intel elif "authenticamd" == vendor.lower(): options = sets.amd found = '' for name, fset in options: if all([f in system_features for f in fset]): found = name else: break return found def get_cpuinfo(platform='linux'): vendor_string = '' feature_string = '' if platform == "darwin": vendor_string = utils.run_command(['sysctl', '-n', 'machdep.cpu.vendor']) feature_string = utils.run_command(['sysctl', '-n', 'machdep.cpu.features']) # osx reports AVX1.0 while linux reports it as AVX feature_string = feature_string.replace("AVX1.0", "AVX") elif os.path.isfile('/proc/cpuinfo'): with open('/proc/cpuinfo') as f: cpuinfo = f.readlines() for line in cpuinfo: if 'vendor_id' in line: vendor_string = line.split(':')[1].strip() elif 'flags' in line: feature_string = line.split(':')[1].strip() if vendor_string and feature_string: break else: raise ValueError("Unknown platform, could not find CPU information") return (vendor_string.strip(), feature_string.strip()) class InvalidLocationError(ValueError): pass @memoize def get(location, map_to_compiler=False): if not location or location == "host": arch = os.environ.get('CHPL_HOST_ARCH', '') elif location == 'target': arch = os.environ.get('CHPL_TARGET_ARCH', '') else: raise InvalidLocationError(location) # fast path out for when the user has set arch=none if arch == 'none': return arch comm_val = chpl_comm.get() compiler_val = chpl_compiler.get(location) platform_val = chpl_platform.get(location) if compiler_val.startswith('cray-prgenv'): if arch and (arch != 'none' or arch != 'unknown'): stderr.write("Warning: Setting the processor type through " "environment variables is not supported for " "cray-prgenv-*. Please use the appropriate craype-* " "module for your processor type.\n") arch = os.environ.get('CRAY_CPU_TARGET', 'none') if arch == 'none': stderr.write("Warning: No craype-* processor type module was " "detected, please load the appropriate one if you want " "any specialization to occur.\n") return arch elif 'pgi' in compiler_val: return 'none' elif 'cray' in compiler_val: return 'none' elif 'ibm' in compiler_val: return 'none' # Only try to do any auto-detection or verification when: # comm == none -- The inverse means that we are probably cross-compiling. # # linux/dawin/ -- The only platforms that we should try and detect on. # cygwin Crays will be handled through the craype-* modules # if comm_val == 'none' and ('linux' in platform_val or platform_val == 'darwin' or platform_val == 'cygwin'): if arch: if arch != 'knc' and not location or location == 'host': # when a user supplies an architecture, and it seems reasonable # to double check their choice we do so. This will only # generate a warning that the user may not be able to run # whatever they compile. # # This only runs when location is 'host' since we # conservatively assume that a setting for 'target' could be in # a cross-compilation setting try: vendor_string, feature_string = get_cpuinfo(platform_val) detected_arch = feature_sets.find(vendor_string, feature_string) if not feature_sets.subset(arch, detected_arch): stderr.write("Warning: The supplied processor type does " "not appear to be compatible with the host " "processor type. The resultant binary may " "not run on the current machine.\n") except ValueError: stderr.write("Warning: Unknown platform, could not find CPU information\n") else: # let the backend compiler do the actual feature set detection. We # could be more aggressive in setting a precise architecture using # the double checking code above, but it seems like a waste of time # to not use the work the backend compilers have already done arch = 'native' if map_to_compiler: version = utils.get_compiler_version(compiler_val) arch = argument_map.find(arch, compiler_val, version) return arch or 'unknown' def _main(): parser = optparse.OptionParser(usage="usage: %prog [--host|target] [--compflag]") parser.add_option('--target', dest='location', action='store_const', const='target', default='target') parser.add_option('--host', dest='location', action='store_const', const='host') parser.add_option('--compflag', dest='map_to_compiler', action='store_true', default=False) (options, args) = parser.parse_args() arch = get(options.location, options.map_to_compiler) stdout.write("{0}\n".format(arch)) if __name__ == '__main__': _main()
#!/usr/bin/python # Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # A script which makes it easy to execute common DOM-related tasks import os import subprocess import sys from sys import argv sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import utils dart_out_dir = utils.GetBuildRoot(utils.GuessOS(), 'release', 'ia32') if utils.IsWindows(): dart_bin = os.path.join(dart_out_dir, 'dart.exe') else: dart_bin = os.path.join(dart_out_dir, 'dart') dart_dir = os.path.abspath( os.path.join( os.path.dirname(os.path.realpath(__file__)), os.path.pardir, os.path.pardir)) def help(): print('Helper script to make it easy to perform common tasks encountered ' 'during the life of a Dart DOM developer.\n' '\n' 'For example, to re-generate DOM classes then run a specific test:\n' ' dom.py gen test_drt html/element_test\n' '\n' 'Or re-generate DOM classes and run the Dart analyzer:\n' ' dom.py gen analyze\n') print('Commands: ') for cmd in sorted(commands.keys()): print('\t%s - %s' % (cmd, commands[cmd][1])) def analyze(): ''' Runs the dart analyzer. ''' return call([ os.path.join(dart_out_dir, 'dart-sdk', 'bin', 'dartanalyzer'), os.path.join('tests', 'html', 'element_test.dart'), '--dart-sdk=sdk', '--show-package-warnings', ]) def build(): ''' Builds the Dart binary ''' return call([ os.path.join('tools', 'build.py'), '--mode=release', '--arch=ia32', 'runtime', ]) def dart2js(): compile_dart2js(argv.pop(0), True) def docs(): return call([ os.path.join(dart_out_dir, 'dart-sdk', 'bin', 'dart'), '--package-root=%s' % os.path.join(dart_out_dir, 'packages/'), os.path.join('tools', 'dom', 'docs', 'bin', 'docs.dart'), ]) def test_docs(): return call([ os.path.join('tools', 'test.py'), '--mode=release', '--checked', 'docs' ]) def compile_dart2js(dart_file, checked): out_file = dart_file + '.js' dart2js_path = os.path.join(dart_out_dir, 'dart-sdk', 'bin', 'dart2js') args = [dart2js_path, dart_file, '--library-root=sdk/', '-o%s' % out_file] if checked: args.append('--checked') call(args) return out_file def gen(): os.chdir(os.path.join('tools', 'dom', 'scripts')) result = call([ os.path.join(os.getcwd(), 'dartdomgenerator.py'), '--rebuild', '--parallel', '--systems=htmldart2js,htmldartium' ]) os.chdir(os.path.join('..', '..', '..')) return result def size_check(): ''' Displays the dart2js size of swarm. ''' dart_file = os.path.join('samples', 'swarm', 'swarm.dart') out_file = compile_dart2js(dart_file, False) return call([ 'du', '-kh', '--apparent-size', out_file, ]) os.remove(out_file) os.remove(out_file + '.deps') os.remove(out_file + '.map') def test_ff(): test_dart2js('ff', argv) def test_drt(): test_dart2js('drt', argv) def test_chrome(): test_dart2js('chrome', argv) def test_dart2js(browser, argv): cmd = [ os.path.join('tools', 'test.py'), '-c', 'dart2js', '-r', browser, '--mode=release', '--checked', '--arch=ia32', '-v', ] if argv: cmd.append(argv.pop(0)) else: print( 'Test commands should be followed by tests to run. Defaulting to html' ) cmd.append('html') return call(cmd) def test_server(): start_test_server(5400, os.path.join('out', 'ReleaseX64')) def test_server_dartium(): start_test_server(5500, os.path.join('..', 'out', 'Release')) def start_test_server(port, build_directory): print( 'Browse tests at ' '\033[94mhttp://localhost:%d/root_build/generated_tests/\033[0m' % port) return call([ utils.CheckedInSdkExecutable(), os.path.join('tools', 'testing', 'dart', 'http_server.dart'), '--port=%d' % port, '--crossOriginPort=%d' % (port + 1), '--network=0.0.0.0', '--build-directory=%s' % build_directory ]) def call(args): print ' '.join(args) pipe = subprocess.Popen( args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = pipe.communicate() if output: print output if error: print error return pipe.returncode commands = { 'analyze': [analyze, 'Run the dart analyzer'], 'build': [build, 'Build dart in release mode'], 'dart2js': [dart2js, 'Run dart2js on the .dart file specified'], 'docs': [docs, 'Generates docs.json'], 'gen': [gen, 'Re-generate DOM generated files (run go.sh)'], 'size_check': [size_check, 'Check the size of dart2js compiled Swarm'], 'test_docs': [test_docs, 'Tests docs.dart'], 'test_chrome': [ test_chrome, 'Run tests in checked mode in Chrome.\n' '\t\tOptionally provide name of test to run.' ], # TODO(antonm): fix option name. 'test_drt': [ test_drt, 'Run tests in checked mode in content shell.\n' '\t\tOptionally provide name of test to run.' ], 'test_ff': [ test_ff, 'Run tests in checked mode in Firefox.\n' '\t\tOptionally provide name of test to run.' ], 'test_server': [ test_server, 'Starts the testing server for manually ' 'running browser tests.' ], 'test_server_dartium': [ test_server_dartium, 'Starts the testing server for ' 'manually running browser tests from a dartium enlistment.' ], } def main(): success = True argv.pop(0) if not argv: help() success = False while (argv): # Make sure that we're always rooted in the dart root folder. os.chdir(dart_dir) command = argv.pop(0) if not command in commands: help() success = False break returncode = commands[command][0]() success = success and not bool(returncode) sys.exit(not success) if __name__ == '__main__': main()
# This is a sample commands.py. You can add your own commands here. # # Please refer to commands_full.py for all the default commands and a complete # documentation. Do NOT add them all here, or you may end up with defunct # commands when upgrading ranger. # A simple command for demonstration purposes follows. # ----------------------------------------------------------------------------- from __future__ import (absolute_import, division, print_function) import os import re import subprocess from collections import deque from ranger.api.commands import Command from ranger.container.file import File from ranger.ext.get_executables import get_executables # Any class that is a subclass of "Command" will be integrated into ranger as a # command. Try typing ":my_edit<ENTER>" in ranger! class my_edit(Command): # The so-called doc-string of the class will be visible in the built-in # help that is accessible by typing "?c" inside ranger. """:my_edit <filename> A sample command for demonstration purposes that opens a file in an editor. """ # The execute method is called when you run this command in ranger. def execute(self): # self.arg(1) is the first (space-separated) argument to the function. # This way you can write ":my_edit somefilename<ENTER>". if self.arg(1): # self.rest(1) contains self.arg(1) and everything that follows target_filename = self.rest(1) else: # self.fm is a ranger.core.filemanager.FileManager object and gives # you access to internals of ranger. # self.fm.thisfile is a ranger.container.file.File object and is a # reference to the currently selected file. target_filename = self.fm.thisfile.path # This is a generic function to print text in ranger. self.fm.notify("Let's edit the file " + target_filename + "!") # Using bad=True in fm.notify allows you to print error messages: if not os.path.exists(target_filename): self.fm.notify("The given file does not exist!", bad=True) return # This executes a function from ranger.core.actions, a module with a # variety of subroutines that can help you construct commands. # Check out the source, or run "pydoc ranger.core.actions" for a list. self.fm.edit_file(target_filename) # The tab method is called when you press tab, and should return a list of # suggestions that the user will tab through. # tabnum is 1 for <TAB> and -1 for <S-TAB> by default def tab(self, tabnum): # This is a generic tab-completion function that iterates through the # content of the current directory. return self._tab_directory_content() class mkcd(Command): """ :mkcd <dirname> Creates a directory with the name <dirname> and enters it. """ def execute(self): from os.path import join, expanduser, lexists from os import makedirs import re dirname = join(self.fm.thisdir.path, expanduser(self.rest(1))) if not lexists(dirname): makedirs(dirname) match = re.search('^/|^~[^/]*/', dirname) if match: self.fm.cd(match.group(0)) dirname = dirname[match.end(0):] for m in re.finditer('[^/]+', dirname): s = m.group(0) if s == '..' or (s.startswith('.') and not self.fm.settings['show_hidden']): self.fm.cd(s) else: ## We force ranger to load content before calling `scout`. self.fm.thisdir.load_content(schedule=False) self.fm.execute_console('scout -ae ^{}$'.format(s)) else: self.fm.notify("file/directory exists!", bad=True) class fzf_select(Command): """ :fzf_select Find a file using fzf. With a prefix argument to select only directories. See: https://github.com/junegunn/fzf """ def execute(self): import subprocess import os from ranger.ext.get_executables import get_executables if 'fzf' not in get_executables(): self.fm.notify('Could not find fzf in the PATH.', bad=True) return fd = None if 'fdfind' in get_executables(): fd = 'fdfind' elif 'fd' in get_executables(): fd = 'fd' if fd is not None: hidden = ('--hidden' if self.fm.settings.show_hidden else '') exclude = "--no-ignore-vcs --exclude '.git' --exclude '*.py[co]' --exclude '__pycache__'" only_directories = ('--type directory' if self.quantifier else '') fzf_default_command = '{} --follow {} {} {} --color=always'.format( fd, hidden, exclude, only_directories ) else: hidden = ('-false' if self.fm.settings.show_hidden else r"-path '*/\.*' -prune") exclude = r"\( -name '\.git' -o -iname '\.*py[co]' -o -fstype 'dev' -o -fstype 'proc' \) -prune" only_directories = ('-type d' if self.quantifier else '') fzf_default_command = 'find -L . -mindepth 1 {} -o {} -o {} -print | cut -b3-'.format( hidden, exclude, only_directories ) env = os.environ.copy() env['FZF_DEFAULT_COMMAND'] = fzf_default_command env['FZF_DEFAULT_OPTS'] = '--height=40% --layout=reverse --ansi --preview="{}"'.format(''' ( batcat --color=always {} || bat --color=always {} || cat {} || tree -ahpCL 3 -I '.git' -I '*.py[co]' -I '__pycache__' {} ) 2>/dev/null | head -n 100 ''') fzf = self.fm.execute_command('fzf --no-multi', env=env, universal_newlines=True, stdout=subprocess.PIPE) stdout, _ = fzf.communicate() if fzf.returncode == 0: selected = os.path.abspath(stdout.strip()) if os.path.isdir(selected): self.fm.cd(selected) else: self.fm.select_file(selected) class YankContent(Command): """ Copy the content of image file and text file with xclip """ def execute(self): if 'xclip' not in get_executables(): self.fm.notify('xclip is not found.', bad=True) return arg = self.rest(1) if arg: if not os.path.isfile(arg): self.fm.notify('{} is not a file.'.format(arg)) return file = File(arg) else: file = self.fm.thisfile if not file.is_file: self.fm.notify('{} is not a file.'.format(file.relative_path)) return relative_path = file.relative_path cmd = ['xclip', '-selection', 'clipboard'] if not file.is_binary(): with open(file.path, 'rb') as fd: subprocess.check_call(cmd, stdin=fd) elif file.image: cmd += ['-t', file.mimetype, file.path] subprocess.check_call(cmd) self.fm.notify('Content of {} is copied to x clipboard'.format(relative_path)) else: self.fm.notify('{} is not an image file or a text file.'.format(relative_path)) def tab(self, tabnum): return self._tab_directory_content() class fd_search(Command): """ :fd_search [-d<depth>] <query> Executes "fd -d<depth> <query>" in the current directory and focuses the first match. <depth> defaults to 1, i.e. only the contents of the current directory. See https://github.com/sharkdp/fd """ SEARCH_RESULTS = deque() def execute(self): self.SEARCH_RESULTS.clear() if 'fdfind' in get_executables(): fd = 'fdfind' elif 'fd' in get_executables(): fd = 'fd' else: self.fm.notify("Couldn't find fd in the PATH.", bad=True) return if self.arg(1): if self.arg(1)[:2] == '-d': depth = self.arg(1) target = self.rest(2) else: depth = '-d1' target = self.rest(1) else: self.fm.notify(":fd_search needs a query.", bad=True) return hidden = ('--hidden' if self.fm.settings.show_hidden else '') exclude = "--no-ignore-vcs --exclude '.git' --exclude '*.py[co]' --exclude '__pycache__'" command = '{} --follow {} {} {} --print0 {}'.format( fd, depth, hidden, exclude, target ) fd = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE) stdout, _ = fd.communicate() if fd.returncode == 0: results = filter(None, stdout.split('\0')) if not self.fm.settings.show_hidden and self.fm.settings.hidden_filter: hidden_filter = re.compile(self.fm.settings.hidden_filter) results = filter(lambda res: not hidden_filter.search(os.path.basename(res)), results) results = map(lambda res: os.path.abspath(os.path.join(self.fm.thisdir.path, res)), results) self.SEARCH_RESULTS.extend(sorted(results, key=str.lower)) if len(self.SEARCH_RESULTS) > 0: self.fm.notify('Found {} result{}.'.format(len(self.SEARCH_RESULTS), ('s' if len(self.SEARCH_RESULTS) > 1 else ''))) self.fm.select_file(self.SEARCH_RESULTS[0]) else: self.fm.notify('No results found.') class fd_next(Command): """ :fd_next Selects the next match from the last :fd_search. """ def execute(self): if len(fd_search.SEARCH_RESULTS) > 1: fd_search.SEARCH_RESULTS.rotate(-1) # rotate left self.fm.select_file(fd_search.SEARCH_RESULTS[0]) elif len(fd_search.SEARCH_RESULTS) == 1: self.fm.select_file(fd_search.SEARCH_RESULTS[0]) class fd_prev(Command): """ :fd_prev Selects the next match from the last :fd_search. """ def execute(self): if len(fd_search.SEARCH_RESULTS) > 1: fd_search.SEARCH_RESULTS.rotate(1) # rotate right self.fm.select_file(fd_search.SEARCH_RESULTS[0]) elif len(fd_search.SEARCH_RESULTS) == 1: self.fm.select_file(fd_search.SEARCH_RESULTS[0])
import uuid from pyramid.httpexceptions import HTTPFound from pyramid.security import NO_PERMISSION_REQUIRED import requests from ..api import ( AuthenticationComplete, AuthenticationDenied, register_provider, ) from ..exceptions import CSRFError from ..exceptions import ThirdPartyFailure from ..settings import ProviderSettings from ..utils import flat_url GOOGLE_OAUTH2_DOMAIN = 'accounts.google.com' class GoogleAuthenticationComplete(AuthenticationComplete): """Google OAuth 2.0 auth complete""" def includeme(config): """Activate the ``google_oauth2`` Pyramid plugin via ``config.include('velruse.providers.google_oauth2')``. After included, two new methods will be available to configure new providers. ``config.add_google_oauth2_login()`` See :func:`~velruse.providers.google_oauth2.add_google_login` for the supported options. ``config.add_google_oauth2_login_from_settings()`` """ config.add_directive('add_google_oauth2_login', add_google_login) config.add_directive('add_google_oauth2_login_from_settings', add_google_login_from_settings) def add_google_login_from_settings(config, prefix='velruse.google.'): settings = config.registry.settings p = ProviderSettings(settings, prefix) p.update('consumer_key', required=True) p.update('consumer_secret', required=True) p.update('scope') p.update('login_path') p.update('callback_path') config.add_google_oauth2_login(**p.kwargs) def add_google_login(config, consumer_key=None, consumer_secret=None, scope=None, login_path='/login/google', callback_path='/login/google/callback', name='google'): """ Add a Google login provider to the application supporting the new OAuth2 protocol. """ provider = GoogleOAuth2Provider( name, consumer_key, consumer_secret, scope) config.add_route(provider.login_route, login_path) config.add_view(provider, attr='login', route_name=provider.login_route, permission=NO_PERMISSION_REQUIRED) config.add_route(provider.callback_route, callback_path, use_global_views=True, factory=provider.callback) register_provider(config, name, provider) class GoogleOAuth2Provider(object): profile_scope = 'profile' email_scope = 'email' def __init__(self, name, consumer_key, consumer_secret, scope): self.name = name self.type = 'google_oauth2' self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.protocol = 'https' self.domain = GOOGLE_OAUTH2_DOMAIN self.login_route = 'velruse.%s-login' % name self.callback_route = 'velruse.%s-callback' % name self.scope = scope if not self.scope: self.scope = ' '.join((self.profile_scope, self.email_scope)) def login(self, request): """Initiate a google login""" scope = ' '.join(request.POST.getall('scope')) or self.scope request.session['velruse.state'] = state = uuid.uuid4().hex approval_prompt = request.POST.get('approval_prompt', 'auto') auth_url = flat_url( '%s://%s/o/oauth2/auth' % (self.protocol, self.domain), scope=scope, response_type='code', client_id=self.consumer_key, redirect_uri=request.route_url(self.callback_route), approval_prompt=approval_prompt, access_type='offline', state=state) return HTTPFound(location=auth_url) def callback(self, request): """Process the google redirect""" sess_state = request.session.pop('velruse.state', None) req_state = request.GET.get('state') if not sess_state or sess_state != req_state: raise CSRFError( 'CSRF Validation check failed. Request state {req_state} is ' 'not the same as session state {sess_state}'.format( req_state=req_state, sess_state=sess_state ) ) code = request.GET.get('code') if not code: reason = request.GET.get('error', 'No reason provided.') return AuthenticationDenied(reason=reason, provider_name=self.name, provider_type=self.type) # Now retrieve the access token with the code r = requests.post( '%s://%s/o/oauth2/token' % (self.protocol, self.domain), dict(client_id=self.consumer_key, client_secret=self.consumer_secret, redirect_uri=request.route_url(self.callback_route), code=code, grant_type='authorization_code'), ) if r.status_code != 200: raise ThirdPartyFailure("Status %s: %s" % ( r.status_code, r.content)) token_data = r.json() access_token = token_data['access_token'] refresh_token = token_data.get('refresh_token') # Retrieve profile data if scopes allow profile = {} user_url = flat_url( 'https://www.googleapis.com/plus/v1/people/me', access_token=access_token) r = requests.get(user_url) if r.status_code == 200: data = r.json() email = None if 'email' in data: email = data['email'] profile['emails'] = [{'value': email, 'primary': True}] elif 'emails' in data: profile['emails'] = data['emails'] if len(profile['emails']): email = data['emails'][0]['value'] profile['emails'][0]['primary'] = True profile['accounts'] = [{ 'domain': self.domain, 'username': email, 'userid': data['id'] }] if 'name' in data: profile['name'] = data['name'] if 'displayName' in data: profile['displayName'] = data['displayName'] elif 'name' in data: profile['displayName'] = profile['name'] else: profile['displayName'] = email profile['preferredUsername'] = email if data.get('verified_email'): profile['verifiedEmail'] = email if 'given_name' in data and 'family_name' in data: profile['name'] = { 'familyName': data['family_name'], 'givenName': data['given_name'] } if 'gender' in data: profile['gender'] = data['gender'] if 'picture' in data: profile['photos'] = [{'value': data['picture']}] if 'locale' in data: profile['locale'] = data['locale'] if 'urls' in data: profile['urls'] = data['urls'] elif 'link' in data: profile['urls'] = [{'value': data['link'], 'type': 'profile'}] elif 'url' in data: profile['urls'] = [{'value': data['url'], 'type': 'profile'}] if 'hd' in data: # Hosted domain (e.g. if the user is Google apps) profile['hostedDomain'] = data['hd'] if 'language' in data: profile['language'] = data['language'] if 'verified' in data: profile['verified'] = data['verified'] cred = {'oauthAccessToken': access_token, 'oauthRefreshToken': refresh_token} return GoogleAuthenticationComplete(profile=profile, credentials=cred, provider_name=self.name, provider_type=self.type)
from __future__ import absolute_import, unicode_literals import itertools import django from django import template from django.conf import settings from django.contrib.humanize.templatetags.humanize import intcomma from django.contrib.messages.constants import DEFAULT_TAGS as MESSAGE_TAGS from django.template.defaultfilters import stringfilter from django.utils.html import conditional_escape from django.utils.safestring import mark_safe from wagtail.utils.pagination import DEFAULT_PAGE_KEY, replace_page_in_query from wagtail.wagtailadmin.menu import admin_menu from wagtail.wagtailadmin.navigation import get_navigation_menu_items from wagtail.wagtailadmin.search import admin_search_areas from wagtail.wagtailcore import hooks from wagtail.wagtailcore.models import PageViewRestriction, UserPagePermissionsProxy from wagtail.wagtailcore.utils import cautious_slugify as _cautious_slugify from wagtail.wagtailcore.utils import camelcase_to_underscore, escape_script register = template.Library() register.filter('intcomma', intcomma) if django.VERSION >= (1, 9): assignment_tag = register.simple_tag else: assignment_tag = register.assignment_tag @register.inclusion_tag('wagtailadmin/shared/explorer_nav.html', takes_context=True) def explorer_nav(context): return { 'nodes': get_navigation_menu_items(context['request'].user) } @register.inclusion_tag('wagtailadmin/shared/explorer_nav_child.html') def explorer_subnav(nodes): return { 'nodes': nodes } @register.inclusion_tag('wagtailadmin/shared/main_nav.html', takes_context=True) def main_nav(context): request = context['request'] return { 'menu_html': admin_menu.render_html(request), 'request': request, } @register.inclusion_tag('wagtailadmin/shared/search_other.html', takes_context=True) def search_other(context, current=None): request = context['request'] return { 'options_html': admin_search_areas.render_html(request, current), 'request': request, } @register.simple_tag def main_nav_js(): return admin_menu.media['js'] @register.filter("ellipsistrim") def ellipsistrim(value, max_length): if len(value) > max_length: truncd_val = value[:max_length] if not len(value) == (max_length + 1) and value[max_length + 1] != " ": truncd_val = truncd_val[:truncd_val.rfind(" ")] return truncd_val + "..." return value @register.filter def no_thousand_separator(num): """ Prevent USE_THOUSAND_SEPARATOR from automatically inserting a thousand separator on this value """ return str(num) @register.filter def fieldtype(bound_field): try: return camelcase_to_underscore(bound_field.field.__class__.__name__) except AttributeError: try: return camelcase_to_underscore(bound_field.__class__.__name__) except AttributeError: return "" @register.filter def widgettype(bound_field): try: return camelcase_to_underscore(bound_field.field.widget.__class__.__name__) except AttributeError: try: return camelcase_to_underscore(bound_field.widget.__class__.__name__) except AttributeError: return "" @assignment_tag(takes_context=True) def page_permissions(context, page): """ Usage: {% page_permissions page as page_perms %} Sets the variable 'page_perms' to a PagePermissionTester object that can be queried to find out what actions the current logged-in user can perform on the given page. """ # Create a UserPagePermissionsProxy object to represent the user's global permissions, and # cache it in the context for the duration of the page request, if one does not exist already if 'user_page_permissions' not in context: context['user_page_permissions'] = UserPagePermissionsProxy(context['request'].user) # Now retrieve a PagePermissionTester from it, specific to the given page return context['user_page_permissions'].for_page(page) @assignment_tag(takes_context=True) def test_page_is_public(context, page): """ Usage: {% test_page_is_public page as is_public %} Sets 'is_public' to True iff there are no page view restrictions in place on this page. Caches the list of page view restrictions in the context, to avoid repeated DB queries on repeated calls. """ if 'all_page_view_restriction_paths' not in context: context['all_page_view_restriction_paths'] = PageViewRestriction.objects.select_related('page').values_list( 'page__path', flat=True ) is_private = any([ page.path.startswith(restricted_path) for restricted_path in context['all_page_view_restriction_paths'] ]) return not is_private @register.simple_tag def hook_output(hook_name): """ Example: {% hook_output 'insert_editor_css' %} Whenever we have a hook whose functions take no parameters and return a string, this tag can be used to output the concatenation of all of those return values onto the page. Note that the output is not escaped - it is the hook function's responsibility to escape unsafe content. """ snippets = [fn() for fn in hooks.get_hooks(hook_name)] return mark_safe(''.join(snippets)) @assignment_tag def usage_count_enabled(): return getattr(settings, 'WAGTAIL_USAGE_COUNT_ENABLED', False) @assignment_tag def base_url_setting(): return getattr(settings, 'BASE_URL', None) @assignment_tag def allow_unicode_slugs(): if django.VERSION < (1, 9): # Unicode slugs are unsupported on Django 1.8 return False else: return getattr(settings, 'WAGTAIL_ALLOW_UNICODE_SLUGS', True) class EscapeScriptNode(template.Node): TAG_NAME = 'escapescript' def __init__(self, nodelist): super(EscapeScriptNode, self).__init__() self.nodelist = nodelist def render(self, context): out = self.nodelist.render(context) return escape_script(out) @classmethod def handle(cls, parser, token): nodelist = parser.parse(('end' + EscapeScriptNode.TAG_NAME,)) parser.delete_first_token() return cls(nodelist) register.tag(EscapeScriptNode.TAG_NAME, EscapeScriptNode.handle) # Helpers for Widget.render_with_errors, our extension to the Django widget API that allows widgets to # take on the responsibility of rendering their own error messages @register.filter def render_with_errors(bound_field): """ Usage: {{ field|render_with_errors }} as opposed to {{ field }}. If the field (a BoundField instance) has errors on it, and the associated widget implements a render_with_errors method, call that; otherwise, call the regular widget rendering mechanism. """ widget = bound_field.field.widget if bound_field.errors and hasattr(widget, 'render_with_errors'): return widget.render_with_errors( bound_field.html_name, bound_field.value(), attrs={'id': bound_field.auto_id}, errors=bound_field.errors ) else: return bound_field.as_widget() @register.filter def has_unrendered_errors(bound_field): """ Return true if this field has errors that were not accounted for by render_with_errors, because the widget does not support the render_with_errors method """ return bound_field.errors and not hasattr(bound_field.field.widget, 'render_with_errors') @register.filter(is_safe=True) @stringfilter def cautious_slugify(value): return _cautious_slugify(value) @register.simple_tag(takes_context=True) def querystring(context, **kwargs): """ Print out the current querystring. Any keyword arguments to this template tag will be added to the querystring before it is printed out. <a href="/page/{% querystring key='value' %}"> Will result in something like: <a href="/page/?foo=bar&key=value"> """ request = context['request'] querydict = request.GET.copy() # Can't do querydict.update(kwargs), because QueryDict.update() appends to # the list of values, instead of replacing the values. for key, value in kwargs.items(): if value is None: # Remove the key if the value is None querydict.pop(key, None) else: # Set the key otherwise querydict[key] = value return '?' + querydict.urlencode() @register.simple_tag(takes_context=True) def pagination_querystring(context, page_number, page_key=DEFAULT_PAGE_KEY): """ Print out a querystring with an updated page number: {% if page.has_next_page %} <a href="{% pagination_link page.next_page_number %}">Next page</a> {% endif %} """ return querystring(context, **{page_key: page_number}) @register.inclusion_tag("wagtailadmin/pages/listing/_pagination.html", takes_context=True) def paginate(context, page, base_url='', page_key=DEFAULT_PAGE_KEY, classnames=''): """ Print pagination previous/next links, and the page count. Take the following arguments: page The current page of results. This should be a Django pagination `Page` instance base_url The base URL of the next/previous page, with no querystring. This is optional, and defaults to the current page by just printing the querystring for the next/previous page. page_key The name of the page variable in the query string. Defaults to the same name as used in the :func:`~wagtail.utils.pagination.paginate` function. classnames Extra classes to add to the next/previous links. """ request = context['request'] return { 'base_url': base_url, 'classnames': classnames, 'request': request, 'page': page, 'page_key': page_key, 'paginator': page.paginator, } @register.inclusion_tag("wagtailadmin/pages/listing/_buttons.html", takes_context=True) def page_listing_buttons(context, page, page_perms, is_parent=False): button_hooks = hooks.get_hooks('register_page_listing_buttons') buttons = sorted(itertools.chain.from_iterable( hook(page, page_perms, is_parent) for hook in button_hooks)) return {'page': page, 'buttons': buttons} @register.simple_tag def message_tags(message): level_tag = MESSAGE_TAGS.get(message.level) if message.extra_tags and level_tag: return message.extra_tags + ' ' + level_tag elif message.extra_tags: return message.extra_tags elif level_tag: return level_tag else: return '' @register.simple_tag def replace_page_param(query, page_number, page_key='p'): """ Replaces ``page_key`` from query string with ``page_number``. """ return conditional_escape(replace_page_in_query(query, page_number, page_key))
""" Manage the password database on BSD systems .. important:: If you feel that Salt should be using this module to manage passwords on a minion, and it is using a different module (or gives an error similar to *'shadow.info' is not available*), see :ref:`here <module-provider-override>`. """ import salt.utils.files import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError try: import pwd except ImportError: pass try: import salt.utils.pycrypto HAS_CRYPT = True except ImportError: HAS_CRYPT = False # Define the module's virtual name __virtualname__ = "shadow" def __virtual__(): if "BSD" in __grains__.get("os", ""): return __virtualname__ return ( False, "The bsd_shadow execution module cannot be loaded: " "only available on BSD family systems.", ) def default_hash(): """ Returns the default hash used for unset passwords CLI Example: .. code-block:: bash salt '*' shadow.default_hash """ return "*" if __grains__["os"].lower() == "freebsd" else "*************" def gen_password(password, crypt_salt=None, algorithm="sha512"): """ Generate hashed password .. note:: When called this function is called directly via remote-execution, the password argument may be displayed in the system's process list. This may be a security risk on certain systems. password Plaintext password to be hashed. crypt_salt Crpytographic salt. If not given, a random 8-character salt will be generated. algorithm The following hash algorithms are supported: * md5 * blowfish (not in mainline glibc, only available in distros that add it) * sha256 * sha512 (default) CLI Example: .. code-block:: bash salt '*' shadow.gen_password 'I_am_password' salt '*' shadow.gen_password 'I_am_password' crypt_salt='I_am_salt' algorithm=sha256 """ if not HAS_CRYPT: raise CommandExecutionError( "gen_password is not available on this operating system " 'because the "crypt" python module is not available.' ) return salt.utils.pycrypto.gen_hash(crypt_salt, password, algorithm) def info(name): """ Return information for the specified user CLI Example: .. code-block:: bash salt '*' shadow.info someuser """ try: data = pwd.getpwnam(name) ret = {"name": data.pw_name, "passwd": data.pw_passwd} except KeyError: return {"name": "", "passwd": ""} if not isinstance(name, str): name = str(name) if ":" in name: raise SaltInvocationError("Invalid username '{}'".format(name)) if __salt__["cmd.has_exec"]("pw"): change, expire = __salt__["cmd.run_stdout"]( ["pw", "user", "show", name], python_shell=False ).split(":")[5:7] elif __grains__["kernel"] in ("NetBSD", "OpenBSD"): try: with salt.utils.files.fopen("/etc/master.passwd", "r") as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith("{}:".format(name)): key = line.split(":") change, expire = key[5:7] ret["passwd"] = str(key[1]) break except OSError: change = expire = None else: change = expire = None try: ret["change"] = int(change) except ValueError: pass try: ret["expire"] = int(expire) except ValueError: pass return ret def set_change(name, change): """ Sets the time at which the password expires (in seconds since the UNIX epoch). See ``man 8 usermod`` on NetBSD and OpenBSD or ``man 8 pw`` on FreeBSD. A value of ``0`` sets the password to never expire. CLI Example: .. code-block:: bash salt '*' shadow.set_change username 1419980400 """ pre_info = info(name) if change == pre_info["change"]: return True if __grains__["kernel"] == "FreeBSD": cmd = ["pw", "user", "mod", name, "-f", change] else: cmd = ["usermod", "-f", change, name] __salt__["cmd.run"](cmd, python_shell=False) post_info = info(name) if post_info["change"] != pre_info["change"]: return post_info["change"] == change def set_expire(name, expire): """ Sets the time at which the account expires (in seconds since the UNIX epoch). See ``man 8 usermod`` on NetBSD and OpenBSD or ``man 8 pw`` on FreeBSD. A value of ``0`` sets the account to never expire. CLI Example: .. code-block:: bash salt '*' shadow.set_expire username 1419980400 """ pre_info = info(name) if expire == pre_info["expire"]: return True if __grains__["kernel"] == "FreeBSD": cmd = ["pw", "user", "mod", name, "-e", expire] else: cmd = ["usermod", "-e", expire, name] __salt__["cmd.run"](cmd, python_shell=False) post_info = info(name) if post_info["expire"] != pre_info["expire"]: return post_info["expire"] == expire def del_password(name): """ .. versionadded:: 2015.8.2 Delete the password from name user CLI Example: .. code-block:: bash salt '*' shadow.del_password username """ cmd = "pw user mod {} -w none".format(name) __salt__["cmd.run"](cmd, python_shell=False, output_loglevel="quiet") uinfo = info(name) return not uinfo["passwd"] def set_password(name, password): """ Set the password for a named user. The password must be a properly defined hash. The password hash can be generated with this command: ``python -c "import crypt; print crypt.crypt('password', ciphersalt)"`` .. note:: When constructing the ``ciphersalt`` string, you must escape any dollar signs, to avoid them being interpolated by the shell. ``'password'`` is, of course, the password for which you want to generate a hash. ``ciphersalt`` is a combination of a cipher identifier, an optional number of rounds, and the cryptographic salt. The arrangement and format of these fields depends on the cipher and which flavor of BSD you are using. For more information on this, see the manpage for ``crpyt(3)``. On NetBSD, additional information is available in ``passwd.conf(5)``. It is important to make sure that a supported cipher is used. CLI Example: .. code-block:: bash salt '*' shadow.set_password someuser '$1$UYCIxa628.9qXjpQCjM4a..' """ if __grains__.get("os", "") == "FreeBSD": cmd = ["pw", "user", "mod", name, "-H", "0"] stdin = password else: cmd = ["usermod", "-p", password, name] stdin = None __salt__["cmd.run"](cmd, stdin=stdin, output_loglevel="quiet", python_shell=False) return info(name)["passwd"] == password
"""Handle installation and updates of bcbio-nextgen, third party software and data. Enables automated installation tool and in-place updates to install additional data and software. """ import argparse import collections import contextlib import datetime import dateutil from distutils.version import LooseVersion import gzip import os import shutil import subprocess import sys import glob import urllib import requests import yaml from bcbio import broad, utils from bcbio.pipeline import genome from bcbio.variation import effects from bcbio.distributed.transaction import file_transaction from bcbio.pipeline import datadict as dd REMOTES = { "requirements": "https://raw.github.com/chapmanb/bcbio-nextgen/master/requirements.txt", "gitrepo": "https://github.com/chapmanb/bcbio-nextgen.git", "cloudbiolinux": "https://github.com/chapmanb/cloudbiolinux.git", "genome_resources": "https://raw.github.com/chapmanb/bcbio-nextgen/master/config/genomes/%s-resources.yaml", "snpeff_dl_url": ("http://downloads.sourceforge.net/project/snpeff/databases/v{snpeff_ver}/" "snpEff_v{snpeff_ver}_{genome}.zip")} SUPPORTED_GENOMES = ["GRCh37", "hg19", "hg38", "hg38-noalt", "mm10", "mm9", "rn6", "rn5", "canFam3", "dm3", "galGal4", "phix", "pseudomonas_aeruginosa_ucbpp_pa14", "sacCer3", "TAIR10", "WBcel235", "xenTro3", "Zv9", "GRCz10"] SUPPORTED_INDEXES = ["bowtie", "bowtie2", "bwa", "novoalign", "snap", "star", "ucsc", "seq"] Tool = collections.namedtuple("Tool", ["name", "fname"]) def upgrade_bcbio(args): """Perform upgrade of bcbio to latest release, or from GitHub development version. Handles bcbio, third party tools and data. """ args = add_install_defaults(args) pip_bin = os.path.join(os.path.dirname(sys.executable), "pip") if args.upgrade in ["skip"]: pass elif args.upgrade in ["stable", "system"]: anaconda_dir = _update_conda_packages() print("Upgrading bcbio-nextgen to latest stable version") _set_pip_ssl(anaconda_dir) sudo_cmd = [] if args.upgrade == "stable" else ["sudo"] subprocess.check_call(sudo_cmd + [pip_bin, "install", "-r", REMOTES["requirements"]]) print("Upgrade of bcbio-nextgen code complete.") elif args.upgrade in ["deps"]: _update_conda_packages() else: anaconda_dir = _update_conda_packages() print("Upgrading bcbio-nextgen to latest development version") _set_pip_ssl(anaconda_dir) subprocess.check_call([pip_bin, "install", "git+%s#egg=bcbio-nextgen" % REMOTES["gitrepo"]]) subprocess.check_call([pip_bin, "install", "--upgrade", "--no-deps", "git+%s#egg=bcbio-nextgen" % REMOTES["gitrepo"]]) print("Upgrade of bcbio-nextgen development code complete.") try: _set_matplotlib_default_backend() except OSError: pass if args.tooldir: with bcbio_tmpdir(): print("Upgrading third party tools to latest versions") _symlink_bcbio(args, script="bcbio_nextgen.py") _symlink_bcbio(args, script="bcbio_setup_genome.py") _symlink_bcbio(args, script="bcbio_prepare_samples.py") upgrade_thirdparty_tools(args, REMOTES) print("Third party tools upgrade complete.") if args.toolplus and (args.tooldir or args.upgrade != "skip"): print("Installing additional tools") _install_toolplus(args) if args.install_data: if len(args.aligners) == 0: print("Warning: no aligners provided with `--aligners` flag") if len(args.genomes) == 0: print("Data not installed, no genomes provided with `--genomes` flag") else: with bcbio_tmpdir(): print("Upgrading bcbio-nextgen data files") upgrade_bcbio_data(args, REMOTES) print("bcbio-nextgen data upgrade complete.") if args.isolate and args.tooldir: print("Installation directory not added to current PATH") print(" Add:\n {t}/bin to PATH\n {t}/lib to LD_LIBRARY_PATH\n" " {t}/lib/perl5 to PERL5LIB".format(t=args.tooldir)) save_install_defaults(args) args.datadir = _get_data_dir() _install_container_bcbio_system(args.datadir) print("Upgrade completed successfully.") return args def _set_pip_ssl(anaconda_dir): """Set PIP SSL certificate to installed conda certificate to avoid SSL errors """ if anaconda_dir: cert_file = os.path.join(anaconda_dir, "ssl", "cert.pem") if os.path.exists(cert_file): os.environ["PIP_CERT"] = cert_file def _set_matplotlib_default_backend(): """ matplotlib will try to print to a display if it is available, but don't want to run it in interactive mode. we tried setting the backend to 'Agg'' before importing, but it was still resulting in issues. we replace the existing backend with 'agg' in the default matplotlibrc. This is a hack until we can find a better solution """ if _matplotlib_installed(): import matplotlib matplotlib.use('Agg', force=True) config = matplotlib.matplotlib_fname() with file_transaction(config) as tx_out_file: with open(config) as in_file, open(tx_out_file, "w") as out_file: for line in in_file: if line.split(":")[0].strip() == "backend": out_file.write("backend: agg\n") else: out_file.write(line) def _matplotlib_installed(): try: import matplotlib except ImportError: return False return True def _symlink_bcbio(args, script="bcbio_nextgen.py"): """Ensure a bcbio-nextgen script symlink in final tool directory. """ bcbio_anaconda = os.path.join(os.path.dirname(sys.executable), script) bcbio_final = os.path.join(args.tooldir, "bin", script) sudo_cmd = ["sudo"] if args.sudo else [] if not os.path.exists(bcbio_final): if os.path.lexists(bcbio_final): subprocess.check_call(sudo_cmd + ["rm", "-f", bcbio_final]) subprocess.check_call(sudo_cmd + ["ln", "-s", bcbio_anaconda, bcbio_final]) def _install_container_bcbio_system(datadir): """Install limited bcbio_system.yaml file for setting core and memory usage. Adds any non-specific programs to the exposed bcbio_system.yaml file, only when upgrade happening inside a docker container. """ base_file = os.path.join(datadir, "config", "bcbio_system.yaml") if not os.path.exists(base_file): return expose_file = os.path.join(datadir, "galaxy", "bcbio_system.yaml") expose = set(["memory", "cores", "jvm_opts"]) with open(base_file) as in_handle: config = yaml.load(in_handle) if os.path.exists(expose_file): with open(expose_file) as in_handle: expose_config = yaml.load(in_handle) else: expose_config = {"resources": {}} for pname, vals in config["resources"].iteritems(): expose_vals = {} for k, v in vals.iteritems(): if k in expose: expose_vals[k] = v if len(expose_vals) > 0 and pname not in expose_config["resources"]: expose_config["resources"][pname] = expose_vals with open(expose_file, "w") as out_handle: yaml.safe_dump(expose_config, out_handle, default_flow_style=False, allow_unicode=False) return expose_file def _get_conda_bin(): conda_bin = os.path.join(os.path.dirname(sys.executable), "conda") if os.path.exists(conda_bin): return conda_bin def _default_deploy_args(args): toolplus = {"data": {"bio_nextgen": []}} custom_add = collections.defaultdict(list) for x in args.toolplus: if not x.fname: for k, vs in toolplus.get(x.name, {}).iteritems(): custom_add[k].extend(vs) return {"flavor": "ngs_pipeline_minimal", "custom_add": dict(custom_add), "vm_provider": "novm", "hostname": "localhost", "fabricrc_overrides": {"edition": "minimal", "use_sudo": args.sudo, "keep_isolated": args.isolate, "conda_cmd": _get_conda_bin(), "distribution": args.distribution or "__auto__", "dist_name": "__auto__"}} def _update_conda_packages(): """If installed in an anaconda directory, upgrade conda packages. """ pkgs = ["azure", "biopython", "boto", "cnvkit", "cpat", "cython", "gffutils", "ipython", "joblib", "lxml", "matplotlib", "msgpack-python", "nose", "numpy", "openssl", "pandas", "patsy", "pycrypto", "pip", "progressbar", "python-dateutil", "pybedtools", "pysam", "pyvcf", "pyyaml", "pyzmq", "reportlab", "requests", "scikit-learn", "scipy", "seaborn", "setuptools", "sqlalchemy", "statsmodels", "toolz", "tornado"] channels = ["-c", "bcbio"] conda_bin = _get_conda_bin() if conda_bin: subprocess.check_call([conda_bin, "install", "--yes", "numpy"]) subprocess.check_call([conda_bin, "install", "--yes"] + channels + pkgs) return os.path.dirname(os.path.dirname(conda_bin)) def _get_data_dir(): base_dir = os.path.realpath(os.path.dirname(os.path.dirname(sys.executable))) if "anaconda" not in os.path.basename(base_dir) and "virtualenv" not in os.path.basename(base_dir): raise ValueError("Cannot update data for bcbio-nextgen not installed by installer.\n" "bcbio-nextgen needs to be installed inside an anaconda environment \n" "located in the same directory as `galaxy` `genomes` and `gemini_data` directories.") return os.path.dirname(base_dir) def get_gemini_dir(data=None): try: data_dir = _get_data_dir() return os.path.join(data_dir, "gemini_data") except ValueError: if data: galaxy_dir = dd.get_galaxy_dir(data) data_dir = os.path.realpath(os.path.dirname(os.path.dirname(galaxy_dir))) return os.path.join(data_dir, "gemini_data") else: return None def upgrade_bcbio_data(args, remotes): """Upgrade required genome data files in place. """ data_dir = _get_data_dir() s = _default_deploy_args(args) s["actions"] = ["setup_biodata"] tooldir = args.tooldir or get_defaults().get("tooldir") if tooldir: s["fabricrc_overrides"]["system_install"] = tooldir s["fabricrc_overrides"]["data_files"] = data_dir s["fabricrc_overrides"]["galaxy_home"] = os.path.join(data_dir, "galaxy") cbl = get_cloudbiolinux(remotes) s["genomes"] = _get_biodata(cbl["biodata"], args) sys.path.insert(0, cbl["dir"]) cbl_deploy = __import__("cloudbio.deploy", fromlist=["deploy"]) cbl_deploy.deploy(s) _upgrade_genome_resources(s["fabricrc_overrides"]["galaxy_home"], remotes["genome_resources"]) _upgrade_snpeff_data(s["fabricrc_overrides"]["galaxy_home"], args, remotes) _upgrade_vep_data(s["fabricrc_overrides"]["galaxy_home"], tooldir) toolplus = set([x.name for x in args.toolplus]) if 'data' in toolplus: gemini = os.path.join(os.path.dirname(sys.executable), "gemini") extras = [] if "cadd" in toolplus: extras.extend(["--extra", "cadd_score"]) subprocess.check_call([gemini, "update", "--dataonly"] + extras) def _upgrade_genome_resources(galaxy_dir, base_url): """Retrieve latest version of genome resource YAML configuration files. """ for dbkey, ref_file in genome.get_builds(galaxy_dir): # Check for a remote genome resources file remote_url = base_url % dbkey requests.packages.urllib3.disable_warnings() r = requests.get(remote_url, verify=False) if r.status_code == requests.codes.ok: local_file = os.path.join(os.path.dirname(ref_file), os.path.basename(remote_url)) if os.path.exists(local_file): with open(local_file) as in_handle: local_config = yaml.load(in_handle) remote_config = yaml.load(r.text) needs_update = remote_config["version"] > local_config.get("version", 0) if needs_update: shutil.move(local_file, local_file + ".old%s" % local_config.get("version", 0)) else: needs_update = True if needs_update: print("Updating %s genome resources configuration" % dbkey) with open(local_file, "w") as out_handle: out_handle.write(r.text) def _upgrade_vep_data(galaxy_dir, tooldir): for dbkey, ref_file in genome.get_builds(galaxy_dir): effects.prep_vep_cache(dbkey, ref_file, tooldir) def _upgrade_snpeff_data(galaxy_dir, args, remotes): """Install or upgrade snpEff databases, localized to reference directory. """ for dbkey, ref_file in genome.get_builds(galaxy_dir): resource_file = os.path.join(os.path.dirname(ref_file), "%s-resources.yaml" % dbkey) if os.path.exists(resource_file): with open(resource_file) as in_handle: resources = yaml.load(in_handle) snpeff_db, snpeff_base_dir = effects.get_db({"genome_resources": resources, "reference": {"fasta": {"base": ref_file}}}) if snpeff_db: snpeff_db_dir = os.path.join(snpeff_base_dir, snpeff_db) if os.path.exists(snpeff_db_dir) and _is_old_database(snpeff_db_dir, args): shutil.rmtree(snpeff_db_dir) if not os.path.exists(snpeff_db_dir): print("Installing snpEff database %s in %s" % (snpeff_db, snpeff_base_dir)) dl_url = remotes["snpeff_dl_url"].format( snpeff_ver=effects.snpeff_version(args).replace(".", "_"), genome=snpeff_db) dl_file = os.path.basename(dl_url) with utils.chdir(snpeff_base_dir): subprocess.check_call(["wget", "-c", "-O", dl_file, dl_url]) subprocess.check_call(["unzip", dl_file]) os.remove(dl_file) dl_dir = os.path.join(snpeff_base_dir, "data", snpeff_db) os.rename(dl_dir, snpeff_db_dir) os.rmdir(os.path.join(snpeff_base_dir, "data")) def _is_old_database(db_dir, args): """Check for old database versions, supported in snpEff 4.1. """ snpeff_version = effects.snpeff_version(args) if LooseVersion(snpeff_version) >= LooseVersion("4.1"): pred_file = os.path.join(db_dir, "snpEffectPredictor.bin") if not utils.file_exists(pred_file): return True with gzip.open(pred_file) as in_handle: version_info = in_handle.readline().strip().split("\t") program, version = version_info[:2] if not program.lower() == "snpeff" or LooseVersion(snpeff_version) > LooseVersion(version): return True return False def _get_biodata(base_file, args): with open(base_file) as in_handle: config = yaml.load(in_handle) config["install_liftover"] = False config["genome_indexes"] = args.aligners config["genomes"] = [_add_biodata_flags(g, args) for g in config["genomes"] if g["dbkey"] in args.genomes] return config def _add_biodata_flags(g, args): toolplus = set([x.name for x in args.toolplus]) if g["dbkey"] in ["hg19", "GRCh37"]: for flag in ["dbnsfp"]: if flag in toolplus: g[flag] = True return g def upgrade_thirdparty_tools(args, remotes): """Install and update third party tools used in the pipeline. Creates a manifest directory with installed programs on the system. """ s = {"fabricrc_overrides": {"system_install": args.tooldir, "local_install": os.path.join(args.tooldir, "local_install"), "distribution": args.distribution, "conda_cmd": _get_conda_bin(), "use_sudo": args.sudo, "edition": "minimal"}} s = _default_deploy_args(args) s["actions"] = ["install_biolinux"] s["fabricrc_overrides"]["system_install"] = args.tooldir s["fabricrc_overrides"]["local_install"] = os.path.join(args.tooldir, "local_install") cbl = get_cloudbiolinux(remotes) sys.path.insert(0, cbl["dir"]) cbl_deploy = __import__("cloudbio.deploy", fromlist=["deploy"]) cbl_deploy.deploy(s) manifest_dir = os.path.join(_get_data_dir(), "manifest") print("Creating manifest of installed packages in %s" % manifest_dir) cbl_manifest = __import__("cloudbio.manifest", fromlist=["manifest"]) if os.path.exists(manifest_dir): for fname in os.listdir(manifest_dir): if not fname.startswith("toolplus"): os.remove(os.path.join(manifest_dir, fname)) cbl_manifest.create(manifest_dir, args.tooldir) def _install_toolplus(args): """Install additional tools we cannot distribute, updating local manifest. """ manifest_dir = os.path.join(_get_data_dir(), "manifest") toolplus_manifest = os.path.join(manifest_dir, "toolplus-packages.yaml") system_config = os.path.join(_get_data_dir(), "galaxy", "bcbio_system.yaml") toolplus_dir = os.path.join(_get_data_dir(), "toolplus") for tool in args.toolplus: if tool.name == "data": _install_gemini(args.tooldir, _get_data_dir(), args) elif tool.name == "kraken": _install_kraken_db(_get_data_dir(), args) elif tool.name in set(["gatk", "mutect"]): _install_gatk_jar(tool.name, tool.fname, toolplus_manifest, system_config, toolplus_dir) elif tool.name in set(["protected"]): # back compatibility pass elif tool.name in set(["cadd", "dbnsfp"]): # larger data targets pass else: raise ValueError("Unexpected toolplus argument: %s %s" (tool.name, tool.fname)) def get_gatk_jar_version(name, fname): if name == "gatk": return broad.get_gatk_version(fname) elif name == "mutect": return broad.get_mutect_version(fname) else: raise ValueError("Unexpected GATK input: %s" % name) def _install_gatk_jar(name, fname, manifest, system_config, toolplus_dir): """Install a jar for GATK or associated tools like MuTect. """ if not fname.endswith(".jar"): raise ValueError("--toolplus argument for %s expects a jar file: %s" % (name, fname)) version = get_gatk_jar_version(name, fname) store_dir = utils.safe_makedir(os.path.join(toolplus_dir, name, version)) shutil.copyfile(fname, os.path.join(store_dir, os.path.basename(fname))) _update_system_file(system_config, name, {"dir": store_dir}) _update_manifest(manifest, name, version) def _update_manifest(manifest_file, name, version): """Update the toolplus manifest file with updated name and version """ if os.path.exists(manifest_file): with open(manifest_file) as in_handle: manifest = yaml.load(in_handle) else: manifest = {} manifest[name] = {"name": name, "version": version} with open(manifest_file, "w") as out_handle: yaml.safe_dump(manifest, out_handle, default_flow_style=False, allow_unicode=False) def _update_system_file(system_file, name, new_kvs): """Update the bcbio_system.yaml file with new resource information. """ bak_file = system_file + ".bak%s" % datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S") shutil.copyfile(system_file, bak_file) with open(system_file) as in_handle: config = yaml.load(in_handle) new_rs = {} for rname, r_kvs in config.get("resources", {}).iteritems(): if rname == name: for k, v in new_kvs.iteritems(): r_kvs[k] = v new_rs[rname] = r_kvs config["resources"] = new_rs with open(system_file, "w") as out_handle: yaml.safe_dump(config, out_handle, default_flow_style=False, allow_unicode=False) def _install_gemini(tooldir, datadir, args): """Install gemini layered on top of bcbio-nextgen, sharing anaconda framework. """ # check if we have an up to date version, upgrading if needed gemini = os.path.join(os.path.dirname(sys.executable), "gemini") if os.path.exists(gemini): vurl = "https://raw.github.com/arq5x/gemini/master/requirements.txt" requests.packages.urllib3.disable_warnings() r = requests.get(vurl, verify=False) for line in r.text.split(): if line.startswith(("gemini=", "gemini>")): latest_version = line.split("=")[-1].split(">")[-1] cur_version = subprocess.check_output([gemini, "-v"], stderr=subprocess.STDOUT).strip().split()[-1] if LooseVersion(latest_version) > LooseVersion(cur_version): subprocess.check_call([gemini, "update"]) # install from scratch inside existing Anaconda python else: url = "https://raw.github.com/arq5x/gemini/master/gemini/scripts/gemini_install.py" script = os.path.basename(url) subprocess.check_call(["wget", "-O", script, url, "--no-check-certificate"]) cmd = [sys.executable, "-Es", script, tooldir, datadir, "--notools", "--nodata", "--sharedpy"] if not args.sudo: cmd.append("--nosudo") subprocess.check_call(cmd) os.remove(script) def _install_kraken_db(datadir, args): """Install kraken minimal DB in genome folder. """ kraken = os.path.join(datadir, "genomes/kraken") url = "https://ccb.jhu.edu/software/kraken/dl/minikraken.tgz" compress = os.path.join(kraken, os.path.basename(url)) base, ext = utils.splitext_plus(os.path.basename(url)) db = os.path.join(kraken, base) tooldir = args.tooldir or get_defaults()["tooldir"] requests.packages.urllib3.disable_warnings() last_mod = urllib.urlopen(url).info().getheader('Last-Modified') last_mod = dateutil.parser.parse(last_mod).astimezone(dateutil.tz.tzutc()) if os.path.exists(os.path.join(tooldir, "bin", "kraken")): if not os.path.exists(db): is_new_version = True else: cur_file = glob.glob(os.path.join(kraken, "minikraken_*"))[0] cur_version = datetime.datetime.utcfromtimestamp(os.path.getmtime(cur_file)) is_new_version = last_mod.date() > cur_version.date() if is_new_version: shutil.move(cur_file, cur_file.replace('minikraken', 'old')) if not os.path.exists(kraken): utils.safe_makedir(kraken) if is_new_version: if not os.path.exists(compress): subprocess.check_call(["wget", "-O", compress, url, "--no-check-certificate"]) cmd = ["tar", "-xzvf", compress, "-C", kraken] subprocess.check_call(cmd) last_version = glob.glob(os.path.join(kraken, "minikraken_*")) utils.symlink_plus(os.path.join(kraken, last_version[0]), os.path.join(kraken, "minikraken")) utils.remove_safe(compress) else: print "You have the latest version %s." % last_mod else: raise argparse.ArgumentTypeError("kraken not installed in tooldir %s." % os.path.join(tooldir, "bin", "kraken")) # ## Store a local configuration file with upgrade details def _get_install_config(): """Return the YAML configuration file used to store upgrade information. """ try: data_dir = _get_data_dir() except ValueError: return None config_dir = utils.safe_makedir(os.path.join(data_dir, "config")) return os.path.join(config_dir, "install-params.yaml") def save_install_defaults(args): """Save installation information to make future upgrades easier. """ install_config = _get_install_config() if install_config is None: return if utils.file_exists(install_config): with open(install_config) as in_handle: cur_config = yaml.load(in_handle) else: cur_config = {} if args.tooldir: cur_config["tooldir"] = args.tooldir cur_config["sudo"] = args.sudo cur_config["isolate"] = args.isolate for attr in ["genomes", "aligners"]: if not cur_config.get(attr): cur_config[attr] = [] for x in getattr(args, attr): if x not in cur_config[attr]: cur_config[attr].append(x) # toolplus -- save non-filename inputs attr = "toolplus" if not cur_config.get(attr): cur_config[attr] = [] for x in getattr(args, attr): if not x.fname: if x.name not in cur_config[attr]: cur_config[attr].append(x.name) with open(install_config, "w") as out_handle: yaml.safe_dump(cur_config, out_handle, default_flow_style=False, allow_unicode=False) def add_install_defaults(args): """Add any saved installation defaults to the upgrade. """ def _has_data_toolplus(args): return len([x for x in args.toolplus if x.name not in ["gatk", "mutect"]]) > 0 # Ensure we install data if we've specified any secondary installation targets if len(args.genomes) > 0 or len(args.aligners) > 0 or _has_data_toolplus(args): args.install_data = True install_config = _get_install_config() if install_config is None or not utils.file_exists(install_config): return args with open(install_config) as in_handle: default_args = yaml.load(in_handle) # if we are upgrading to development, also upgrade the tools if args.upgrade in ["development"]: args.tools = True if args.tools and args.tooldir is None: if "tooldir" in default_args: args.tooldir = str(default_args["tooldir"]) else: raise ValueError("Default tool directory not yet saved in config defaults. " "Specify the '--tooldir=/path/to/tools' to upgrade tools. " "After a successful upgrade, the '--tools' parameter will " "work for future upgrades.") for attr in ["genomes", "aligners", "toolplus"]: for x in default_args.get(attr, []): x = Tool(x, None) if attr == "toolplus" else str(x) new_val = getattr(args, attr) if x not in getattr(args, attr): new_val.append(x) setattr(args, attr, new_val) if "sudo" in default_args and args.sudo is not False: args.sudo = default_args["sudo"] if "isolate" in default_args and args.isolate is not True: args.isolate = default_args["isolate"] return args def get_defaults(): install_config = _get_install_config() if install_config is None or not utils.file_exists(install_config): return {} with open(install_config) as in_handle: return yaml.load(in_handle) def _check_toolplus(x): """Parse options for adding non-standard/commercial tools like GATK and MuTecT. """ std_choices = set(["data", "cadd", "dbnsfp", "kraken"]) if x in std_choices: return Tool(x, None) elif "=" in x and len(x.split("=")) == 2: name, fname = x.split("=") fname = os.path.normpath(os.path.realpath(fname)) if not os.path.exists(fname): raise argparse.ArgumentTypeError("Unexpected --toolplus argument for %s. File does not exist: %s" % (name, fname)) return Tool(name, fname) else: raise argparse.ArgumentTypeError("Unexpected --toolplus argument. Expect toolname=filename.") def add_subparser(subparsers): parser = subparsers.add_parser("upgrade", help="Install or upgrade bcbio-nextgen") parser.add_argument("--tooldir", help="Directory to install 3rd party software tools. Leave unspecified for no tools", type=lambda x: (os.path.abspath(os.path.expanduser(x))), default=None) parser.add_argument("--tools", help="Boolean argument specifying upgrade of tools. Uses previously saved install directory", action="store_true", default=False) parser.add_argument("-u", "--upgrade", help="Code version to upgrade", choices=["stable", "development", "system", "deps", "skip"], default="skip") parser.add_argument("--toolplus", help="Specify additional tool categories to install", action="append", default=[], type=_check_toolplus) parser.add_argument("--genomes", help="Genomes to download", action="append", default=[], choices=SUPPORTED_GENOMES) parser.add_argument("--aligners", help="Aligner indexes to download", action="append", default=[], choices=SUPPORTED_INDEXES) parser.add_argument("--data", help="Upgrade data dependencies", dest="install_data", action="store_true", default=False) parser.add_argument("--sudo", help="Use sudo for the installation, enabling install of system packages", dest="sudo", action="store_true", default=False) parser.add_argument("--isolate", help="Created an isolated installation without PATH updates", dest="isolate", action="store_true", default=False) parser.add_argument("--distribution", help="Operating system distribution", default="", choices=["ubuntu", "debian", "centos", "scientificlinux", "macosx"]) return parser def get_cloudbiolinux(remotes): base_dir = os.path.join(os.getcwd(), "cloudbiolinux") if not os.path.exists(base_dir): subprocess.check_call(["git", "clone", remotes["cloudbiolinux"]]) return {"biodata": os.path.join(base_dir, "config", "biodata.yaml"), "dir": base_dir} @contextlib.contextmanager def bcbio_tmpdir(): orig_dir = os.getcwd() work_dir = os.path.join(os.getcwd(), "tmpbcbio-install") if not os.path.exists(work_dir): os.makedirs(work_dir) os.chdir(work_dir) yield work_dir os.chdir(orig_dir) shutil.rmtree(work_dir)
# Copyright 2018 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Processes raw data to build train, validation and test set. Runs either locally or in Google Cloud DataFlow. Performs the following operations: - reads data from BigQuery - adds hash key value to each row - scales data - shuffles and splits data in train / validation / test sets - oversamples train data - stores data as TFRecord - splits and stores test data into labels and features files. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse from datetime import datetime import json import os import posixpath import random import sys import apache_beam as beam from apache_beam.io import tfrecordio import tensorflow as tf import tensorflow_transform as tft import tensorflow_transform.beam.impl as beam_impl from tensorflow_transform.coders import example_proto_coder from tensorflow_transform.tf_metadata import dataset_metadata from tensorflow_transform.tf_metadata import dataset_schema from constants import constants from utils.datasettype import DatasetType def preprocessing_fn(inputs): """Performs scaling of input features. Args: inputs: Dictionary of input columns mapping strings to `Tensor` or `SparseTensor`s. Returns: Dictionary of output columns mapping strings to `Tensor` or `SparseTensor`. """ output = {} for c in constants.FEATURE_COLUMNS: output[c] = tft.scale_to_0_1(inputs[c]) output[constants.LABEL_COLUMN] = inputs[constants.LABEL_COLUMN] output[constants.KEY_COLUMN] = inputs[constants.KEY_COLUMN] return output @beam.ptransform_fn def check_size(p, name, path): """Performs checks on the input pipeline and stores stats in specfied path. Checks performed: counts rows and derives class distribution. Args: p: PCollection, input pipeline. name: string, unique identifier for the beam step. path: string: path to store stats. Returns: PCollection """ class _Combine(beam.CombineFn): """Counts and take the average of positive classes in the pipeline.""" def create_accumulator(self): return (0.0, 0.0) def add_input(self, sum_count, inputs): (s, count) = sum_count return s + inputs, count + 1 def merge_accumulators(self, accumulators): sums, counts = zip(*accumulators) return sum(sums), sum(counts) # We should not consider the case count == 0 as an error (class initialized # with count == 0). def extract_output(self, sum_count): (s, count) = sum_count return count, (1.0 * s / count) if count else float('NaN') return (p | 'CheckMapTo_1_{}'.format(name) >> beam.Map(lambda x: x[constants.LABEL_COLUMN]) | 'CheckSum_{}'.format(name) >> beam.CombineGlobally(_Combine()) | 'CheckRecord_{}'.format(name) >> beam.io.WriteToText( '{}.txt'.format(path))) @beam.ptransform_fn def shuffle_data(p): """Shuffles data from PCollection. Args: p: PCollection. Returns: PCollection of shuffled data. """ class _AddRandomKey(beam.DoFn): def process(self, element): yield (random.random(), element) shuffled_data = ( p | 'PairWithRandom' >> beam.ParDo(_AddRandomKey()) | 'GroupByRandom' >> beam.GroupByKey() | 'DropRandom' >> beam.FlatMap(lambda (k, vs): vs)) return shuffled_data @beam.ptransform_fn def randomly_split(p, train_size, validation_size, test_size): """Randomly splits input pipeline in three sets based on input ratio. Args: p: PCollection, input pipeline. train_size: float, ratio of data going to train set. validation_size: float, ratio of data going to validation set. test_size: float, ratio of data going to test set. Returns: Tuple of PCollection. Raises: ValueError: Train validation and test sizes don`t add up to 1.0. """ if train_size + validation_size + test_size != 1.0: raise ValueError('Train validation and test sizes don`t add up to 1.0.') class _SplitData(beam.DoFn): def process(self, element): r = random.random() if r < test_size: yield beam.pvalue.TaggedOutput(DatasetType.TEST.name, element) elif r < 1 - train_size: yield beam.pvalue.TaggedOutput(DatasetType.VAL.name, element) else: yield element split_data = ( p | 'SplitData' >> beam.ParDo(_SplitData()).with_outputs( DatasetType.VAL.name, DatasetType.TEST.name, main=DatasetType.TRAIN.name)) split_data_id = {} for k in [DatasetType.TRAIN, DatasetType.VAL, DatasetType.TEST]: split_data_id[k] = split_data[k.name] return split_data_id @beam.ptransform_fn def read_data(p, bq_table, project_id): """Inputs raw data from BigQuery table into beam pipeline. Args: p: PCollection, pipeline to input data. bq_table: string, name of table to read data from. project_id: string, GCP project id. Returns: PCollection. """ column_list = ', '.join(constants.FEATURE_COLUMNS + [constants.LABEL_COLUMN]) query = 'SELECT {} FROM [{}:{}.{}]'.format(column_list, project_id, constants.BQ_DATASET, bq_table) data = ( p | 'ReadData' >> beam.io.Read( beam.io.BigQuerySource(query=query, use_standard_sql=False))) return data def make_input_schema(): """Builds the schema of the data read from BigQuery. Appends key column to schema for inference. Returns: A dictionary mapping keys of column names to `tf.FixedLenFeature` instances. """ feature_spec = {} for c in constants.FEATURE_COLUMNS: feature_spec[c] = tf.FixedLenFeature(shape=[], dtype=tf.float32) feature_spec[constants.LABEL_COLUMN] = tf.FixedLenFeature( shape=[], dtype=tf.int64) feature_spec[constants.KEY_COLUMN] = tf.FixedLenFeature( shape=[], dtype=tf.int64) return dataset_schema.from_feature_spec(feature_spec) @beam.ptransform_fn def oversampling(p): """Oversamples the positive class elements contained in the input pipeline. Computes the current class distribution and re-sample positive class to ensure a class distribution close to 50% / 50%. Samples each positive class item w/ bernouilli distribution approximated with normal distribution (mean=ratio, var=ratio, where ratio is the factor by which we want to increase the number of positive samples). Args: p: PCollection. Returns: PCollection of re-balanced elements. Raises: ValueError: No positive class items found in pipeline. """ # Computes percentage of positive class to use as side input in main pipeline. percentage = ( p | 'ReduceToClass' >> beam.Map(lambda x: 1.0 * x[constants.LABEL_COLUMN]) | beam.CombineGlobally(beam.combiners.MeanCombineFn())) class _Sample(beam.DoFn): """DoFn that performs resampling element by element. Attributes: process: Function performing the resampling at element level. """ def process(self, element, percent_positive): if not percent_positive: raise ValueError('No positive class items found in pipeline.') ratio = 1.0 / percent_positive n = ( max(int(random.gauss(mu=ratio, sigma=ratio**0.5)), 0) if element[constants.LABEL_COLUMN] else 1) for _ in range(n): yield element proc = ( p | 'DuplicateItemAndFlatten' >> beam.ParDo( _Sample(), percent_positive=beam.pvalue.AsSingleton(percentage))) return proc @beam.ptransform_fn def store_transformed_data(data, schema, path, name=''): """Stores data from input pipeline into TFRecord in the specified path. Args: data: `PCollection`, input pipeline. schema: `DatasetMetadata` object, describes schema of the input pipeline. path: string, where to write output. name: string: name describing pipeline to be written. Returns: PCollection """ p = ( data | 'WriteData{}'.format(name) >> tfrecordio.WriteToTFRecord( path, coder=example_proto_coder.ExampleProtoCoder(schema.schema))) return p @beam.ptransform_fn def split_features_labels(data, label_column, key_column): """Separates features from true labels in input pipeline for future inference. Args: data: PCollection, input pipeline. label_column: string, name of column containing labels. key_column: string, name of column containing keys. Returns: Dictionary mapping the strings 'labels' and 'features' to PCollection objects. """ label_pipeline, features_pipeline = 'labels', 'features' class _SplitFeaturesLabels(beam.DoFn): def process(self, element, label_column, key_column): yield beam.pvalue.TaggedOutput(label_pipeline, { key_column: element[key_column], label_column: element.pop(label_column) }) yield element data |= 'SplitFeaturesLabels' >> beam.ParDo( _SplitFeaturesLabels(), label_column=label_column, key_column=key_column).with_outputs( label_pipeline, main=features_pipeline) return {k: data[k] for k in (label_pipeline, features_pipeline)} class AddHash(beam.DoFn): """DoFn that adds a hash key to each element based on the feature values. Attributes: process: Adds the hash key at the element level. """ def process(self, element, label_column, key_column, dtype): hsh = 0 if dtype == DatasetType.TEST: hsh = [element[k] for k in element if k != label_column] hsh = hash(tuple(hsh)) element.update({key_column: hsh}) yield element def preprocess(p, output_dir, check_path, data_size, bq_table, split_data_path, project_id): """Main processing pipeline reading, processing and storing processed data. Performs the following operations: - reads data from BigQuery - adds hash key value to each row - scales data - shuffles and splits data in train / validation / test sets - oversamples train data - stores data as TFRecord - splits and stores test data into labels and features files Args: p: PCollection, initial pipeline. output_dir: string, path to directory to store output. check_path: string, path to directory to store data checks. data_size: tuple of float, ratio of data going respectively to train, validation and test sets. bq_table: string, name of table to read data from. split_data_path: string, path to directory to store train, validation and test raw datasets. project_id: string, GCP project id. Raises: ValueError: No test dataset found in pipeline output. """ train_size, validation_size, test_size = data_size data = (p | 'ReadData' >> read_data(bq_table=bq_table, project_id=project_id)) _ = data | 'StoreData' >> beam.io.WriteToText( posixpath.join(output_dir, check_path, 'processed_data.txt')) split_data = ( data | 'RandomlySplitData' >> randomly_split( train_size=train_size, validation_size=validation_size, test_size=test_size)) for k in split_data: split_data[k] |= 'AddHash_{}'.format(k.name) >> beam.ParDo( AddHash(), label_column=constants.LABEL_COLUMN, key_column=constants.KEY_COLUMN, dtype=k) # Splits test data into features pipeline and labels pipeline. if DatasetType.TEST not in split_data: raise ValueError('No test dataset found in pipeline output.') test_data = ( split_data.pop(DatasetType.TEST) | 'SplitFeaturesLabels' >> split_features_labels(constants.LABEL_COLUMN, constants.KEY_COLUMN)) # Stores test data features and labels pipeline separately. for k in test_data: _ = ( test_data[k] | 'ParseJsonToString_{}'.format(k) >> beam.Map(json.dumps) | 'StoreSplitData_{}'.format(k) >> beam.io.WriteToText( posixpath.join( output_dir, split_data_path, 'split_data_{}_{}.txt'.format( DatasetType.TEST.name, k)))) meta_data = dataset_metadata.DatasetMetadata(make_input_schema()) transform_fn = ( (split_data[DatasetType.TRAIN], meta_data) | 'AnalyzeTrainDataset' >> beam_impl.AnalyzeDataset(preprocessing_fn)) _ = ( transform_fn | 'WriteTransformFn' >> tft.beam.tft_beam_io.WriteTransformFn( posixpath.join(output_dir, constants.PATH_INPUT_TRANSFORMATION))) _ = ( meta_data | 'WriteInputMetadata' >> tft.beam.tft_beam_io.WriteMetadata( posixpath.join(output_dir, constants.PATH_INPUT_SCHEMA), pipeline=p)) transformed_metadata, transformed_data = {}, {} for k in [DatasetType.TRAIN, DatasetType.VAL]: transformed_data[k], transformed_metadata[k] = ( ((split_data[k], meta_data), transform_fn) | 'Transform{}'.format(k) >> beam_impl.TransformDataset()) transformed_data[DatasetType.TRAIN] = ( transformed_data[DatasetType.TRAIN] | 'OverSampleTraining' >> oversampling()) for k in transformed_data: _ = ( transformed_data[k] | 'ShuffleData{}'.format(k) >> shuffle_data() | 'StoreData{}'.format(k) >> store_transformed_data( schema=transformed_metadata[k], path=posixpath.join(output_dir, constants.PATH_TRANSFORMED_DATA_SPLIT[k]), name=DatasetType(k).name)) for k in transformed_data: _ = ( transformed_data[k] | 'CheckSize{}'.format(k.name) >> check_size( name=DatasetType(k).name, path=posixpath.join(output_dir, check_path, k.name))) def parse_arguments(argv): """Parses execution arguments and replaces default values. Args: argv: Input arguments from sys. Returns: Parsed arguments. """ parser = argparse.ArgumentParser() parser.add_argument( '--bq_table', default='raw_data', help='Name of BigQuery table to read data from.') parser.add_argument( '--check_path', default='check', help='Directory in which to write data checks.') parser.add_argument( '--cloud', default=False, action='store_true', help='Run preprocessing on the cloud.') parser.add_argument( '--output_dir', default='output-{}'.format(datetime.now().strftime('%Y%m%d%H%M%S')), help='Directory in which to write outputs.') parser.add_argument( '--test_size', default=0.15, help='Fraction of data going into test set.') parser.add_argument( '--train_size', default=0.7, help='Fraction of data going into train set.') parser.add_argument( '--validation_size', default=0.15, help='Fraction of data going into validation set.') parser.add_argument( '--split_data_path', default='split_data', help='Directory in which to write data once split.') parser.add_argument( '--project_id', required=True, help='Google Cloud project ID.') parser.add_argument( '--bucket_id', required=True, help='Google Cloud bucket ID.') args, _ = parser.parse_known_args(args=argv[1:]) return args def main(): """Parses execution arguments, creates and runs processing pipeline. Cheks current OS. Posix OS is required for local and GCP paths consistency. Raises: OSError: Posix OS required. ValueError: Train validation and test size dont add up to 1.0. """ if os.name != 'posix': raise OSError('Posix OS required.') args = parse_arguments(sys.argv) if args.train_size + args.validation_size + args.test_size != 1.0: raise ValueError('Train validation and test size dont add up to 1.0.') output_dir = args.output_dir if args.cloud: output_dir = posixpath.join('gs://', args.bucket_id, output_dir) runner = 'DataflowRunner' else: output_dir = posixpath.join('.', output_dir) runner = 'DirectRunner' temp_dir = posixpath.join(output_dir, 'tmp') options = { 'project': args.project_id, 'job_name': '{}-{}'.format(args.project_id, datetime.now().strftime('%Y%m%d%H%M%S')), 'setup_file': posixpath.abspath( posixpath.join(posixpath.dirname(__file__), 'setup.py')), 'temp_location': temp_dir, 'save_main_session': True } pipeline_options = beam.pipeline.PipelineOptions(flags=[], **options) with beam.Pipeline(runner, options=pipeline_options) as p: with beam_impl.Context(temp_dir=temp_dir): preprocess( p=p, output_dir=output_dir, check_path=args.check_path, data_size=(args.train_size, args.validation_size, args.test_size), bq_table=args.bq_table, split_data_path=args.split_data_path, project_id=args.project_id) if __name__ == '__main__': main()
# # Copyright 2011 Ning, Inc. # # Ning 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. # # # Send NetFlow data. # # /!\ nfdump is assumed to be in the path /!\ # # Periodically, every 5 minutes by default, nfcapd will rename the current # file (nfcad.current.<pid>) to nfcapd.%i%02i%02i%02i%02i (year/month/day/hour/minute). # We look for these files, and send them to Scribe or collector. # # A ramfs is strongly encouraged for the data output directory (-l option): # # mkfs -q /dev/ram1 8589934592 # 8 GB # mkdir -p /mnt/nfdump # mount /dev/ram1 /mnt/nfdump # import argparse import base64 import glob import logging import os import socket import subprocess import sys import time import threading from scribe import scribe import thrift from thrift.transport import TTransport, TSocket from thrift.protocol import TBinaryProtocol from netflow.ttypes import Netflow log = logging.getLogger('nfcapd2coll') class NetflowDumpSender(threading.Thread): def __init__(self, threadNb, infile, scribeHost, scribePort): threading.Thread.__init__(self) self.infile = infile self.scribeHost = scribeHost self.scribePort = scribePort self.events = [] def run(self): # Output data as CSV into csvOutput nfdump = subprocess.Popen(['nfdump', '-q', '-r', self.infile, '-o', 'csv'], stdout=subprocess.PIPE) csvOutput = nfdump.communicate()[0] self.__parse_data(csvOutput) try: os.remove(self.infile) log.debug('Deleted file: %s', self.infile) except os.error, err: log.error('Unable to delete file [%s]: %s', self.infile, err) log.info('Done with file %s - start sending it', self.infile) self.__send_events() def __parse_data(self, data): """Given CSV generated by nfdump, create the associated events Keyword arguments: data -- CSV output of nfdump """ for line in data.split('\n'): payload = line.split(',') if len(payload) > 1: self.events.append(self.__create_event(payload)) log.info('Created %d events from file %s', len(self.events), self.infile) def __create_event(self, netflowPayload): """Create Netflow event from a dump line Keyword arguments: netflowPayload -- tuple containing all Netflow fields """ transportOut = TTransport.TMemoryBuffer() protocolOut = TBinaryProtocol.TBinaryProtocol(transportOut) # The first field looks like: 2004-07-11 10:31:40 try: msgDate = time.mktime(time.strptime(netflowPayload[0], "%Y-%m-%d %H:%M:%S")) except ValueError, err: log.info('Ignoring bad line from file %s: %s', self.infile, netflowPayload) return None except AttributeError, err: log.info('Ignoring bad line from file %s: %s', self.infile, netflowPayload) return None timeInMilliSinceEpoch = msgDate * 1000 netflow = Netflow(timeInMilliSinceEpoch, netflowPayload[0], netflowPayload[1], netflowPayload[2], netflowPayload[3], netflowPayload[4], netflowPayload[5], netflowPayload[6], netflowPayload[7], netflowPayload[8], netflowPayload[9], netflowPayload[10], netflowPayload[11], netflowPayload[12], netflowPayload[13], netflowPayload[14], netflowPayload[15], netflowPayload[16], netflowPayload[17], netflowPayload[18], netflowPayload[19], netflowPayload[20], netflowPayload[21], netflowPayload[22], netflowPayload[23], netflowPayload[24], netflowPayload[25], netflowPayload[26], netflowPayload[27], netflowPayload[28], netflowPayload[29], netflowPayload[30], netflowPayload[31], netflowPayload[32], netflowPayload[33], netflowPayload[34], netflowPayload[35], netflowPayload[36], netflowPayload[37], netflowPayload[38], netflowPayload[39], netflowPayload[40], netflowPayload[41]) netflow.write(protocolOut) netflowInBytes = transportOut.getvalue() log.debug('Created: %s', str(netflow)) return scribe.LogEntry("Netflow", str(timeInMilliSinceEpoch) + ":" + base64.b64encode(netflowInBytes)) def __send_events(self): """Send all events """ socket = TSocket.TSocket(host=self.scribeHost, port=self.scribePort) transport = TTransport.TFramedTransport(socket) protocol = TBinaryProtocol.TBinaryProtocol(trans=transport, strictRead=False, strictWrite=False) client = scribe.Client(iprot=protocol, oprot=protocol) transport.open() log.info('Sending %d messages from file %s to %s:%d', len(self.events), self.infile, self.scribeHost, self.scribePort) result = client.Log(messages=self.events) transport.close() return result def generate_netflow_events_from_dumps(directory, scribeHost, scribePort): """Given a directory of nfcapd files, create events for all rotated files (not current one). Parsed files are deleted. Keyword arguments: directory -- directory containing dumps scribeHost -- Scribe server to talk to scribePort -- Scribe server's port """ threads = [] # The files look like nfcapd.201011021335 # We don't use nfdump -R to delete processed files as we go. # Given a day of data, send by batches (limit memory) for i in range(10): for j in range(10): # nfcapd.201105050800 for file in glob.glob(os.path.join(directory, 'nfcapd.????????'+str(i)+str(j)+'??')): log.info('Processing file: %s', file) sender = NetflowDumpSender(1 + len(threads), file, scribeHost, scribePort) threads.append(sender) sender.start() log.info('Parsed %s, created %d threads', directory, len(threads)) for thread in threads: thread.join() def main(argv=None): handler = logging.StreamHandler(sys.stdout) log.setLevel(logging.INFO) log.addHandler(handler) log.debug('Logging handler configured') if argv is None: argv = sys.argv parser = argparse.ArgumentParser(description='Extract Netflow events from nfcapd dumps and forward them remotely to Scribe.') parser.add_argument('--directory', required=True, help='Directory of files to parse') parser.add_argument('--scribeHost', required=True, help='Scribe server to connect to') parser.add_argument('--scribePort', required=True, help='Scribe port') args = parser.parse_args() try: directory, scribeHost, scribePort = args.directory, args.scribeHost, int(args.scribePort) log.info('Looking for files in %s, sending events to %s:%d', directory, scribeHost, scribePort) generate_netflow_events_from_dumps(directory, scribeHost, scribePort) except thrift.transport.TTransport.TTransportException, err: log.error('Unable to connect to Scribe: %s', err) if __name__ == "__main__": sys.exit(main())
#!/usr/bin/env python from __future__ import print_function import re import sys import os import os.path from optparse import OptionParser import pysam readKeyRe = re.compile('(.*)\s[1-2](.*)') readNumRe = re.compile('.*\s([1-2]).*') # upper and lower limit of the paired reads length upperLimit = 2000 lowerLimit = 0 # [*] Log file Specification # # Symbol Description # ------------------------------------------------- # ! Error lines # < Low score alignments # = Pairs with more than one best score # ~ Read pair mapped on the same strand # ? Segment length out of reasonable range # @ Mapped positions overlapped # READ_ERROR = '!' READ_LOW_SCORE = '<' READ_MULTI_BEST = '=' READ_WRONG_CHROM = '~' READ_WRONG_SIZE = '?' READ_OVERLAPPED = '@' # sort bam file by qname # use pysam sort interface def SortSam(inBam, outBam): pysam.sort("-n", inBam, outBam) def ScoreByCigar(cigar): totalCount = 0 matchCount = 0 for tag in cigar : if(tag[0] == 0): matchCount += tag[1] totalCount += tag[1] if(totalCount == 0): return -1 return int(round(100.0 * matchCount / totalCount)) def ReadPairScoreByCigar(cigar1, cigar2): return ScoreByCigar(cigar1) + ScoreByCigar(cigar2) def ReadPairLen(read1, read2): if(not (read1 and read2)): return -1 return (read2.pos + read2.query_length - read1.pos) # Unique Single reads # # dictSingle structure: # dictSingle = {"key1": [read1, read2, ...], "key2": [read1, read2, ...]} # # Unique Strategy: # # 1. For reads with the same qname, keep the alignment with the highest score # def UniqueSingleReads(dictSingle, strictMode, outFile, logFile): count = 0 if(len(dictSingle) <= 0): return 0 for reads in dictSingle.itervalues(): bestScore = -1 bestReads = [] for read in reads: score = ScoreByCigar(read.cigar) if(score > bestScore): bestScore = score for bestRead in bestReads : # write read to log file logMsg = READ_LOW_SCORE + ' ' + str(bestRead) logFile.write(logMsg + '\n') bestReads = [read] elif(score == bestScore): bestReads += [read] else: logMsg = READ_LOW_SCORE + ' ' + str(read) logFile.write(logMsg + '\n') # write best reads bestReadCount = len(bestReads) if(bestReadCount <= 0): return 0 elif(bestReadCount == 1): bestRead = bestReads[0] else: if(strictMode): for bestRead in bestReads : logMsg = READ_MULTI_BEST + ' ' + str(bestRead) logFile.write(logMsg + '\n') return 0 else: bestRead = bestReads[0] if(bestRead): outFile.write(bestRead) count += 1 return count # Unique paired reads: # # dictPaired Structure: # dictPaired = {'key1': [read1, read2], 'key2':[read1, read2]} # # Unique Strategy: # # 1. Keep alignment pairs with the highest score. # # 2. Reads are properly mapped (on the same chromsome & on the opposite strand) # # 3. Reads length should be in a proper range # def UniquePairedReads(dictPaired, strictMode, bamFile, outFile, logFile): bestScore = -1 bestPairs = [] pairCount = 0 if(len(dictPaired) <= 0): return 0 for key, pair in dictPaired.iteritems(): # pairs are properly mapped if(not pair[0] and not pair[1]): logMsg = READ_ERROR + ' ' + key logFile.write(logMsg + '\n') continue elif(not pair[0] and pair[1]): logMsg = READ_ERROR + ' ' + str(pair[1]) logFile.write(logMsg + '\n') continue elif(pair[0] and not pair[1]): logMsg = READ_ERROR + ' ' + str(pair[0]) logFile.write(logMsg + '\n') continue # paired reads on the same chromsome if(bamFile.getrname(pair[0].rname) != bamFile.getrname(pair[1].rname)): logMsg = READ_WRONG_CHROM + ' ' + str(pair[0]) logFile.write(logMsg + '\n') logMsg = READ_WRONG_CHROM + ' ' + str(pair[1]) logFile.write(logMsg + '\n') continue # pair size pairLen = ReadPairLen(pair[0], pair[1]) if(pairLen < lowerLimit or pairLen > upperLimit): logMsg = READ_WRONG_SIZE + ' ' + str(pair[0]) logFile.write(logMsg + '\n') logMsg = READ_WRONG_SIZE + ' ' + str(pair[1]) logFile.write(logMsg + '\n') continue # pair score score = ReadPairScoreByCigar(pair[0].cigar, pair[1].cigar) if(score > bestScore): bestScore = score for bestPair in bestPairs: logMsg = READ_LOW_SCORE + ' ' + str(bestPair[0]) logFile.write(logMsg + '\n') logMsg = READ_LOW_SCORE + ' ' + str(bestPair[1]) logFile.write(logMsg + '\n') bestPairs = [pair] elif(score == bestScore): bestPairs += [pair] else: logMsg = READ_LOW_SCORE + ' ' + str(pair[0]) logFile.write(logMsg + '\n') logMsg = READ_LOW_SCORE + ' ' + str(pair[1]) logFile.write(logMsg + '\n') # write best pair bestPairCount = len(bestPairs) if(bestPairCount <= 0): return 0 elif(bestPairCount == 1): bestPair = bestPairs[0] else: if(strictMode): for bestPair in bestPairs: logMsg = READ_MULTI_BEST + ' ' + str(bestPair[0]) logFile.write(logMsg + '\n') logMsg = READ_MULTI_BEST + ' ' + str(bestPair[1]) logFile.write(logMsg + '\n') return 0 else: bestPair = bestPairs[0] if(bestPair): outFile.write(bestPair[0]) outFile.write(bestPair[1]) pairCount = 2 return pairCount def main(): # parse the command line options usage = 'usage: %prog [options] input.bam -o output.bam' parser = OptionParser(usage=usage, version='%prog version 0.1.0') parser.add_option('-o', '--output-file', dest='outputfile', help='write the result to output file') parser.add_option('-s', '--sort', action="store_true", dest="sort", default=False, help='sort the input SAM file before further processing') parser.add_option('-k', '--reg-key', dest='regkey', help='regexp to extract the key part of the read qname') parser.add_option('-n', '--reg-num', dest='regnum', help='regexp to extract the number part of the read qname') parser.add_option('-u', '--upper-limit', dest='upperlimit', help='the upper limit of the paired reads length') parser.add_option('-l', '--lower-limit', dest='lowerlimit', help='the lower limit of the paired reads length') parser.add_option('-t', '--strict-mode', action="store_true", dest="strictmode", default=False, help='strict mode') parser.add_option('-q', '--quiet-mode', action="store_true", dest="quiet", default=False, help='supress progress output') (options, args) = parser.parse_args() if(len(args) != 1): parser.print_help() sys.exit(0) inputBamFileName = args[0] baseFileName = os.path.splitext(os.path.basename(inputBamFileName))[0] bamFileName = inputBamFileName rmTemp = False if(options.sort): print('[*] Sorting by QNAME...') bamFileName = 'sorted.' + baseFileName SortSam(inputBamFileName, bamFileName) bamFileName += '.bam' rmTemp = True strictMode = False if(options.strictmode): strictMode = True # Prepare the qname regexp global readKeyRe global readNumRe if(options.regkey): readKeyRe = re.compile(options.regkey) if(options.regnum): readNumRe = re.compile(options.regnum) global upperLimit global lowerLimit if(options.upperlimit): upperLimit = int(options.upperlimit) if(options.lowerlimit): lowerLimit = int(options.lowerlimit) # Load the input bam file print('[*] Initializing...') if(not os.path.exists(bamFileName)): print('error: Failed to open file "', bamFileName, '"') sys.exit(-1) bamFile = pysam.AlignmentFile(bamFileName, "rb") # prepare the output file outputBamFileName = 'unique.' + baseFileName + '.bam' if(options.outputfile): outputBamFileName = options.outputfile outFile = pysam.AlignmentFile(outputBamFileName, 'wb', template = bamFile) logFileName = baseFileName + '.rmdup.log' try: logFile = open(logFileName, 'w') except IOError: print('error: Create log file failed!') sys.exit(-1) # process file readCount = 0 keepedCount = 0 print('[*] Processing...') dictPaired = {} dictSingle = {} currentGroupKey = '' for read in bamFile.fetch(until_eof = True): try: groupKey = ''.join(readKeyRe.findall(read.qname)[0]) except: groupKey = read.qname if(groupKey != currentGroupKey): currentGroupKey = groupKey # handle and write results keepedCount += UniquePairedReads(dictPaired, strictMode, bamFile, outFile, logFile) keepedCount += UniqueSingleReads(dictSingle, strictMode, outFile, logFile) dictPaired.clear() dictSingle.clear() if(read.is_proper_pair): # paired reads chrpos = bamFile.getrname(read.rname).strip() + str(read.pos) chrposNext = bamFile.getrname(read.rnext).strip() + str(read.pnext) if(chrpos < chrposNext): readKey = groupKey + ':' + chrpos + ':' + chrposNext else: readKey = groupKey + ':' + chrposNext + ':' + chrpos if(read.is_reverse): readType = 1 else: readType = 0 if(readKey in dictPaired): if(dictPaired[readKey][readType]): logMsg = READ_OVERLAPPED + ' ' + str(read) logFile.write(logMsg + '\n') else: dictPaired[readKey][readType] = read else: dictPaired[readKey] = [None, None] dictPaired[readKey][readType] = read else: # single read try: readKey = groupKey + ':' + readNumRe.findall(read.qname)[0] except: if(read.is_read1): readNum = '1' else: readNum = '2' readKey = groupKey + ':' + readNum if(readKey in dictSingle): dictSingle[readKey] += [read] else: dictSingle[readKey] = [read] # progress information readCount = readCount + 1 if not options.quiet : sys.stdout.write('\r read #%ld' % (readCount)) sys.stdout.flush() # write the cached alignments keepedCount += UniquePairedReads(dictPaired, strictMode, bamFile, outFile, logFile) keepedCount += UniqueSingleReads(dictSingle, strictMode, outFile, logFile) if(readCount == 0): keepedPercent = 0.0 else: keepedPercent = keepedCount * 1.0 / readCount print('\n %ld (%.2f%%) alignments written.' % (keepedCount, keepedPercent * 100)) # Clear resources bamFile.close() outFile.close() logFile.close() if(rmTemp): os.unlink(bamFileName) print('[*] Complete') if __name__ == '__main__': main()
import base64 from Crypto.PublicKey import RSA from django.http import HttpResponseBadRequest from rest_framework.exceptions import ValidationError from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.routers import APIRootView from rest_framework.viewsets import ViewSet from netbox.api.views import ModelViewSet from secrets import filters from secrets.exceptions import InvalidKey from secrets.models import Secret, SecretRole, SessionKey, UserKey from utilities.utils import count_related from . import serializers ERR_USERKEY_MISSING = "No UserKey found for the current user." ERR_USERKEY_INACTIVE = "UserKey has not been activated for decryption." ERR_PRIVKEY_MISSING = "Private key was not provided." ERR_PRIVKEY_INVALID = "Invalid private key." class SecretsRootView(APIRootView): """ Secrets API root view """ def get_view_name(self): return 'Secrets' # # Secret Roles # class SecretRoleViewSet(ModelViewSet): queryset = SecretRole.objects.annotate( secret_count=count_related(Secret, 'role') ) serializer_class = serializers.SecretRoleSerializer filterset_class = filters.SecretRoleFilterSet # # Secrets # class SecretViewSet(ModelViewSet): queryset = Secret.objects.prefetch_related('role', 'tags') serializer_class = serializers.SecretSerializer filterset_class = filters.SecretFilterSet master_key = None def get_serializer_context(self): # Make the master key available to the serializer for encrypting plaintext values context = super().get_serializer_context() context['master_key'] = self.master_key return context def initial(self, request, *args, **kwargs): super().initial(request, *args, **kwargs) if request.user.is_authenticated: # Read session key from HTTP cookie or header if it has been provided. The session key must be provided in # order to encrypt/decrypt secrets. if 'session_key' in request.COOKIES: session_key = base64.b64decode(request.COOKIES['session_key']) elif 'HTTP_X_SESSION_KEY' in request.META: session_key = base64.b64decode(request.META['HTTP_X_SESSION_KEY']) else: session_key = None # We can't encrypt secret plaintext without a session key. if self.action in ['create', 'update'] and session_key is None: raise ValidationError("A session key must be provided when creating or updating secrets.") # Attempt to retrieve the master key for encryption/decryption if a session key has been provided. if session_key is not None: try: sk = SessionKey.objects.get(userkey__user=request.user) self.master_key = sk.get_master_key(session_key) except (SessionKey.DoesNotExist, InvalidKey): raise ValidationError("Invalid session key.") def retrieve(self, request, *args, **kwargs): secret = self.get_object() # Attempt to decrypt the secret if the master key is known if self.master_key is not None: secret.decrypt(self.master_key) serializer = self.get_serializer(secret) return Response(serializer.data) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: # Attempt to decrypt all secrets if the master key is known if self.master_key is not None: secrets = [] for secret in page: secret.decrypt(self.master_key) secrets.append(secret) serializer = self.get_serializer(secrets, many=True) else: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) class GetSessionKeyViewSet(ViewSet): """ Retrieve a temporary session key to use for encrypting and decrypting secrets via the API. The user's private RSA key is POSTed with the name `private_key`. An example: curl -v -X POST -H "Authorization: Token <token>" -H "Accept: application/json; indent=4" \\ --data-urlencode "private_key@<filename>" https://netbox/api/secrets/get-session-key/ This request will yield a base64-encoded session key to be included in an `X-Session-Key` header in future requests: { "session_key": "+8t4SI6XikgVmB5+/urhozx9O5qCQANyOk1MNe6taRf=" } This endpoint accepts one optional parameter: `preserve_key`. If True and a session key exists, the existing session key will be returned instead of a new one. """ permission_classes = [IsAuthenticated] def create(self, request): # Read private key private_key = request.POST.get('private_key', None) if private_key is None: return HttpResponseBadRequest(ERR_PRIVKEY_MISSING) # Validate user key try: user_key = UserKey.objects.get(user=request.user) except UserKey.DoesNotExist: return HttpResponseBadRequest(ERR_USERKEY_MISSING) if not user_key.is_active(): return HttpResponseBadRequest(ERR_USERKEY_INACTIVE) # Validate private key master_key = user_key.get_master_key(private_key) if master_key is None: return HttpResponseBadRequest(ERR_PRIVKEY_INVALID) try: current_session_key = SessionKey.objects.get(userkey__user_id=request.user.pk) except SessionKey.DoesNotExist: current_session_key = None if current_session_key and request.GET.get('preserve_key', False): # Retrieve the existing session key key = current_session_key.get_session_key(master_key) else: # Create a new SessionKey SessionKey.objects.filter(userkey__user=request.user).delete() sk = SessionKey(userkey=user_key) sk.save(master_key=master_key) key = sk.key # Encode the key using base64. (b64decode() returns a bytestring under Python 3.) encoded_key = base64.b64encode(key).decode() # Craft the response response = Response({ 'session_key': encoded_key, }) # If token authentication is not in use, assign the session key as a cookie if request.auth is None: response.set_cookie('session_key', value=encoded_key) return response class GenerateRSAKeyPairViewSet(ViewSet): """ This endpoint can be used to generate a new RSA key pair. The keys are returned in PEM format. { "public_key": "<public key>", "private_key": "<private key>" } """ permission_classes = [IsAuthenticated] def list(self, request): # Determine what size key to generate key_size = request.GET.get('key_size', 2048) if key_size not in range(2048, 4097, 256): key_size = 2048 # Export RSA private and public keys in PEM format key = RSA.generate(key_size) private_key = key.exportKey('PEM') public_key = key.publickey().exportKey('PEM') return Response({ 'private_key': private_key, 'public_key': public_key, })
# Copyright 2013, Big Switch Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from mox import IsA # noqa from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse_lazy from django import http from openstack_horizon import api from openstack_horizon.api import fwaas from openstack_horizon.test import helpers as test class FirewallTests(test.TestCase): class AttributeDict(dict): def __getattr__(self, attr): return self[attr] def __setattr__(self, attr, value): self[attr] = value DASHBOARD = 'project' INDEX_URL = reverse_lazy('horizon:%s:firewalls:index' % DASHBOARD) ADDRULE_PATH = 'horizon:%s:firewalls:addrule' % DASHBOARD ADDPOLICY_PATH = 'horizon:%s:firewalls:addpolicy' % DASHBOARD ADDFIREWALL_PATH = 'horizon:%s:firewalls:addfirewall' % DASHBOARD RULE_DETAIL_PATH = 'horizon:%s:firewalls:ruledetails' % DASHBOARD POLICY_DETAIL_PATH = 'horizon:%s:firewalls:policydetails' % DASHBOARD FIREWALL_DETAIL_PATH = 'horizon:%s:firewalls:firewalldetails' % DASHBOARD UPDATERULE_PATH = 'horizon:%s:firewalls:updaterule' % DASHBOARD UPDATEPOLICY_PATH = 'horizon:%s:firewalls:updatepolicy' % DASHBOARD UPDATEFIREWALL_PATH = 'horizon:%s:firewalls:updatefirewall' % DASHBOARD INSERTRULE_PATH = 'horizon:%s:firewalls:insertrule' % DASHBOARD REMOVERULE_PATH = 'horizon:%s:firewalls:removerule' % DASHBOARD def set_up_expect(self): # retrieve rules tenant_id = self.tenant.id api.fwaas.rule_list( IsA(http.HttpRequest), tenant_id=tenant_id).AndReturn(self.fw_rules.list()) # retrieves policies policies = self.fw_policies.list() api.fwaas.policy_list( IsA(http.HttpRequest), tenant_id=tenant_id).AndReturn(policies) # retrieves firewalls firewalls = self.firewalls.list() api.fwaas.firewall_list( IsA(http.HttpRequest), tenant_id=tenant_id).AndReturn(firewalls) def set_up_expect_with_exception(self): tenant_id = self.tenant.id api.fwaas.rule_list( IsA(http.HttpRequest), tenant_id=tenant_id).AndRaise(self.exceptions.neutron) api.fwaas.policy_list( IsA(http.HttpRequest), tenant_id=tenant_id).AndRaise(self.exceptions.neutron) api.fwaas.firewall_list( IsA(http.HttpRequest), tenant_id=tenant_id).AndRaise(self.exceptions.neutron) @test.create_stubs({api.fwaas: ('firewall_list', 'policy_list', 'rule_list')}, ) def test_index_firewalls(self): self.set_up_expect() self.mox.ReplayAll() tenant_id = self.tenant.id res = self.client.get(self.INDEX_URL, tenant_id=tenant_id) self.assertTemplateUsed(res, '%s/firewalls/details_tabs.html' % self.DASHBOARD) self.assertTemplateUsed(res, 'horizon_lib/common/_detail_table.html') self.assertEqual(len(res.context['table'].data), len(self.firewalls.list())) @test.create_stubs({api.fwaas: ('firewall_list', 'policy_list', 'rule_list')}, ) def test_index_policies(self): self.set_up_expect() self.mox.ReplayAll() tenant_id = self.tenant.id res = self.client.get(self.INDEX_URL + '?tab=fwtabs__policies', tenant_id=tenant_id) self.assertTemplateUsed(res, '%s/firewalls/details_tabs.html' % self.DASHBOARD) self.assertTemplateUsed(res, 'horizon_lib/common/_detail_table.html') self.assertEqual(len(res.context['policiestable_table'].data), len(self.fw_policies.list())) @test.create_stubs({api.fwaas: ('firewall_list', 'policy_list', 'rule_list')}, ) def test_index_rules(self): self.set_up_expect() self.mox.ReplayAll() tenant_id = self.tenant.id res = self.client.get(self.INDEX_URL + '?tab=fwtabs__rules', tenant_id=tenant_id) self.assertTemplateUsed(res, '%s/firewalls/details_tabs.html' % self.DASHBOARD) self.assertTemplateUsed(res, 'horizon_lib/common/_detail_table.html') self.assertEqual(len(res.context['rulestable_table'].data), len(self.fw_rules.list())) @test.create_stubs({api.fwaas: ('firewall_list', 'policy_list', 'rule_list')}, ) def test_index_exception_firewalls(self): self.set_up_expect_with_exception() self.mox.ReplayAll() tenant_id = self.tenant.id res = self.client.get(self.INDEX_URL, tenant_id=tenant_id) self.assertTemplateUsed(res, '%s/firewalls/details_tabs.html' % self.DASHBOARD) self.assertTemplateUsed(res, 'horizon_lib/common/_detail_table.html') self.assertEqual(len(res.context['table'].data), 0) @test.create_stubs({api.fwaas: ('firewall_list', 'policy_list', 'rule_list')}, ) def test_index_exception_policies(self): self.set_up_expect_with_exception() self.mox.ReplayAll() tenant_id = self.tenant.id res = self.client.get(self.INDEX_URL + '?tab=fwtabs__policies', tenant_id=tenant_id) self.assertTemplateUsed(res, '%s/firewalls/details_tabs.html' % self.DASHBOARD) self.assertTemplateUsed(res, 'horizon_lib/common/_detail_table.html') self.assertEqual(len(res.context['policiestable_table'].data), 0) @test.create_stubs({api.fwaas: ('firewall_list', 'policy_list', 'rule_list')}, ) def test_index_exception_rules(self): self.set_up_expect_with_exception() self.mox.ReplayAll() tenant_id = self.tenant.id res = self.client.get(self.INDEX_URL + '?tab=fwtabs__rules', tenant_id=tenant_id) self.assertTemplateUsed(res, '%s/firewalls/details_tabs.html' % self.DASHBOARD) self.assertTemplateUsed(res, 'horizon_lib/common/_detail_table.html') self.assertEqual(len(res.context['rulestable_table'].data), 0) @test.create_stubs({api.fwaas: ('rule_create',), }) def test_add_rule_post(self): rule1 = self.fw_rules.first() form_data = {'name': rule1.name, 'description': rule1.description, 'protocol': rule1.protocol, 'action': rule1.action, 'source_ip_address': rule1.source_ip_address, 'source_port': rule1.source_port, 'destination_ip_address': rule1.destination_ip_address, 'destination_port': rule1.destination_port, 'shared': rule1.shared, 'enabled': rule1.enabled } api.fwaas.rule_create( IsA(http.HttpRequest), **form_data).AndReturn(rule1) self.mox.ReplayAll() res = self.client.post(reverse(self.ADDRULE_PATH), form_data) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, str(self.INDEX_URL)) def test_add_rule_post_with_error(self): rule1 = self.fw_rules.first() form_data = {'name': rule1.name, 'description': rule1.description, 'protocol': 'abc', 'action': 'pass', 'source_ip_address': rule1.source_ip_address, 'source_port': rule1.source_port, 'destination_ip_address': rule1.destination_ip_address, 'destination_port': rule1.destination_port, 'shared': rule1.shared, 'enabled': rule1.enabled } self.mox.ReplayAll() res = self.client.post(reverse(self.ADDRULE_PATH), form_data) self.assertFormErrors(res, 2) @test.create_stubs({api.fwaas: ('policy_create', 'rule_list'), }) def test_add_policy_post(self): policy = self.fw_policies.first() rules = self.fw_rules.list() tenant_id = self.tenant.id form_data = {'name': policy.name, 'description': policy.description, 'firewall_rules': policy.firewall_rules, 'shared': policy.shared, 'audited': policy.audited } post_data = {'name': policy.name, 'description': policy.description, 'rule': policy.firewall_rules, 'shared': policy.shared, 'audited': policy.audited } # NOTE: SelectRulesAction.populate_rule_choices() lists rule not # associated with any policy. We need to ensure that rules specified # in policy.firewall_rules in post_data (above) are not associated # with any policy. Test data in neutron_data is data in a stable state, # so we need to modify here. for rule in rules: if rule.id in policy.firewall_rules: rule.firewall_policy_id = rule.policy = None api.fwaas.rule_list( IsA(http.HttpRequest), tenant_id=tenant_id).AndReturn(rules) api.fwaas.policy_create( IsA(http.HttpRequest), **form_data).AndReturn(policy) self.mox.ReplayAll() res = self.client.post(reverse(self.ADDPOLICY_PATH), post_data) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, str(self.INDEX_URL)) @test.create_stubs({api.fwaas: ('policy_create', 'rule_list'), }) def test_add_policy_post_with_error(self): policy = self.fw_policies.first() rules = self.fw_rules.list() tenant_id = self.tenant.id form_data = {'description': policy.description, 'firewall_rules': None, 'shared': policy.shared, 'audited': policy.audited } api.fwaas.rule_list( IsA(http.HttpRequest), tenant_id=tenant_id).AndReturn(rules) self.mox.ReplayAll() res = self.client.post(reverse(self.ADDPOLICY_PATH), form_data) self.assertFormErrors(res, 1) @test.create_stubs({api.fwaas: ('firewall_create', 'policy_list'), }) def test_add_firewall_post(self): firewall = self.firewalls.first() policies = self.fw_policies.list() tenant_id = self.tenant.id form_data = {'name': firewall.name, 'description': firewall.description, 'firewall_policy_id': firewall.firewall_policy_id, 'shared': firewall.shared, 'admin_state_up': firewall.admin_state_up } api.fwaas.policy_list( IsA(http.HttpRequest), tenant_id=tenant_id).AndReturn(policies) api.fwaas.firewall_create( IsA(http.HttpRequest), **form_data).AndReturn(firewall) self.mox.ReplayAll() res = self.client.post(reverse(self.ADDFIREWALL_PATH), form_data) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, str(self.INDEX_URL)) @test.create_stubs({api.fwaas: ('firewall_create', 'policy_list'), }) def test_add_firewall_post_with_error(self): firewall = self.firewalls.first() policies = self.fw_policies.list() tenant_id = self.tenant.id form_data = {'name': firewall.name, 'description': firewall.description, 'firewall_policy_id': None, 'shared': firewall.shared, 'admin_state_up': firewall.admin_state_up } api.fwaas.policy_list( IsA(http.HttpRequest), tenant_id=tenant_id).AndReturn(policies) self.mox.ReplayAll() res = self.client.post(reverse(self.ADDFIREWALL_PATH), form_data) self.assertFormErrors(res, 1) @test.create_stubs({api.fwaas: ('rule_get',)}) def test_update_rule_get(self): rule = self.fw_rules.first() api.fwaas.rule_get(IsA(http.HttpRequest), rule.id).AndReturn(rule) self.mox.ReplayAll() res = self.client.get(reverse(self.UPDATERULE_PATH, args=(rule.id,))) self.assertTemplateUsed(res, 'project/firewalls/updaterule.html') @test.create_stubs({api.fwaas: ('rule_get', 'rule_update')}) def test_update_rule_post(self): rule = self.fw_rules.first() api.fwaas.rule_get(IsA(http.HttpRequest), rule.id).AndReturn(rule) data = {'name': 'new name', 'description': 'new desc', 'protocol': 'ICMP', 'action': 'ALLOW', 'shared': False, 'enabled': True, 'source_ip_address': rule.source_ip_address, 'destination_ip_address': None, 'source_port': None, 'destination_port': rule.destination_port, } api.fwaas.rule_update(IsA(http.HttpRequest), rule.id, **data)\ .AndReturn(rule) self.mox.ReplayAll() form_data = data.copy() form_data['destination_ip_address'] = '' form_data['source_port'] = '' res = self.client.post( reverse(self.UPDATERULE_PATH, args=(rule.id,)), form_data) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, str(self.INDEX_URL)) @test.create_stubs({api.fwaas: ('rule_get', 'rule_update')}) def test_update_protocol_any_rule_post(self): # protocol any means protocol == None in neutron context. rule = self.fw_rules.get(protocol=None) api.fwaas.rule_get(IsA(http.HttpRequest), rule.id).AndReturn(rule) data = {'name': 'new name', 'description': 'new desc', 'protocol': 'ICMP', 'action': 'ALLOW', 'shared': False, 'enabled': True, 'source_ip_address': rule.source_ip_address, 'destination_ip_address': None, 'source_port': None, 'destination_port': rule.destination_port, } api.fwaas.rule_update(IsA(http.HttpRequest), rule.id, **data)\ .AndReturn(rule) self.mox.ReplayAll() form_data = data.copy() form_data['destination_ip_address'] = '' form_data['source_port'] = '' res = self.client.post( reverse(self.UPDATERULE_PATH, args=(rule.id,)), form_data) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, str(self.INDEX_URL)) @test.create_stubs({api.fwaas: ('rule_get', 'rule_update')}) def test_update_rule_protocol_to_ANY_post(self): rule = self.fw_rules.first() api.fwaas.rule_get(IsA(http.HttpRequest), rule.id).AndReturn(rule) data = {'name': 'new name', 'description': 'new desc', 'protocol': None, 'action': 'ALLOW', 'shared': False, 'enabled': True, 'source_ip_address': rule.source_ip_address, 'destination_ip_address': None, 'source_port': None, 'destination_port': rule.destination_port, } api.fwaas.rule_update(IsA(http.HttpRequest), rule.id, **data)\ .AndReturn(rule) self.mox.ReplayAll() form_data = data.copy() form_data['destination_ip_address'] = '' form_data['source_port'] = '' form_data['protocol'] = 'ANY' res = self.client.post( reverse(self.UPDATERULE_PATH, args=(rule.id,)), form_data) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, str(self.INDEX_URL)) @test.create_stubs({api.fwaas: ('policy_get',)}) def test_update_policy_get(self): policy = self.fw_policies.first() api.fwaas.policy_get(IsA(http.HttpRequest), policy.id).AndReturn(policy) self.mox.ReplayAll() res = self.client.get( reverse(self.UPDATEPOLICY_PATH, args=(policy.id,))) self.assertTemplateUsed(res, 'project/firewalls/updatepolicy.html') @test.create_stubs({api.fwaas: ('policy_get', 'policy_update', 'rule_list')}) def test_update_policy_post(self): policy = self.fw_policies.first() api.fwaas.policy_get(IsA(http.HttpRequest), policy.id).AndReturn(policy) data = {'name': 'new name', 'description': 'new desc', 'shared': True, 'audited': False } api.fwaas.policy_update(IsA(http.HttpRequest), policy.id, **data)\ .AndReturn(policy) self.mox.ReplayAll() res = self.client.post( reverse(self.UPDATEPOLICY_PATH, args=(policy.id,)), data) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, str(self.INDEX_URL)) @test.create_stubs({api.fwaas: ('firewall_get', 'policy_list')}) def test_update_firewall_get(self): firewall = self.firewalls.first() policies = self.fw_policies.list() tenant_id = self.tenant.id api.fwaas.policy_list( IsA(http.HttpRequest), tenant_id=tenant_id).AndReturn(policies) api.fwaas.firewall_get(IsA(http.HttpRequest), firewall.id).AndReturn(firewall) self.mox.ReplayAll() res = self.client.get( reverse(self.UPDATEFIREWALL_PATH, args=(firewall.id,))) self.assertTemplateUsed(res, 'project/firewalls/updatefirewall.html') @test.create_stubs({api.fwaas: ('firewall_get', 'policy_list', 'firewall_update')}) def test_update_firewall_post(self): firewall = self.firewalls.first() tenant_id = self.tenant.id api.fwaas.firewall_get(IsA(http.HttpRequest), firewall.id).AndReturn(firewall) data = {'name': 'new name', 'description': 'new desc', 'firewall_policy_id': firewall.firewall_policy_id, 'admin_state_up': False } policies = self.fw_policies.list() api.fwaas.policy_list( IsA(http.HttpRequest), tenant_id=tenant_id).AndReturn(policies) api.fwaas.firewall_update(IsA(http.HttpRequest), firewall.id, **data)\ .AndReturn(firewall) self.mox.ReplayAll() res = self.client.post( reverse(self.UPDATEFIREWALL_PATH, args=(firewall.id,)), data) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, str(self.INDEX_URL)) @test.create_stubs({api.fwaas: ('policy_get', 'policy_insert_rule', 'rule_list', 'rule_get')}) def test_policy_insert_rule(self): policy = self.fw_policies.first() tenant_id = self.tenant.id rules = self.fw_rules.list() new_rule_id = rules[2].id data = {'firewall_rule_id': new_rule_id, 'insert_before': rules[1].id, 'insert_after': rules[0].id} api.fwaas.policy_get(IsA(http.HttpRequest), policy.id).AndReturn(policy) policy.firewall_rules = [rules[0].id, new_rule_id, rules[1].id] api.fwaas.rule_list( IsA(http.HttpRequest), tenant_id=tenant_id).AndReturn(rules) api.fwaas.rule_get( IsA(http.HttpRequest), new_rule_id).AndReturn(rules[2]) api.fwaas.policy_insert_rule(IsA(http.HttpRequest), policy.id, **data)\ .AndReturn(policy) self.mox.ReplayAll() res = self.client.post( reverse(self.INSERTRULE_PATH, args=(policy.id,)), data) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, str(self.INDEX_URL)) @test.create_stubs({api.fwaas: ('policy_get', 'policy_remove_rule', 'rule_list', 'rule_get')}) def test_policy_remove_rule(self): policy = self.fw_policies.first() tenant_id = self.tenant.id rules = self.fw_rules.list() remove_rule_id = policy.firewall_rules[0] left_rule_id = policy.firewall_rules[1] data = {'firewall_rule_id': remove_rule_id} after_remove_policy_dict = {'id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'tenant_id': '1', 'name': 'policy1', 'description': 'policy description', 'firewall_rules': [left_rule_id], 'audited': True, 'shared': True} after_remove_policy = fwaas.Policy(after_remove_policy_dict) api.fwaas.policy_get(IsA(http.HttpRequest), policy.id).AndReturn(policy) api.fwaas.rule_list( IsA(http.HttpRequest), tenant_id=tenant_id).AndReturn(rules) api.fwaas.rule_get( IsA(http.HttpRequest), remove_rule_id).AndReturn(rules[0]) api.fwaas.policy_remove_rule(IsA(http.HttpRequest), policy.id, **data)\ .AndReturn(after_remove_policy) self.mox.ReplayAll() res = self.client.post( reverse(self.REMOVERULE_PATH, args=(policy.id,)), data) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, str(self.INDEX_URL)) @test.create_stubs({api.fwaas: ('firewall_list', 'policy_list', 'rule_list', 'rule_delete')}) def test_delete_rule(self): self.set_up_expect() rule = self.fw_rules.first() api.fwaas.rule_delete(IsA(http.HttpRequest), rule.id) self.mox.ReplayAll() form_data = {"action": "rulestable__deleterule__%s" % rule.id} res = self.client.post(self.INDEX_URL, form_data) self.assertNoFormErrors(res) @test.create_stubs({api.fwaas: ('firewall_list', 'policy_list', 'rule_list', 'policy_delete')}) def test_delete_policy(self): self.set_up_expect() policy = self.fw_policies.first() api.fwaas.policy_delete(IsA(http.HttpRequest), policy.id) self.mox.ReplayAll() form_data = {"action": "policiestable__deletepolicy__%s" % policy.id} res = self.client.post(self.INDEX_URL, form_data) self.assertNoFormErrors(res) @test.create_stubs({api.fwaas: ('firewall_list', 'policy_list', 'rule_list', 'firewall_delete')}) def test_delete_firewall(self): self.set_up_expect() fwl = self.firewalls.first() api.fwaas.firewall_delete(IsA(http.HttpRequest), fwl.id) self.mox.ReplayAll() form_data = {"action": "firewallstable__deletefirewall__%s" % fwl.id} res = self.client.post(self.INDEX_URL, form_data) self.assertNoFormErrors(res)
# -*- coding: utf-8 -*- from django.conf import settings from django.core.urlresolvers import reverse from django.shortcuts import get_object_or_404 from django.db import transaction from django.utils.decorators import method_decorator from django.utils.translation import ugettext_lazy as _ from greenmine.core.generic import GenericView from greenmine.core.decorators import login_required, staff_required from greenmine import models from greenmine.wiki import models as wiki_models import datetime import subprocess import shutil import pickle import base64 import zlib import copy import sys import os import re import io class BinaryFile(object): def __init__(self, name): self.name = name def __enter__(self): self._file = io.open(self.name, mode='w+b') return self._file def __exit__(self, exc_type, exc_value, traceback): self._file.flush() self._file.close() class ProjectExportView(GenericView): template_path = 'config/project-export.html' menu = ['settings', 'export'] @login_required def get(self, request, pslug): project = get_object_or_404(models.Project, slug=pslug) context = { 'project': project, 'flist': models.ExportDirectoryCache.objects.all() } return self.render_to_response(self.template_path, context) class RehashExportsDirectory(GenericView): def backup_path_list(self): for path in os.listdir(settings.BACKUP_PATH): if os.path.splitext(path)[1] != '.xz': continue yield os.path.join(settings.BACKUP_PATH, path) def backup_file_list(self): for path in self.backup_path_list(): yield path, os.path.basename(path), os.path.getsize(path) @login_required def get(self, request, pslug): project = get_object_or_404(models.Project, slug=pslug) models.ExportDirectoryCache.objects.all().delete() for path, name, size in self.backup_file_list(): models.ExportDirectoryCache.objects.create( path = name, size = size, ) return self.redirect_referer(_(u"Now rehashed")) class PerojectImportNow(GenericView): @login_required def get(self, request, project, iid): project = get_object_or_404(models.Project, slug=pslug) class ProjectExportNow(GenericView): def _clean_copy(self, obj): new_object = copy.deepcopy(obj) if "_state" in new_object: del new_object["_state"] return new_object def create_tempdir_for_project(self, project): self.dirname = u"{0}_backup".format(project.slug) self.path = os.path.join(settings.BACKUP_PATH, self.dirname) if os.path.exists(self.path): shutil.rmtree(self.path) os.mkdir(self.path) def _backup_project_data(self, project): filename = "project-data.data" filepath = os.path.join(self.path, filename) with io.open(filepath, 'w+b') as f: obj = self._clean_copy(project.__dict__) pickle.dump(obj, f, -1) filename = 'project-owner.data' filepath = os.path.join(self.path, filename) with io.open(filepath, 'w+b') as f: obj = self._clean_copy(project.owner.__dict__) pickle.dump(obj, f, -1) def _backup_user_roles(self, project): directory_pathname = "user_roles" path = os.path.join(self.path, directory_pathname) if os.path.exists(path): shutil.rmtree(path) os.mkdir(path) for pur in models.ProjectUserRole.objects.filter(project=project): obj = self._clean_copy(pur.__dict__) filename = "{0}_{1}.data".format(pur.id, project.id) filepath = os.path.join(path, filename) with BinaryFile(filepath) as f: pickle.dump(obj, f, -1) def _backup_milestones(self, project): directory_pathname = "milestones" path = os.path.join(self.path, directory_pathname) if os.path.exists(path): shutil.rmtree(path) os.mkdir(path) for milestone in project.milestones.all(): obj = self._clean_copy(milestone.__dict__) filename = "{0}_{1}.data".format(milestone.id, project.id) filepath = os.path.join(path, filename) with BinaryFile(filepath) as f: pickle.dump(obj, f, -1) def _backup_user_story(self, project): directory_pathname = "user_stories" path = os.path.join(self.path, directory_pathname) if os.path.exists(path): shutil.rmtree(path) os.mkdir(path) for user_story in project.user_stories.all(): obj = self._clean_copy(user_story.__dict__) obj['watchers'] = [o.id for o in user_story.watchers.all().distinct()] filename = "{0}_{1}.data".format(user_story.id, project.id) filepath = os.path.join(path, filename) with BinaryFile(filepath) as f: pickle.dump(obj, f, -1) def _backup_tasks(self, project): directory_pathname = "tasks" path = os.path.join(self.path, directory_pathname) if os.path.exists(path): shutil.rmtree(path) os.mkdir(path) for task in project.tasks.all(): obj = self._clean_copy(task.__dict__) obj['watchers'] = [o.id for o in task.watchers.all()] filename = "task_{0}_{1}.data".format(task.id, project.id) filepath = os.path.join(path, filename) with BinaryFile(filepath) as f: pickle.dump(obj, f, -1) #for response in models.TaskResponse.objects.filter(task__in=project.tasks.all()): # obj = self._clean_copy(response.__dict__) # obj['watchers'] = [o.id for o in task.watchers.all()] # filename = "response_{0}_{1}.data".format(response.id, project.id) # filepath = os.path.join(path, filename) # with BinaryFile(filepath) as f: # pickle.dump(obj, f, -1) # #for res_file in models.TaskAttachedFile.objects.filter(task__in=project.tasks.all()): # obj = self._clean_copy(res_file.__dict__) # raw_file_data = res_file.attached_file.read() # raw_file_data = zlib.compress(raw_file_data, 9) # raw_file_data = base64.b64encode(raw_file_data) # obj['__raw_file_data'] = raw_file_data # filename = "file_response_{0}_{1}.data".format(res_file.id, project.id) # filepath = os.path.join(path, filename) # with BinaryFile(filepath) as f: # pickle.dump(obj, f, -1) def _backup_questions(self, project): directory_pathname = "questions" path = os.path.join(self.path, directory_pathname) if os.path.exists(path): shutil.rmtree(path) os.mkdir(path) for question in project.questions.all(): obj = self._clean_copy(question.__dict__) obj['watchers'] = [o.id for o in question.watchers.all()] filename = "{0}_{1}.data".format(question.id, project.id) filepath = os.path.join(path, filename) with BinaryFile(filepath) as f: pickle.dump(obj, f, -1) for response in models.QuestionResponse.objects\ .filter(question__in=project.questions.all()): obj = self._clean_copy(question.__dict__) raw_file_data = response.attached_file.read() raw_file_data = zlib.compress(raw_file_data, 9) raw_file_data = base64.b64encode(raw_file_data) obj['__raw_file_data'] = raw_file_data filename = "file_response_{0}_{1}.data".format(response.id, project.id) filepath = os.path.join(path, filename) with BinaryFile(filepath) as f: pickle.dump(obj, f, -1) def _backup_wiki(self, project): directory_pathname = "wiki" path = os.path.join(self.path, directory_pathname) if os.path.exists(path): shutil.rmtree(path) os.mkdir(path) for wikipage in project.wiki_pages.all(): obj = self._clean_copy(wikipage.__dict__) obj['watchers'] = [o.id for o in wikipage.watchers.all()] filename = "{0}_{1}.data".format(wikipage.id, project.id) filepath = os.path.join(path, filename) with BinaryFile(filepath) as f: pickle.dump(obj, f, -1) for fattached in wiki_models.WikiPageAttachment.objects\ .filter(wikipage__in=project.wiki_pages.all()): obj = self._clean_copy(fattached.__dict__) raw_file_data = fattached.attached_file.read() raw_file_data = zlib.compress(raw_file_data, 9) raw_file_data = base64.b64encode(raw_file_data) obj['__raw_file_data'] = raw_file_data filename = "file_response_{0}_{1}.data".format(fattached.id, project.id) filepath = os.path.join(path, filename) with BinaryFile(filepath) as f: pickle.dump(obj, f, -1) def _create_tarball(self, project): current_date = datetime.datetime.now().strftime("%Y-%m-%d-%H%M%s") filename = "{0}-{1}.tar.xz".format(project.slug, current_date) current_pwd = os.getcwd() os.chdir(settings.BACKUP_PATH) command = "tar cvJf {0} {1}".format(filename, self.dirname) p = subprocess.Popen(command.split(), stdout=sys.stdout) os.chdir(current_pwd) @login_required def get(self, request, pslug): project = get_object_or_404(models.Project, slug=pslug) self.create_tempdir_for_project(project) self._backup_project_data(project) self._backup_user_roles(project) self._backup_milestones(project) self._backup_user_story(project) self._backup_tasks(project) self._backup_questions(project) self._backup_wiki(project) self._create_tarball(project) return self.redirect_referer("Now exported, rehash directory!")
from __future__ import absolute_import import cgi import email.utils import hashlib import getpass import json import logging import mimetypes import os import platform import re import shutil import sys import tempfile from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._vendor.six.moves.urllib import request as urllib_request import pip from pip.exceptions import InstallationError, HashMismatch from pip.models import PyPI from pip.utils import (splitext, rmtree, format_size, display_path, backup_dir, ask_path_exists, unpack_file) from pip.utils.ui import DownloadProgressBar, DownloadProgressSpinner from pip.locations import write_delete_marker_file from pip.vcs import vcs from pip._vendor import requests, six from pip._vendor.requests.adapters import BaseAdapter, HTTPAdapter from pip._vendor.requests.auth import AuthBase, HTTPBasicAuth from pip._vendor.requests.models import Response from pip._vendor.requests.structures import CaseInsensitiveDict from pip._vendor.requests.packages import urllib3 from pip._vendor.cachecontrol import CacheControlAdapter from pip._vendor.cachecontrol.caches import FileCache from pip._vendor.lockfile import LockError from pip._vendor.six.moves import xmlrpc_client __all__ = ['get_file_content', 'is_url', 'url_to_path', 'path_to_url', 'is_archive_file', 'unpack_vcs_link', 'unpack_file_url', 'is_vcs_url', 'is_file_url', 'unpack_http_url', 'unpack_url'] logger = logging.getLogger(__name__) def user_agent(): """ Return a string representing the user agent. """ data = { "installer": {"name": "pip", "version": pip.__version__}, "python": platform.python_version(), "implementation": { "name": platform.python_implementation(), }, } if data["implementation"]["name"] == 'CPython': data["implementation"]["version"] = platform.python_version() elif data["implementation"]["name"] == 'PyPy': if sys.pypy_version_info.releaselevel == 'final': pypy_version_info = sys.pypy_version_info[:3] else: pypy_version_info = sys.pypy_version_info data["implementation"]["version"] = ".".join( [str(x) for x in pypy_version_info] ) elif data["implementation"]["name"] == 'Jython': # Complete Guess data["implementation"]["version"] = platform.python_version() elif data["implementation"]["name"] == 'IronPython': # Complete Guess data["implementation"]["version"] = platform.python_version() if sys.platform.startswith("linux"): distro = dict(filter( lambda x: x[1], zip(["name", "version", "id"], platform.linux_distribution()), )) libc = dict(filter( lambda x: x[1], zip(["lib", "version"], platform.libc_ver()), )) if libc: distro["libc"] = libc if distro: data["distro"] = distro if sys.platform.startswith("darwin") and platform.mac_ver()[0]: data["distro"] = {"name": "OS X", "version": platform.mac_ver()[0]} if platform.system(): data.setdefault("system", {})["name"] = platform.system() if platform.release(): data.setdefault("system", {})["release"] = platform.release() if platform.machine(): data["cpu"] = platform.machine() return "{data[installer][name]}/{data[installer][version]} {json}".format( data=data, json=json.dumps(data, separators=(",", ":"), sort_keys=True), ) class MultiDomainBasicAuth(AuthBase): def __init__(self, prompting=True): self.prompting = prompting self.passwords = {} def __call__(self, req): parsed = urllib_parse.urlparse(req.url) # Get the netloc without any embedded credentials netloc = parsed.netloc.rsplit("@", 1)[-1] # Set the url of the request to the url without any credentials req.url = urllib_parse.urlunparse(parsed[:1] + (netloc,) + parsed[2:]) # Use any stored credentials that we have for this netloc username, password = self.passwords.get(netloc, (None, None)) # Extract credentials embedded in the url if we have none stored if username is None: username, password = self.parse_credentials(parsed.netloc) if username or password: # Store the username and password self.passwords[netloc] = (username, password) # Send the basic auth with this request req = HTTPBasicAuth(username or "", password or "")(req) # Attach a hook to handle 401 responses req.register_hook("response", self.handle_401) return req def handle_401(self, resp, **kwargs): # We only care about 401 responses, anything else we want to just # pass through the actual response if resp.status_code != 401: return resp # We are not able to prompt the user so simple return the response if not self.prompting: return resp parsed = urllib_parse.urlparse(resp.url) # Prompt the user for a new username and password username = six.moves.input("User for %s: " % parsed.netloc) password = getpass.getpass("Password: ") # Store the new username and password to use for future requests if username or password: self.passwords[parsed.netloc] = (username, password) # Consume content and release the original connection to allow our new # request to reuse the same one. resp.content resp.raw.release_conn() # Add our new username and password to the request req = HTTPBasicAuth(username or "", password or "")(resp.request) # Send our new request new_resp = resp.connection.send(req, **kwargs) new_resp.history.append(resp) return new_resp def parse_credentials(self, netloc): if "@" in netloc: userinfo = netloc.rsplit("@", 1)[0] if ":" in userinfo: return userinfo.split(":", 1) return userinfo, None return None, None class LocalFSAdapter(BaseAdapter): def send(self, request, stream=None, timeout=None, verify=None, cert=None, proxies=None): pathname = url_to_path(request.url) resp = Response() resp.status_code = 200 resp.url = request.url try: stats = os.stat(pathname) except OSError as exc: resp.status_code = 404 resp.raw = exc else: modified = email.utils.formatdate(stats.st_mtime, usegmt=True) content_type = mimetypes.guess_type(pathname)[0] or "text/plain" resp.headers = CaseInsensitiveDict({ "Content-Type": content_type, "Content-Length": stats.st_size, "Last-Modified": modified, }) resp.raw = open(pathname, "rb") resp.close = resp.raw.close return resp def close(self): pass class SafeFileCache(FileCache): """ A file based cache which is safe to use even when the target directory may not be accessible or writable. """ def get(self, *args, **kwargs): try: return super(SafeFileCache, self).get(*args, **kwargs) except (LockError, OSError, IOError): # We intentionally silence this error, if we can't access the cache # then we can just skip caching and process the request as if # caching wasn't enabled. pass def set(self, *args, **kwargs): try: return super(SafeFileCache, self).set(*args, **kwargs) except (LockError, OSError, IOError): # We intentionally silence this error, if we can't access the cache # then we can just skip caching and process the request as if # caching wasn't enabled. pass def delete(self, *args, **kwargs): try: return super(SafeFileCache, self).delete(*args, **kwargs) except (LockError, OSError, IOError): # We intentionally silence this error, if we can't access the cache # then we can just skip caching and process the request as if # caching wasn't enabled. pass class InsecureHTTPAdapter(HTTPAdapter): def cert_verify(self, conn, url, verify, cert): conn.cert_reqs = 'CERT_NONE' conn.ca_certs = None class PipSession(requests.Session): timeout = None def __init__(self, *args, **kwargs): retries = kwargs.pop("retries", 0) cache = kwargs.pop("cache", None) insecure_hosts = kwargs.pop("insecure_hosts", []) super(PipSession, self).__init__(*args, **kwargs) # Attach our User Agent to the request self.headers["User-Agent"] = user_agent() # Attach our Authentication handler to the session self.auth = MultiDomainBasicAuth() # Create our urllib3.Retry instance which will allow us to customize # how we handle retries. retries = urllib3.Retry( # Set the total number of retries that a particular request can # have. total=retries, # A 503 error from PyPI typically means that the Fastly -> Origin # connection got interupted in some way. A 503 error in general # is typically considered a transient error so we'll go ahead and # retry it. status_forcelist=[503], # Add a small amount of back off between failed requests in # order to prevent hammering the service. backoff_factor=0.25, ) # We want to _only_ cache responses on securely fetched origins. We do # this because we can't validate the response of an insecurely fetched # origin, and we don't want someone to be able to poison the cache and # require manual evication from the cache to fix it. if cache: secure_adapter = CacheControlAdapter( cache=SafeFileCache(cache), max_retries=retries, ) else: secure_adapter = HTTPAdapter(max_retries=retries) # Our Insecure HTTPAdapter disables HTTPS validation. It does not # support caching (see above) so we'll use it for all http:// URLs as # well as any https:// host that we've marked as ignoring TLS errors # for. insecure_adapter = InsecureHTTPAdapter(max_retries=retries) self.mount("https://", secure_adapter) self.mount("http://", insecure_adapter) # Enable file:// urls self.mount("file://", LocalFSAdapter()) # We want to use a non-validating adapter for any requests which are # deemed insecure. for host in insecure_hosts: self.mount("https://{0}/".format(host), insecure_adapter) def request(self, method, url, *args, **kwargs): # Allow setting a default timeout on a session kwargs.setdefault("timeout", self.timeout) # Dispatch the actual request return super(PipSession, self).request(method, url, *args, **kwargs) def get_file_content(url, comes_from=None, session=None): """Gets the content of a file; it may be a filename, file: URL, or http: URL. Returns (location, content). Content is unicode.""" if session is None: raise TypeError( "get_file_content() missing 1 required keyword argument: 'session'" ) match = _scheme_re.search(url) if match: scheme = match.group(1).lower() if (scheme == 'file' and comes_from and comes_from.startswith('http')): raise InstallationError( 'Requirements file %s references URL %s, which is local' % (comes_from, url)) if scheme == 'file': path = url.split(':', 1)[1] path = path.replace('\\', '/') match = _url_slash_drive_re.match(path) if match: path = match.group(1) + ':' + path.split('|', 1)[1] path = urllib_parse.unquote(path) if path.startswith('/'): path = '/' + path.lstrip('/') url = path else: # FIXME: catch some errors resp = session.get(url) resp.raise_for_status() if six.PY3: return resp.url, resp.text else: return resp.url, resp.content try: with open(url) as f: content = f.read() except IOError as exc: raise InstallationError( 'Could not open requirements file: %s' % str(exc) ) return url, content _scheme_re = re.compile(r'^(http|https|file):', re.I) _url_slash_drive_re = re.compile(r'/*([a-z])\|', re.I) def is_url(name): """Returns true if the name looks like a URL""" if ':' not in name: return False scheme = name.split(':', 1)[0].lower() return scheme in ['http', 'https', 'file', 'ftp'] + vcs.all_schemes def url_to_path(url): """ Convert a file: URL to a path. """ assert url.startswith('file:'), ( "You can only turn file: urls into filenames (not %r)" % url) _, netloc, path, _, _ = urllib_parse.urlsplit(url) # if we have a UNC path, prepend UNC share notation if netloc: netloc = '\\\\' + netloc path = urllib_request.url2pathname(netloc + path) return path def path_to_url(path): """ Convert a path to a file: URL. The path will be made absolute and have quoted path parts. """ path = os.path.normpath(os.path.abspath(path)) url = urllib_parse.urljoin('file:', urllib_request.pathname2url(path)) return url def is_archive_file(name): """Return True if `name` is a considered as an archive file.""" archives = ( '.zip', '.tar.gz', '.tar.bz2', '.tgz', '.tar', '.whl' ) ext = splitext(name)[1].lower() if ext in archives: return True return False def unpack_vcs_link(link, location, only_download=False): vcs_backend = _get_used_vcs_backend(link) if only_download: vcs_backend.export(location) else: vcs_backend.unpack(location) def _get_used_vcs_backend(link): for backend in vcs.backends: if link.scheme in backend.schemes: vcs_backend = backend(link.url) return vcs_backend def is_vcs_url(link): return bool(_get_used_vcs_backend(link)) def is_file_url(link): return link.url.lower().startswith('file:') def _check_hash(download_hash, link): if download_hash.digest_size != hashlib.new(link.hash_name).digest_size: logger.critical( "Hash digest size of the package %d (%s) doesn't match the " "expected hash name %s!", download_hash.digest_size, link, link.hash_name, ) raise HashMismatch('Hash name mismatch for package %s' % link) if download_hash.hexdigest() != link.hash: logger.critical( "Hash of the package %s (%s) doesn't match the expected hash %s!", link, download_hash.hexdigest(), link.hash, ) raise HashMismatch( 'Bad %s hash for package %s' % (link.hash_name, link) ) def _get_hash_from_file(target_file, link): try: download_hash = hashlib.new(link.hash_name) except (ValueError, TypeError): logger.warning( "Unsupported hash name %s for package %s", link.hash_name, link, ) return None with open(target_file, 'rb') as fp: while True: chunk = fp.read(4096) if not chunk: break download_hash.update(chunk) return download_hash def _download_url(resp, link, content_file): download_hash = None if link.hash and link.hash_name: try: download_hash = hashlib.new(link.hash_name) except ValueError: logger.warning( "Unsupported hash name %s for package %s", link.hash_name, link, ) try: total_length = int(resp.headers['content-length']) except (ValueError, KeyError, TypeError): total_length = 0 cached_resp = getattr(resp, "from_cache", False) if cached_resp: show_progress = False elif total_length > (40 * 1000): show_progress = True elif not total_length: show_progress = True else: show_progress = False show_url = link.show_url try: def resp_read(chunk_size): try: # Special case for urllib3. for chunk in resp.raw.stream( chunk_size, # We use decode_content=False here because we do # want urllib3 to mess with the raw bytes we get # from the server. If we decompress inside of # urllib3 then we cannot verify the checksum # because the checksum will be of the compressed # file. This breakage will only occur if the # server adds a Content-Encoding header, which # depends on how the server was configured: # - Some servers will notice that the file isn't a # compressible file and will leave the file alone # and with an empty Content-Encoding # - Some servers will notice that the file is # already compressed and will leave the file # alone and will add a Content-Encoding: gzip # header # - Some servers won't notice anything at all and # will take a file that's already been compressed # and compress it again and set the # Content-Encoding: gzip header # # By setting this not to decode automatically we # hope to eliminate problems with the second case. decode_content=False): yield chunk except AttributeError: # Standard file-like object. while True: chunk = resp.raw.read(chunk_size) if not chunk: break yield chunk progress_indicator = lambda x, *a, **k: x if link.netloc == PyPI.netloc: url = show_url else: url = link.url_without_fragment if show_progress: # We don't show progress on cached responses if total_length: logger.info( "Downloading %s (%s)", url, format_size(total_length), ) progress_indicator = DownloadProgressBar( max=total_length, ).iter else: logger.info("Downloading %s", url) progress_indicator = DownloadProgressSpinner().iter elif cached_resp: logger.info("Using cached %s", url) else: logger.info("Downloading %s", url) logger.debug('Downloading from URL %s', link) for chunk in progress_indicator(resp_read(4096), 4096): if download_hash is not None: download_hash.update(chunk) content_file.write(chunk) finally: if link.hash and link.hash_name: _check_hash(download_hash, link) return download_hash def _copy_file(filename, location, content_type, link): copy = True download_location = os.path.join(location, link.filename) if os.path.exists(download_location): response = ask_path_exists( 'The file %s exists. (i)gnore, (w)ipe, (b)ackup ' % display_path(download_location), ('i', 'w', 'b')) if response == 'i': copy = False elif response == 'w': logger.warning('Deleting %s', display_path(download_location)) os.remove(download_location) elif response == 'b': dest_file = backup_dir(download_location) logger.warning( 'Backing up %s to %s', display_path(download_location), display_path(dest_file), ) shutil.move(download_location, dest_file) if copy: shutil.copy(filename, download_location) logger.info('Saved %s', display_path(download_location)) def unpack_http_url(link, location, download_dir=None, session=None): if session is None: raise TypeError( "unpack_http_url() missing 1 required keyword argument: 'session'" ) temp_dir = tempfile.mkdtemp('-unpack', 'pip-') # If a download dir is specified, is the file already downloaded there? already_downloaded_path = None if download_dir: already_downloaded_path = _check_download_dir(link, download_dir) if already_downloaded_path: from_path = already_downloaded_path content_type = mimetypes.guess_type(from_path)[0] else: # let's download to a tmp dir from_path, content_type = _download_http_url(link, session, temp_dir) # unpack the archive to the build dir location. even when only downloading # archives, they have to be unpacked to parse dependencies unpack_file(from_path, location, content_type, link) # a download dir is specified; let's copy the archive there if download_dir and not already_downloaded_path: _copy_file(from_path, download_dir, content_type, link) if not already_downloaded_path: os.unlink(from_path) os.rmdir(temp_dir) def unpack_file_url(link, location, download_dir=None): """Unpack link into location. If download_dir is provided and link points to a file, make a copy of the link file inside download_dir.""" link_path = url_to_path(link.url_without_fragment) # If it's a url to a local directory if os.path.isdir(link_path): if os.path.isdir(location): rmtree(location) shutil.copytree( link_path, location, symlinks=True, ignore=shutil.ignore_patterns( '.tox', '.git', '.hg', '.bzr', '.svn')) if download_dir: logger.info('Link is a directory, ignoring download_dir') return # if link has a hash, let's confirm it matches if link.hash: link_path_hash = _get_hash_from_file(link_path, link) _check_hash(link_path_hash, link) # If a download dir is specified, is the file already there and valid? already_downloaded_path = None if download_dir: already_downloaded_path = _check_download_dir(link, download_dir) if already_downloaded_path: from_path = already_downloaded_path else: from_path = link_path content_type = mimetypes.guess_type(from_path)[0] # unpack the archive to the build dir location. even when only downloading # archives, they have to be unpacked to parse dependencies unpack_file(from_path, location, content_type, link) # a download dir is specified and not already downloaded if download_dir and not already_downloaded_path: _copy_file(from_path, download_dir, content_type, link) class PipXmlrpcTransport(xmlrpc_client.Transport): """Provide a `xmlrpclib.Transport` implementation via a `PipSession` object. """ def __init__(self, index_url, session, use_datetime=False): xmlrpc_client.Transport.__init__(self, use_datetime) index_parts = urllib_parse.urlparse(index_url) self._scheme = index_parts.scheme self._session = session def request(self, host, handler, request_body, verbose=False): parts = (self._scheme, host, handler, None, None, None) url = urllib_parse.urlunparse(parts) try: headers = {'Content-Type': 'text/xml'} response = self._session.post(url, data=request_body, headers=headers, stream=True) response.raise_for_status() self.verbose = verbose return self.parse_response(response.raw) except requests.HTTPError as exc: logger.critical( "HTTP error %s while getting %s", exc.response.status_code, url, ) raise def unpack_url(link, location, download_dir=None, only_download=False, session=None): """Unpack link. If link is a VCS link: if only_download, export into download_dir and ignore location else unpack into location for other types of link: - unpack into location - if download_dir, copy the file into download_dir - if only_download, mark location for deletion """ # non-editable vcs urls if is_vcs_url(link): unpack_vcs_link(link, location, only_download) # file urls elif is_file_url(link): unpack_file_url(link, location, download_dir) if only_download: write_delete_marker_file(location) # http urls else: if session is None: session = PipSession() unpack_http_url( link, location, download_dir, session, ) if only_download: write_delete_marker_file(location) def _download_http_url(link, session, temp_dir): """Download link url into temp_dir using provided session""" target_url = link.url.split('#', 1)[0] try: resp = session.get( target_url, # We use Accept-Encoding: identity here because requests # defaults to accepting compressed responses. This breaks in # a variety of ways depending on how the server is configured. # - Some servers will notice that the file isn't a compressible # file and will leave the file alone and with an empty # Content-Encoding # - Some servers will notice that the file is already # compressed and will leave the file alone and will add a # Content-Encoding: gzip header # - Some servers won't notice anything at all and will take # a file that's already been compressed and compress it again # and set the Content-Encoding: gzip header # By setting this to request only the identity encoding We're # hoping to eliminate the third case. Hopefully there does not # exist a server which when given a file will notice it is # already compressed and that you're not asking for a # compressed file and will then decompress it before sending # because if that's the case I don't think it'll ever be # possible to make this work. headers={"Accept-Encoding": "identity"}, stream=True, ) resp.raise_for_status() except requests.HTTPError as exc: logger.critical( "HTTP error %s while getting %s", exc.response.status_code, link, ) raise content_type = resp.headers.get('content-type', '') filename = link.filename # fallback # Have a look at the Content-Disposition header for a better guess content_disposition = resp.headers.get('content-disposition') if content_disposition: type, params = cgi.parse_header(content_disposition) # We use ``or`` here because we don't want to use an "empty" value # from the filename param. filename = params.get('filename') or filename ext = splitext(filename)[1] if not ext: ext = mimetypes.guess_extension(content_type) if ext: filename += ext if not ext and link.url != resp.url: ext = os.path.splitext(resp.url)[1] if ext: filename += ext file_path = os.path.join(temp_dir, filename) with open(file_path, 'wb') as content_file: _download_url(resp, link, content_file) return file_path, content_type def _check_download_dir(link, download_dir): """ Check download_dir for previously downloaded file with correct hash If a correct file is found return its path else None """ download_path = os.path.join(download_dir, link.filename) if os.path.exists(download_path): # If already downloaded, does its hash match? logger.info('File was already downloaded %s', download_path) if link.hash: download_hash = _get_hash_from_file(download_path, link) try: _check_hash(download_hash, link) except HashMismatch: logger.warning( 'Previously-downloaded file %s has bad hash, ' 're-downloading.', download_path ) os.unlink(download_path) return None return download_path return None
# -*- coding: utf-8 -*- # # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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.""" import mock import pytest from google.cloud import errorreporting_v1beta1 from google.cloud.errorreporting_v1beta1.proto import common_pb2 from google.cloud.errorreporting_v1beta1.proto import error_stats_service_pb2 class MultiCallableStub(object): """Stub for the grpc.UnaryUnaryMultiCallable interface.""" def __init__(self, method, channel_stub): self.method = method self.channel_stub = channel_stub def __call__(self, request, timeout=None, metadata=None, credentials=None): self.channel_stub.requests.append((self.method, request)) response = None if self.channel_stub.responses: response = self.channel_stub.responses.pop() if isinstance(response, Exception): raise response if response: return response class ChannelStub(object): """Stub for the grpc.Channel interface.""" def __init__(self, responses=[]): self.responses = responses self.requests = [] def unary_unary(self, method, request_serializer=None, response_deserializer=None): return MultiCallableStub(method, self) class CustomException(Exception): pass class TestErrorStatsServiceClient(object): def test_list_group_stats(self): # Setup Expected Response next_page_token = "" error_group_stats_element = {} error_group_stats = [error_group_stats_element] expected_response = { "next_page_token": next_page_token, "error_group_stats": error_group_stats, } expected_response = error_stats_service_pb2.ListGroupStatsResponse( **expected_response ) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = errorreporting_v1beta1.ErrorStatsServiceClient() # Setup Request project_name = client.project_path("[PROJECT]") time_range = {} paged_list_response = client.list_group_stats(project_name, time_range) resources = list(paged_list_response) assert len(resources) == 1 assert expected_response.error_group_stats[0] == resources[0] assert len(channel.requests) == 1 expected_request = error_stats_service_pb2.ListGroupStatsRequest( project_name=project_name, time_range=time_range ) actual_request = channel.requests[0][1] assert expected_request == actual_request def test_list_group_stats_exception(self): channel = ChannelStub(responses=[CustomException()]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = errorreporting_v1beta1.ErrorStatsServiceClient() # Setup request project_name = client.project_path("[PROJECT]") time_range = {} paged_list_response = client.list_group_stats(project_name, time_range) with pytest.raises(CustomException): list(paged_list_response) def test_list_events(self): # Setup Expected Response next_page_token = "" error_events_element = {} error_events = [error_events_element] expected_response = { "next_page_token": next_page_token, "error_events": error_events, } expected_response = error_stats_service_pb2.ListEventsResponse( **expected_response ) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = errorreporting_v1beta1.ErrorStatsServiceClient() # Setup Request project_name = client.project_path("[PROJECT]") group_id = "groupId506361563" paged_list_response = client.list_events(project_name, group_id) resources = list(paged_list_response) assert len(resources) == 1 assert expected_response.error_events[0] == resources[0] assert len(channel.requests) == 1 expected_request = error_stats_service_pb2.ListEventsRequest( project_name=project_name, group_id=group_id ) actual_request = channel.requests[0][1] assert expected_request == actual_request def test_list_events_exception(self): channel = ChannelStub(responses=[CustomException()]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = errorreporting_v1beta1.ErrorStatsServiceClient() # Setup request project_name = client.project_path("[PROJECT]") group_id = "groupId506361563" paged_list_response = client.list_events(project_name, group_id) with pytest.raises(CustomException): list(paged_list_response) def test_delete_events(self): # Setup Expected Response expected_response = {} expected_response = error_stats_service_pb2.DeleteEventsResponse( **expected_response ) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = errorreporting_v1beta1.ErrorStatsServiceClient() # Setup Request project_name = client.project_path("[PROJECT]") response = client.delete_events(project_name) assert expected_response == response assert len(channel.requests) == 1 expected_request = error_stats_service_pb2.DeleteEventsRequest( project_name=project_name ) actual_request = channel.requests[0][1] assert expected_request == actual_request def test_delete_events_exception(self): # Mock the API response channel = ChannelStub(responses=[CustomException()]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = errorreporting_v1beta1.ErrorStatsServiceClient() # Setup request project_name = client.project_path("[PROJECT]") with pytest.raises(CustomException): client.delete_events(project_name)
# Copyright (c) 2010 Citrix Systems, 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. # # Parts of this file are based upon xmlrpclib.py, the XML-RPC client # interface included in the Python distribution. # # Copyright (c) 1999-2002 by Secret Labs AB # Copyright (c) 1999-2002 by Fredrik Lundh # # By obtaining, using, and/or copying this software and/or its # associated documentation, you agree that you have read, understood, # and will comply with the following terms and conditions: # # Permission to use, copy, modify, and distribute this software and # its associated documentation for any purpose and without fee is # hereby granted, provided that the above copyright notice appears in # all copies, and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of # Secret Labs AB or the author not be used in advertising or publicity # pertaining to distribution of the software without specific, written # prior permission. # # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. # -------------------------------------------------------------------- """ A fake XenAPI SDK. """ import base64 import pickle import random import uuid from xml.sax import saxutils import zlib from oslo.serialization import jsonutils from oslo.utils import timeutils from oslo.utils import units from nova import exception from nova.i18n import _ from nova.openstack.common import log as logging from nova.virt.xenapi.client import session as xenapi_session _CLASSES = ['host', 'network', 'session', 'pool', 'SR', 'VBD', 'PBD', 'VDI', 'VIF', 'PIF', 'VM', 'VLAN', 'task'] _db_content = {} LOG = logging.getLogger(__name__) def reset(): for c in _CLASSES: _db_content[c] = {} host = create_host('fake') create_vm('fake dom 0', 'Running', is_a_template=False, is_control_domain=True, resident_on=host) def reset_table(table): if table not in _CLASSES: return _db_content[table] = {} def _create_pool(name_label): return _create_object('pool', {'name_label': name_label}) def create_host(name_label, hostname='fake_name', address='fake_addr'): host_ref = _create_object('host', {'name_label': name_label, 'hostname': hostname, 'address': address}) host_default_sr_ref = _create_local_srs(host_ref) _create_local_pif(host_ref) # Create a pool if we don't have one already if len(_db_content['pool']) == 0: pool_ref = _create_pool('') _db_content['pool'][pool_ref]['master'] = host_ref _db_content['pool'][pool_ref]['default-SR'] = host_default_sr_ref _db_content['pool'][pool_ref]['suspend-image-SR'] = host_default_sr_ref def create_network(name_label, bridge): return _create_object('network', {'name_label': name_label, 'bridge': bridge}) def create_vm(name_label, status, **kwargs): if status == 'Running': domid = random.randrange(1, 1 << 16) resident_on = _db_content['host'].keys()[0] else: domid = -1 resident_on = '' vm_rec = kwargs.copy() vm_rec.update({'name_label': name_label, 'domid': domid, 'power_state': status, 'blocked_operations': {}, 'resident_on': resident_on}) vm_ref = _create_object('VM', vm_rec) after_VM_create(vm_ref, vm_rec) return vm_ref def destroy_vm(vm_ref): vm_rec = _db_content['VM'][vm_ref] vbd_refs = vm_rec['VBDs'] # NOTE(johannes): Shallow copy since destroy_vbd will remove itself # from the list for vbd_ref in vbd_refs[:]: destroy_vbd(vbd_ref) del _db_content['VM'][vm_ref] def destroy_vbd(vbd_ref): vbd_rec = _db_content['VBD'][vbd_ref] vm_ref = vbd_rec['VM'] vm_rec = _db_content['VM'][vm_ref] vm_rec['VBDs'].remove(vbd_ref) vdi_ref = vbd_rec['VDI'] vdi_rec = _db_content['VDI'][vdi_ref] vdi_rec['VBDs'].remove(vbd_ref) del _db_content['VBD'][vbd_ref] def destroy_vdi(vdi_ref): vdi_rec = _db_content['VDI'][vdi_ref] vbd_refs = vdi_rec['VBDs'] # NOTE(johannes): Shallow copy since destroy_vbd will remove itself # from the list for vbd_ref in vbd_refs[:]: destroy_vbd(vbd_ref) del _db_content['VDI'][vdi_ref] def create_vdi(name_label, sr_ref, **kwargs): vdi_rec = { 'SR': sr_ref, 'read_only': False, 'type': '', 'name_label': name_label, 'name_description': '', 'sharable': False, 'other_config': {}, 'location': '', 'xenstore_data': {}, 'sm_config': {'vhd-parent': None}, 'physical_utilisation': '123', 'managed': True, } vdi_rec.update(kwargs) vdi_ref = _create_object('VDI', vdi_rec) after_VDI_create(vdi_ref, vdi_rec) return vdi_ref def after_VDI_create(vdi_ref, vdi_rec): vdi_rec.setdefault('VBDs', []) def create_vbd(vm_ref, vdi_ref, userdevice=0, other_config=None): if other_config is None: other_config = {} vbd_rec = {'VM': vm_ref, 'VDI': vdi_ref, 'userdevice': str(userdevice), 'currently_attached': False, 'other_config': other_config} vbd_ref = _create_object('VBD', vbd_rec) after_VBD_create(vbd_ref, vbd_rec) return vbd_ref def after_VBD_create(vbd_ref, vbd_rec): """Create read-only fields and backref from VM and VDI to VBD when VBD is created. """ vbd_rec['currently_attached'] = False vbd_rec['device'] = '' vbd_rec.setdefault('other_config', {}) vm_ref = vbd_rec['VM'] vm_rec = _db_content['VM'][vm_ref] vm_rec['VBDs'].append(vbd_ref) vm_name_label = _db_content['VM'][vm_ref]['name_label'] vbd_rec['vm_name_label'] = vm_name_label vdi_ref = vbd_rec['VDI'] if vdi_ref and vdi_ref != "OpaqueRef:NULL": vdi_rec = _db_content['VDI'][vdi_ref] vdi_rec['VBDs'].append(vbd_ref) def after_VIF_create(vif_ref, vif_rec): """Create backref from VM to VIF when VIF is created. """ vm_ref = vif_rec['VM'] vm_rec = _db_content['VM'][vm_ref] vm_rec['VIFs'].append(vif_ref) def after_VM_create(vm_ref, vm_rec): """Create read-only fields in the VM record.""" vm_rec.setdefault('domid', -1) vm_rec.setdefault('is_control_domain', False) vm_rec.setdefault('is_a_template', False) vm_rec.setdefault('memory_static_max', str(8 * units.Gi)) vm_rec.setdefault('memory_dynamic_max', str(8 * units.Gi)) vm_rec.setdefault('VCPUs_max', str(4)) vm_rec.setdefault('VBDs', []) vm_rec.setdefault('VIFs', []) vm_rec.setdefault('resident_on', '') def create_pbd(host_ref, sr_ref, attached): config = {'path': '/var/run/sr-mount/%s' % sr_ref} return _create_object('PBD', {'device_config': config, 'host': host_ref, 'SR': sr_ref, 'currently_attached': attached}) def create_task(name_label): return _create_object('task', {'name_label': name_label, 'status': 'pending'}) def _create_local_srs(host_ref): """Create an SR that looks like the one created on the local disk by default by the XenServer installer. Also, fake the installation of an ISO SR. """ create_sr(name_label='Local storage ISO', type='iso', other_config={'i18n-original-value-name_label': 'Local storage ISO', 'i18n-key': 'local-storage-iso'}, physical_size=80000, physical_utilisation=40000, virtual_allocation=80000, host_ref=host_ref) return create_sr(name_label='Local storage', type='ext', other_config={'i18n-original-value-name_label': 'Local storage', 'i18n-key': 'local-storage'}, physical_size=40000, physical_utilisation=20000, virtual_allocation=10000, host_ref=host_ref) def create_sr(**kwargs): sr_ref = _create_object( 'SR', {'name_label': kwargs.get('name_label'), 'type': kwargs.get('type'), 'content_type': kwargs.get('type', 'user'), 'shared': kwargs.get('shared', False), 'physical_size': kwargs.get('physical_size', str(1 << 30)), 'physical_utilisation': str( kwargs.get('physical_utilisation', 0)), 'virtual_allocation': str(kwargs.get('virtual_allocation', 0)), 'other_config': kwargs.get('other_config', {}), 'VDIs': kwargs.get('VDIs', [])}) pbd_ref = create_pbd(kwargs.get('host_ref'), sr_ref, True) _db_content['SR'][sr_ref]['PBDs'] = [pbd_ref] return sr_ref def _create_local_pif(host_ref): pif_ref = _create_object('PIF', {'name-label': 'Fake PIF', 'MAC': '00:11:22:33:44:55', 'physical': True, 'VLAN': -1, 'device': 'fake0', 'host_uuid': host_ref, 'network': '', 'IP': '10.1.1.1', 'IPv6': '', 'uuid': '', 'management': 'true'}) _db_content['PIF'][pif_ref]['uuid'] = pif_ref return pif_ref def _create_object(table, obj): ref = str(uuid.uuid4()) obj['uuid'] = str(uuid.uuid4()) _db_content[table][ref] = obj return ref def _create_sr(table, obj): sr_type = obj[6] # Forces fake to support iscsi only if sr_type != 'iscsi' and sr_type != 'nfs': raise Failure(['SR_UNKNOWN_DRIVER', sr_type]) host_ref = _db_content['host'].keys()[0] sr_ref = _create_object(table, obj[2]) if sr_type == 'iscsi': vdi_ref = create_vdi('', sr_ref) pbd_ref = create_pbd(host_ref, sr_ref, True) _db_content['SR'][sr_ref]['VDIs'] = [vdi_ref] _db_content['SR'][sr_ref]['PBDs'] = [pbd_ref] _db_content['VDI'][vdi_ref]['SR'] = sr_ref _db_content['PBD'][pbd_ref]['SR'] = sr_ref return sr_ref def _create_vlan(pif_ref, vlan_num, network_ref): pif_rec = get_record('PIF', pif_ref) vlan_pif_ref = _create_object('PIF', {'name-label': 'Fake VLAN PIF', 'MAC': '00:11:22:33:44:55', 'physical': True, 'VLAN': vlan_num, 'device': pif_rec['device'], 'host_uuid': pif_rec['host_uuid']}) return _create_object('VLAN', {'tagged-pif': pif_ref, 'untagged-pif': vlan_pif_ref, 'tag': vlan_num}) def get_all(table): return _db_content[table].keys() def get_all_records(table): return _db_content[table] def _query_matches(record, query): # Simple support for the XenServer query language: # 'field "host"="<uuid>" and field "SR"="<sr uuid>"' # Tested through existing tests (e.g. calls to find_network_with_bridge) and_clauses = query.split(" and ") if len(and_clauses) > 1: matches = True for clause in and_clauses: matches = matches and _query_matches(record, clause) return matches or_clauses = query.split(" or ") if len(or_clauses) > 1: matches = False for clause in or_clauses: matches = matches or _query_matches(record, clause) return matches if query[:4] == 'not ': return not _query_matches(record, query[4:]) # Now it must be a single field - bad queries never match if query[:5] != 'field': return False (field, value) = query[6:].split('=', 1) # Some fields (e.g. name_label, memory_overhead) have double # underscores in the DB, but only single underscores when querying field = field.replace("__", "_").strip(" \"'") value = value.strip(" \"'") # Strings should be directly compared if isinstance(record[field], str): return record[field] == value # But for all other value-checks, convert to a string first # (Notably used for booleans - which can be lower or camel # case and are interpreted/sanitised by XAPI) return str(record[field]).lower() == value.lower() def get_all_records_where(table_name, query): matching_records = {} table = _db_content[table_name] for record in table: if _query_matches(table[record], query): matching_records[record] = table[record] return matching_records def get_record(table, ref): if ref in _db_content[table]: return _db_content[table].get(ref) else: raise Failure(['HANDLE_INVALID', table, ref]) def check_for_session_leaks(): if len(_db_content['session']) > 0: raise exception.NovaException('Sessions have leaked: %s' % _db_content['session']) def as_value(s): """Helper function for simulating XenAPI plugin responses. It escapes and wraps the given argument. """ return '<value>%s</value>' % saxutils.escape(s) def as_json(*args, **kwargs): """Helper function for simulating XenAPI plugin responses for those that are returning JSON. If this function is given plain arguments, then these are rendered as a JSON list. If it's given keyword arguments then these are rendered as a JSON dict. """ arg = args or kwargs return jsonutils.dumps(arg) class Failure(Exception): def __init__(self, details): self.details = details def __str__(self): try: return str(self.details) except Exception: return "XenAPI Fake Failure: %s" % str(self.details) def _details_map(self): return {str(i): self.details[i] for i in range(len(self.details))} class SessionBase(object): """Base class for Fake Sessions.""" def __init__(self, uri): self._session = None xenapi_session.apply_session_helpers(self) def pool_get_default_SR(self, _1, pool_ref): return _db_content['pool'].values()[0]['default-SR'] def VBD_insert(self, _1, vbd_ref, vdi_ref): vbd_rec = get_record('VBD', vbd_ref) get_record('VDI', vdi_ref) vbd_rec['empty'] = False vbd_rec['VDI'] = vdi_ref def VBD_plug(self, _1, ref): rec = get_record('VBD', ref) if rec['currently_attached']: raise Failure(['DEVICE_ALREADY_ATTACHED', ref]) rec['currently_attached'] = True rec['device'] = rec['userdevice'] def VBD_unplug(self, _1, ref): rec = get_record('VBD', ref) if not rec['currently_attached']: raise Failure(['DEVICE_ALREADY_DETACHED', ref]) rec['currently_attached'] = False rec['device'] = '' def VBD_add_to_other_config(self, _1, vbd_ref, key, value): db_ref = _db_content['VBD'][vbd_ref] if 'other_config' not in db_ref: db_ref['other_config'] = {} if key in db_ref['other_config']: raise Failure(['MAP_DUPLICATE_KEY', 'VBD', 'other_config', vbd_ref, key]) db_ref['other_config'][key] = value def VBD_get_other_config(self, _1, vbd_ref): db_ref = _db_content['VBD'][vbd_ref] if 'other_config' not in db_ref: return {} return db_ref['other_config'] def PBD_create(self, _1, pbd_rec): pbd_ref = _create_object('PBD', pbd_rec) _db_content['PBD'][pbd_ref]['currently_attached'] = False return pbd_ref def PBD_plug(self, _1, pbd_ref): rec = get_record('PBD', pbd_ref) if rec['currently_attached']: raise Failure(['DEVICE_ALREADY_ATTACHED', rec]) rec['currently_attached'] = True sr_ref = rec['SR'] _db_content['SR'][sr_ref]['PBDs'] = [pbd_ref] def PBD_unplug(self, _1, pbd_ref): rec = get_record('PBD', pbd_ref) if not rec['currently_attached']: raise Failure(['DEVICE_ALREADY_DETACHED', rec]) rec['currently_attached'] = False sr_ref = rec['SR'] _db_content['SR'][sr_ref]['PBDs'].remove(pbd_ref) def SR_introduce(self, _1, sr_uuid, label, desc, type, content_type, shared, sm_config): ref = None rec = None for ref, rec in _db_content['SR'].iteritems(): if rec.get('uuid') == sr_uuid: # make forgotten = 0 and return ref _db_content['SR'][ref]['forgotten'] = 0 return ref # SR not found in db, so we create one params = {'sr_uuid': sr_uuid, 'label': label, 'desc': desc, 'type': type, 'content_type': content_type, 'shared': shared, 'sm_config': sm_config} sr_ref = _create_object('SR', params) _db_content['SR'][sr_ref]['uuid'] = sr_uuid _db_content['SR'][sr_ref]['forgotten'] = 0 vdi_per_lun = False if type == 'iscsi': # Just to be clear vdi_per_lun = True if vdi_per_lun: # we need to create a vdi because this introduce # is likely meant for a single vdi vdi_ref = create_vdi('', sr_ref) _db_content['SR'][sr_ref]['VDIs'] = [vdi_ref] _db_content['VDI'][vdi_ref]['SR'] = sr_ref return sr_ref def SR_forget(self, _1, sr_ref): _db_content['SR'][sr_ref]['forgotten'] = 1 def SR_scan(self, _1, sr_ref): return def VM_get_xenstore_data(self, _1, vm_ref): return _db_content['VM'][vm_ref].get('xenstore_data', {}) def VM_remove_from_xenstore_data(self, _1, vm_ref, key): db_ref = _db_content['VM'][vm_ref] if 'xenstore_data' not in db_ref: return if key in db_ref['xenstore_data']: del db_ref['xenstore_data'][key] def VM_add_to_xenstore_data(self, _1, vm_ref, key, value): db_ref = _db_content['VM'][vm_ref] if 'xenstore_data' not in db_ref: db_ref['xenstore_data'] = {} db_ref['xenstore_data'][key] = value def VM_pool_migrate(self, _1, vm_ref, host_ref, options): pass def VDI_remove_from_other_config(self, _1, vdi_ref, key): db_ref = _db_content['VDI'][vdi_ref] if 'other_config' not in db_ref: return if key in db_ref['other_config']: del db_ref['other_config'][key] def VDI_add_to_other_config(self, _1, vdi_ref, key, value): db_ref = _db_content['VDI'][vdi_ref] if 'other_config' not in db_ref: db_ref['other_config'] = {} if key in db_ref['other_config']: raise Failure(['MAP_DUPLICATE_KEY', 'VDI', 'other_config', vdi_ref, key]) db_ref['other_config'][key] = value def VDI_copy(self, _1, vdi_to_copy_ref, sr_ref): db_ref = _db_content['VDI'][vdi_to_copy_ref] name_label = db_ref['name_label'] read_only = db_ref['read_only'] sharable = db_ref['sharable'] other_config = db_ref['other_config'].copy() return create_vdi(name_label, sr_ref, sharable=sharable, read_only=read_only, other_config=other_config) def VDI_clone(self, _1, vdi_to_clone_ref): db_ref = _db_content['VDI'][vdi_to_clone_ref] sr_ref = db_ref['SR'] return self.VDI_copy(_1, vdi_to_clone_ref, sr_ref) def host_compute_free_memory(self, _1, ref): # Always return 12GB available return 12 * units.Gi def _plugin_agent_version(self, method, args): return as_json(returncode='0', message='1.0\\r\\n') def _plugin_agent_key_init(self, method, args): return as_json(returncode='D0', message='1') def _plugin_agent_password(self, method, args): return as_json(returncode='0', message='success') def _plugin_agent_inject_file(self, method, args): return as_json(returncode='0', message='success') def _plugin_agent_resetnetwork(self, method, args): return as_json(returncode='0', message='success') def _plugin_agent_agentupdate(self, method, args): url = args["url"] md5 = args["md5sum"] message = "success with %(url)s and hash:%(md5)s" % dict(url=url, md5=md5) return as_json(returncode='0', message=message) def _plugin_noop(self, method, args): return '' def _plugin_pickle_noop(self, method, args): return pickle.dumps(None) def _plugin_migration_transfer_vhd(self, method, args): kwargs = pickle.loads(args['params'])['kwargs'] vdi_ref = self.xenapi_request('VDI.get_by_uuid', (kwargs['vdi_uuid'], )) assert vdi_ref return pickle.dumps(None) _plugin_glance_upload_vhd = _plugin_pickle_noop _plugin_kernel_copy_vdi = _plugin_noop _plugin_kernel_create_kernel_ramdisk = _plugin_noop _plugin_kernel_remove_kernel_ramdisk = _plugin_noop _plugin_migration_move_vhds_into_sr = _plugin_noop def _plugin_xenhost_host_data(self, method, args): return jsonutils.dumps({ 'host_memory': {'total': 10, 'overhead': 20, 'free': 30, 'free-computed': 40}, 'host_uuid': 'fb97583b-baa1-452d-850e-819d95285def', 'host_name-label': 'fake-xenhost', 'host_name-description': 'Default install of XenServer', 'host_hostname': 'fake-xenhost', 'host_ip_address': '10.219.10.24', 'enabled': 'true', 'host_capabilities': ['xen-3.0-x86_64', 'xen-3.0-x86_32p', 'hvm-3.0-x86_32', 'hvm-3.0-x86_32p', 'hvm-3.0-x86_64'], 'host_other-config': { 'agent_start_time': '1412774967.', 'iscsi_iqn': 'iqn.2014-10.org.example:39fa9ee3', 'boot_time': '1412774885.', }, 'host_cpu_info': { 'physical_features': '0098e3fd-bfebfbff-00000001-28100800', 'modelname': 'Intel(R) Xeon(R) CPU X3430 @ 2.40GHz', 'vendor': 'GenuineIntel', 'features': '0098e3fd-bfebfbff-00000001-28100800', 'family': 6, 'maskable': 'full', 'cpu_count': 4, 'socket_count': '1', 'flags': 'fpu de tsc msr pae mce cx8 apic sep mtrr mca ' 'cmov pat clflush acpi mmx fxsr sse sse2 ss ht ' 'nx constant_tsc nonstop_tsc aperfmperf pni vmx ' 'est ssse3 sse4_1 sse4_2 popcnt hypervisor ida ' 'tpr_shadow vnmi flexpriority ept vpid', 'stepping': 5, 'model': 30, 'features_after_reboot': '0098e3fd-bfebfbff-00000001-28100800', 'speed': '2394.086' }, }) def _plugin_poweraction(self, method, args): return jsonutils.dumps({"power_action": method[5:]}) _plugin_xenhost_host_reboot = _plugin_poweraction _plugin_xenhost_host_startup = _plugin_poweraction _plugin_xenhost_host_shutdown = _plugin_poweraction def _plugin_xenhost_set_host_enabled(self, method, args): enabled = 'enabled' if args.get('enabled') == 'true' else 'disabled' return jsonutils.dumps({"status": enabled}) def _plugin_xenhost_host_uptime(self, method, args): return jsonutils.dumps({"uptime": "fake uptime"}) def _plugin_xenhost_get_pci_device_details(self, method, args): """Simulate the ouput of three pci devices. Both of those devices are available for pci passtrough but only one will match with the pci whitelist used in the method test_pci_passthrough_devices_*(). Return a single list. """ # Driver is not pciback dev_bad1 = ["Slot:\t0000:86:10.0", "Class:\t0604", "Vendor:\t10b5", "Device:\t8747", "Rev:\tba", "Driver:\tpcieport", "\n"] # Driver is pciback but vendor and device are bad dev_bad2 = ["Slot:\t0000:88:00.0", "Class:\t0300", "Vendor:\t0bad", "Device:\tcafe", "SVendor:\t10de", "SDevice:\t100d", "Rev:\ta1", "Driver:\tpciback", "\n"] # Driver is pciback and vendor, device are used for matching dev_good = ["Slot:\t0000:87:00.0", "Class:\t0300", "Vendor:\t10de", "Device:\t11bf", "SVendor:\t10de", "SDevice:\t100d", "Rev:\ta1", "Driver:\tpciback", "\n"] lspci_output = "\n".join(dev_bad1 + dev_bad2 + dev_good) return pickle.dumps(lspci_output) def _plugin_xenhost_get_pci_type(self, method, args): return pickle.dumps("type-PCI") def _plugin_console_get_console_log(self, method, args): dom_id = args["dom_id"] if dom_id == 0: raise Failure('Guest does not have a console') return base64.b64encode(zlib.compress("dom_id: %s" % dom_id)) def _plugin_nova_plugin_version_get_version(self, method, args): return pickle.dumps("1.2") def _plugin_xenhost_query_gc(self, method, args): return pickle.dumps("False") def host_call_plugin(self, _1, _2, plugin, method, args): func = getattr(self, '_plugin_%s_%s' % (plugin, method), None) if not func: raise Exception('No simulation in host_call_plugin for %s,%s' % (plugin, method)) return func(method, args) def VDI_get_virtual_size(self, *args): return 1 * units.Gi def VDI_resize_online(self, *args): return 'derp' VDI_resize = VDI_resize_online def _VM_reboot(self, session, vm_ref): db_ref = _db_content['VM'][vm_ref] if db_ref['power_state'] != 'Running': raise Failure(['VM_BAD_POWER_STATE', 'fake-opaque-ref', db_ref['power_state'].lower(), 'halted']) db_ref['power_state'] = 'Running' db_ref['domid'] = random.randrange(1, 1 << 16) def VM_clean_reboot(self, session, vm_ref): return self._VM_reboot(session, vm_ref) def VM_hard_reboot(self, session, vm_ref): return self._VM_reboot(session, vm_ref) def VM_hard_shutdown(self, session, vm_ref): db_ref = _db_content['VM'][vm_ref] db_ref['power_state'] = 'Halted' db_ref['domid'] = -1 VM_clean_shutdown = VM_hard_shutdown def VM_suspend(self, session, vm_ref): db_ref = _db_content['VM'][vm_ref] db_ref['power_state'] = 'Suspended' def VM_pause(self, session, vm_ref): db_ref = _db_content['VM'][vm_ref] db_ref['power_state'] = 'Paused' def pool_eject(self, session, host_ref): pass def pool_join(self, session, hostname, username, password): pass def pool_set_name_label(self, session, pool_ref, name): pass def host_migrate_receive(self, session, destref, nwref, options): return "fake_migrate_data" def VM_assert_can_migrate(self, session, vmref, migrate_data, live, vdi_map, vif_map, options): pass def VM_migrate_send(self, session, mref, migrate_data, live, vdi_map, vif_map, options): pass def VM_remove_from_blocked_operations(self, session, vm_ref, key): # operation is idempotent, XenServer doesn't care if the key exists _db_content['VM'][vm_ref]['blocked_operations'].pop(key, None) def xenapi_request(self, methodname, params): if methodname.startswith('login'): self._login(methodname, params) return None elif methodname == 'logout' or methodname == 'session.logout': self._logout() return None else: full_params = (self._session,) + params meth = getattr(self, methodname, None) if meth is None: LOG.debug('Raising NotImplemented') raise NotImplementedError( _('xenapi.fake does not have an implementation for %s') % methodname) return meth(*full_params) def _login(self, method, params): self._session = str(uuid.uuid4()) _session_info = {'uuid': str(uuid.uuid4()), 'this_host': _db_content['host'].keys()[0]} _db_content['session'][self._session] = _session_info def _logout(self): s = self._session self._session = None if s not in _db_content['session']: raise exception.NovaException( "Logging out a session that is invalid or already logged " "out: %s" % s) del _db_content['session'][s] def __getattr__(self, name): if name == 'handle': return self._session elif name == 'xenapi': return _Dispatcher(self.xenapi_request, None) elif name.startswith('login') or name.startswith('slave_local'): return lambda *params: self._login(name, params) elif name.startswith('Async'): return lambda *params: self._async(name, params) elif '.' in name: impl = getattr(self, name.replace('.', '_')) if impl is not None: def callit(*params): LOG.debug('Calling %(name)s %(impl)s', {'name': name, 'impl': impl}) self._check_session(params) return impl(*params) return callit if self._is_gettersetter(name, True): LOG.debug('Calling getter %s', name) return lambda *params: self._getter(name, params) elif self._is_gettersetter(name, False): LOG.debug('Calling setter %s', name) return lambda *params: self._setter(name, params) elif self._is_create(name): return lambda *params: self._create(name, params) elif self._is_destroy(name): return lambda *params: self._destroy(name, params) elif name == 'XenAPI': return FakeXenAPI() else: return None def _is_gettersetter(self, name, getter): bits = name.split('.') return (len(bits) == 2 and bits[0] in _CLASSES and bits[1].startswith(getter and 'get_' or 'set_')) def _is_create(self, name): return self._is_method(name, 'create') def _is_destroy(self, name): return self._is_method(name, 'destroy') def _is_method(self, name, meth): bits = name.split('.') return (len(bits) == 2 and bits[0] in _CLASSES and bits[1] == meth) def _getter(self, name, params): self._check_session(params) (cls, func) = name.split('.') if func == 'get_all': self._check_arg_count(params, 1) return get_all(cls) if func == 'get_all_records': self._check_arg_count(params, 1) return get_all_records(cls) if func == 'get_all_records_where': self._check_arg_count(params, 2) return get_all_records_where(cls, params[1]) if func == 'get_record': self._check_arg_count(params, 2) return get_record(cls, params[1]) if func in ('get_by_name_label', 'get_by_uuid'): self._check_arg_count(params, 2) return_singleton = (func == 'get_by_uuid') return self._get_by_field( _db_content[cls], func[len('get_by_'):], params[1], return_singleton=return_singleton) if len(params) == 2: field = func[len('get_'):] ref = params[1] if (ref in _db_content[cls]): if (field in _db_content[cls][ref]): return _db_content[cls][ref][field] else: raise Failure(['HANDLE_INVALID', cls, ref]) LOG.debug('Raising NotImplemented') raise NotImplementedError( _('xenapi.fake does not have an implementation for %s or it has ' 'been called with the wrong number of arguments') % name) def _setter(self, name, params): self._check_session(params) (cls, func) = name.split('.') if len(params) == 3: field = func[len('set_'):] ref = params[1] val = params[2] if (ref in _db_content[cls] and field in _db_content[cls][ref]): _db_content[cls][ref][field] = val return LOG.debug('Raising NotImplemented') raise NotImplementedError( 'xenapi.fake does not have an implementation for %s or it has ' 'been called with the wrong number of arguments or the database ' 'is missing that field' % name) def _create(self, name, params): self._check_session(params) is_sr_create = name == 'SR.create' is_vlan_create = name == 'VLAN.create' # Storage Repositories have a different API expected = is_sr_create and 10 or is_vlan_create and 4 or 2 self._check_arg_count(params, expected) (cls, _) = name.split('.') ref = (is_sr_create and _create_sr(cls, params) or is_vlan_create and _create_vlan(params[1], params[2], params[3]) or _create_object(cls, params[1])) # Call hook to provide any fixups needed (ex. creating backrefs) after_hook = 'after_%s_create' % cls if after_hook in globals(): globals()[after_hook](ref, params[1]) obj = get_record(cls, ref) # Add RO fields if cls == 'VM': obj['power_state'] = 'Halted' return ref def _destroy(self, name, params): self._check_session(params) self._check_arg_count(params, 2) table = name.split('.')[0] ref = params[1] if ref not in _db_content[table]: raise Failure(['HANDLE_INVALID', table, ref]) # Call destroy function (if exists) destroy_func = globals().get('destroy_%s' % table.lower()) if destroy_func: destroy_func(ref) else: del _db_content[table][ref] def _async(self, name, params): task_ref = create_task(name) task = _db_content['task'][task_ref] func = name[len('Async.'):] try: result = self.xenapi_request(func, params[1:]) if result: result = as_value(result) task['result'] = result task['status'] = 'success' except Failure as exc: task['error_info'] = exc.details task['status'] = 'failed' task['finished'] = timeutils.utcnow() return task_ref def _check_session(self, params): if (self._session is None or self._session not in _db_content['session']): raise Failure(['HANDLE_INVALID', 'session', self._session]) if len(params) == 0 or params[0] != self._session: LOG.debug('Raising NotImplemented') raise NotImplementedError('Call to XenAPI without using .xenapi') def _check_arg_count(self, params, expected): actual = len(params) if actual != expected: raise Failure(['MESSAGE_PARAMETER_COUNT_MISMATCH', expected, actual]) def _get_by_field(self, recs, k, v, return_singleton): result = [] for ref, rec in recs.iteritems(): if rec.get(k) == v: result.append(ref) if return_singleton: try: return result[0] except IndexError: raise Failure(['UUID_INVALID', v, result, recs, k]) return result class FakeXenAPI(object): def __init__(self): self.Failure = Failure # Based upon _Method from xmlrpclib. class _Dispatcher(object): def __init__(self, send, name): self.__send = send self.__name = name def __repr__(self): if self.__name: return '<xenapi.fake._Dispatcher for %s>' % self.__name else: return '<xenapi.fake._Dispatcher>' def __getattr__(self, name): if self.__name is None: return _Dispatcher(self.__send, name) else: return _Dispatcher(self.__send, "%s.%s" % (self.__name, name)) def __call__(self, *args): return self.__send(self.__name, args)
from enum import Enum, IntEnum def is_int(var): try: _ = int(var) return True except (ValueError, TypeError): return False def is_int_range(minimum, maximum): def wrapped(var): if is_int(var): var = int(var) return (minimum <= var) and (maximum >= var) else: return False return wrapped def is_on_off(var): return is_int(var) and int(var) in [0, 1] def is_in_list(l): def wrapped(var): return var in l return wrapped class SetReq(Enum): def __new__(cls, value, default_value, is_legal): obj = object.__new__(cls) obj._value_ = value obj._default_value_ = default_value obj._is_legal_ = is_legal return obj def __repr__(self): return str(self.value) def get_default_value(self): return self._default_value_ def is_legal(self, value): return self._is_legal_(value) ALL = (-1, 0, lambda _: False) V_TEMP = (0, 0, is_int) V_HUM = (1, 0, is_int) V_LIGHT = (2, 0, is_on_off) V_DIMMER = (3, 0, is_int_range(0, 100)) V_PRESSURE = (4, 0, is_int) V_FORECAST = (5, "unknown", is_in_list(["stable", "sunny", "cloudy", "unstable", "thunderstorm", "unknown"])) V_RAIN = (6, 0, is_int) V_RAINRATE = (7, 0, is_int) V_WIND = (8, 0, is_int) V_GUST = (9, "", lambda _: True) V_DIRECTION = (10, "", lambda _: True) V_UV = (11, 0, is_int) V_WEIGHT = (12, 0, is_int) V_DISTANCE = (13, 0, is_int) V_IMPEDANCE = (14, 0, is_int) V_ARMED = (15, 0, is_on_off) V_TRIPPED = (16, 0, is_on_off) V_WATT = (17, 0, is_int) V_KWH = (18, 0, is_int) V_SCENE_ON = (19, "", lambda _: True) V_SCENE_OFF = (20, "", lambda _: True) V_HEATER = (21, "Off", is_in_list(["Off", "HeatOn", "CoolOn", "AutoChangeOver"])) V_HEATER_SW = (22, 0, is_on_off) V_LIGHT_LEVEL = (23, 0, is_int_range(0, 100)) V_VAR1 = (24, "", lambda _: True) V_VAR2 = (25, "", lambda _: True) V_VAR3 = (26, "", lambda _: True) V_VAR4 = (27, "", lambda _: True) V_VAR5 = (28, "", lambda _: True) V_UP = (29, "", lambda _: True) V_DOWN = (30, "", lambda _: True) V_STOP = (31, "", lambda _: True) V_IR_SEND = (32, "", lambda _: True) V_IR_RECEIVE = (33, "", lambda _: True) V_FLOW = (34, 0, is_int) V_VOLUME = (35, 0, is_int) V_LOCK_STATUS = (36, 0, is_on_off) V_DUST_LEVEL = (37, 0, is_int) V_VOLTAGE = (38, 0, is_int) V_CURRENT = (39, 0, is_int) class Presentation(Enum): def __new__(cls, value, is_sensor, setreqs=None): """ :type value: int :type is_sensor: bool :type setreqs: list[SetReq] :return: Presentation """ if not setreqs: setreqs = [] obj = object.__new__(cls) obj._value_ = value obj._is_sensor_ = is_sensor obj._setreqs_ = setreqs return obj def __repr__(self): return str(self.value) def is_sensor(self): """ :rtype: bool """ return self._is_sensor_ def get_setreqs(self): """ :rtype: list[SetReq] """ return self._setreqs_ ALL = (-1, False) S_DOOR = (0, True, [SetReq.V_TRIPPED]) S_MOTION = (1, True, [SetReq.V_TRIPPED]) S_SMOKE = (2, True, [SetReq.V_TRIPPED]) S_LIGHT = (3, False, [SetReq.V_LIGHT, SetReq.V_LIGHT_LEVEL]) S_DIMMER = (4, False, [SetReq.V_DIMMER, SetReq.V_LIGHT]) S_COVER = (5, False, [SetReq.V_UP, SetReq.V_DOWN, SetReq.V_STOP]) S_TEMP = (6, True, [SetReq.V_TEMP]) S_HUM = (7, True, [SetReq.V_HUM]) S_BARO = (8, True, [SetReq.V_PRESSURE]) S_WIND = (9, True, [SetReq.V_WIND, SetReq.V_GUST, SetReq.V_DIRECTION]) S_RAIN = (10, True, [SetReq.V_RAIN, SetReq.V_RAINRATE]) S_UV = (11, True, [SetReq.V_UV]) S_WEIGHT = (12, True, [SetReq.V_WEIGHT]) S_POWER = (13, True, [SetReq.V_WATT, SetReq.V_KWH, SetReq.V_IMPEDANCE, SetReq.V_VOLTAGE, SetReq.V_CURRENT]) S_HEATER = (14, False, [SetReq.V_HEATER, SetReq.V_HEATER_SW]) S_DISTANCE = (15, True, [SetReq.V_DISTANCE]) S_LIGHT_LEVEL = (16, True, [SetReq.V_LIGHT_LEVEL]) S_ARDUINO_NODE = (17, False) S_ARDUINO_REPEATER_NODE = (18, False) S_LOCK = (19, False, [SetReq.V_LOCK_STATUS]) S_IR = (20, False, [SetReq.V_IR_RECEIVE, SetReq.V_IR_SEND]) S_WATER = (21, True, [SetReq.V_FLOW, SetReq.V_VOLUME]) S_AIR_QUALITY = (22, True) S_CUSTOM = (23, True, [SetReq.V_VAR1, SetReq.V_VAR2, SetReq.V_VAR3, SetReq.V_VAR4, SetReq.V_VAR5]) S_DUST = (24, True, [SetReq.V_DUST_LEVEL]) S_SCENE_CONTROLLER = (25, False, [SetReq.V_SCENE_OFF, SetReq.V_SCENE_ON]) class Internal(Enum): def __repr__(self): return str(self.value) ALL = -1 I_BATTERY_LEVEL = 0 I_TIME = 1 I_VERSION = 2 I_ID_REQUEST = 3 I_ID_RESPONSE = 4 I_INCLUSION_MODE = 5 I_CONFIG = 6 I_FIND_PARENT = 7 I_FIND_PARENT_RESPONSE = 8 I_LOG_MESSAGE = 9 I_CHILDREN = 10 I_SKETCH_NAME = 11 I_SKETCH_VERSION = 12 I_REBOOT = 13 I_GATEWAY_READY = 14 class Stream(IntEnum): ALL = -1 ST_FIRMWARE_CONFIG_REQUEST = 0 ST_FIRMWARE_CONFIG_RESPONSE = 1 ST_FIRMWARE_REQUEST = 2 ST_FIRMWARE_RESPONSE = 3 ST_SOUND = 4 ST_IMAGE = 5 class MessageType(Enum): def __new__(cls, value, associated_enum): obj = object.__new__(cls) obj._value_ = value obj._associated_enum_ = associated_enum return obj def __repr__(self): return str(self.value) def get_associated_enum(self): return self._associated_enum_ PRESENTATION = (0, Presentation) SET = (1, SetReq) REQ = (2, SetReq) INTERNAL = (3, Internal) STREAM = (4, Stream)
# -*- coding: utf-8 -*- ''' Functions to calculate spike-triggered average and spike-field coherence of analog signals. :copyright: Copyright 2015-2016 by the Elephant team, see `doc/authors.rst`. :license: Modified BSD, see LICENSE.txt for details. ''' from __future__ import division, print_function, unicode_literals import numpy as np import scipy.signal import quantities as pq from neo.core import AnalogSignal, SpikeTrain import warnings from .conversion import BinnedSpikeTrain def spike_triggered_average(signal, spiketrains, window): """ Calculates the spike-triggered averages of analog signals in a time window relative to the spike times of a corresponding spiketrain for multiple signals each. The function receives n analog signals and either one or n spiketrains. In case it is one spiketrain this one is muliplied n-fold and used for each of the n analog signals. Parameters ---------- signal : neo AnalogSignal object 'signal' contains n analog signals. spiketrains : one SpikeTrain or one numpy ndarray or a list of n of either of these. 'spiketrains' contains the times of the spikes in the spiketrains. window : tuple of 2 Quantity objects with dimensions of time. 'window' is the start time and the stop time, relative to a spike, of the time interval for signal averaging. If the window size is not a multiple of the sampling interval of the signal the window will be extended to the next multiple. Returns ------- result_sta : neo AnalogSignal object 'result_sta' contains the spike-triggered averages of each of the analog signals with respect to the spikes in the corresponding spiketrains. The length of 'result_sta' is calculated as the number of bins from the given start and stop time of the averaging interval and the sampling rate of the analog signal. If for an analog signal no spike was either given or all given spikes had to be ignored because of a too large averaging interval, the corresponding returned analog signal has all entries as nan. The number of used spikes and unused spikes for each analog signal are returned as annotations to the returned AnalogSignal object. Examples -------- >>> signal = neo.AnalogSignal(np.array([signal1, signal2]).T, units='mV', ... sampling_rate=10/ms) >>> stavg = spike_triggered_average(signal, [spiketrain1, spiketrain2], ... (-5 * ms, 10 * ms)) """ # checking compatibility of data and data types # window_starttime: time to specify the start time of the averaging # interval relative to a spike # window_stoptime: time to specify the stop time of the averaging # interval relative to a spike window_starttime, window_stoptime = window if not (isinstance(window_starttime, pq.quantity.Quantity) and window_starttime.dimensionality.simplified == pq.Quantity(1, "s").dimensionality): raise TypeError("The start time of the window (window[0]) " "must be a time quantity.") if not (isinstance(window_stoptime, pq.quantity.Quantity) and window_stoptime.dimensionality.simplified == pq.Quantity(1, "s").dimensionality): raise TypeError("The stop time of the window (window[1]) " "must be a time quantity.") if window_stoptime <= window_starttime: raise ValueError("The start time of the window (window[0]) must be " "earlier than the stop time of the window (window[1]).") # checks on signal if not isinstance(signal, AnalogSignal): raise TypeError( "Signal must be an AnalogSignal, not %s." % type(signal)) if len(signal.shape) > 1: # num_signals: number of analog signals num_signals = signal.shape[1] else: raise ValueError("Empty analog signal, hence no averaging possible.") if window_stoptime - window_starttime > signal.t_stop - signal.t_start: raise ValueError("The chosen time window is larger than the " "time duration of the signal.") # spiketrains type check if isinstance(spiketrains, (np.ndarray, SpikeTrain)): spiketrains = [spiketrains] elif isinstance(spiketrains, list): for st in spiketrains: if not isinstance(st, (np.ndarray, SpikeTrain)): raise TypeError( "spiketrains must be a SpikeTrain, a numpy ndarray, or a " "list of one of those, not %s." % type(spiketrains)) else: raise TypeError( "spiketrains must be a SpikeTrain, a numpy ndarray, or a list of " "one of those, not %s." % type(spiketrains)) # multiplying spiketrain in case only a single spiketrain is given if len(spiketrains) == 1 and num_signals != 1: template = spiketrains[0] spiketrains = [] for i in range(num_signals): spiketrains.append(template) # checking for matching numbers of signals and spiketrains if num_signals != len(spiketrains): raise ValueError( "The number of signals and spiketrains has to be the same.") # checking the times of signal and spiketrains for i in range(num_signals): if spiketrains[i].t_start < signal.t_start: raise ValueError( "The spiketrain indexed by %i starts earlier than " "the analog signal." % i) if spiketrains[i].t_stop > signal.t_stop: raise ValueError( "The spiketrain indexed by %i stops later than " "the analog signal." % i) # *** Main algorithm: *** # window_bins: number of bins of the chosen averaging interval window_bins = int(np.ceil(((window_stoptime - window_starttime) * signal.sampling_rate).simplified)) # result_sta: array containing finally the spike-triggered averaged signal result_sta = AnalogSignal(np.zeros((window_bins, num_signals)), sampling_rate=signal.sampling_rate, units=signal.units) # setting of correct times of the spike-triggered average # relative to the spike result_sta.t_start = window_starttime used_spikes = np.zeros(num_signals, dtype=int) unused_spikes = np.zeros(num_signals, dtype=int) total_used_spikes = 0 for i in range(num_signals): # summing over all respective signal intervals around spiketimes for spiketime in spiketrains[i]: # checks for sufficient signal data around spiketime if (spiketime + window_starttime >= signal.t_start and spiketime + window_stoptime <= signal.t_stop): # calculating the startbin in the analog signal of the # averaging window for spike startbin = int(np.floor(((spiketime + window_starttime - signal.t_start) * signal.sampling_rate).simplified)) # adds the signal in selected interval relative to the spike result_sta[:, i] += signal[ startbin: startbin + window_bins, i] # counting of the used spikes used_spikes[i] += 1 else: # counting of the unused spikes unused_spikes[i] += 1 # normalization result_sta[:, i] = result_sta[:, i] / used_spikes[i] total_used_spikes += used_spikes[i] if total_used_spikes == 0: warnings.warn( "No spike at all was either found or used for averaging") result_sta.annotate(used_spikes=used_spikes, unused_spikes=unused_spikes) return result_sta def spike_field_coherence(signal, spiketrain, **kwargs): """ Calculates the spike-field coherence between a analog signal(s) and a (binned) spike train. The current implementation makes use of scipy.signal.coherence(). Additional kwargs will will be directly forwarded to scipy.signal.coherence(), except for the axis parameter and the sampling frequency, which will be extracted from the input signals. The spike_field_coherence function receives an analog signal array and either a binned spike train or a spike train containing the original spike times. In case of original spike times the spike train is binned according to the sampling rate of the analog signal array. The AnalogSignal object can contain one or multiple signal traces. In case of multiple signal traces, the spike field coherence is calculated individually for each signal trace and the spike train. Parameters ---------- signal : neo AnalogSignal object 'signal' contains n analog signals. spiketrain : SpikeTrain or BinnedSpikeTrain Single spike train to perform the analysis on. The binsize of the binned spike train must match the sampling_rate of signal. **kwargs: All kwargs are passed to `scipy.signal.coherence()`. Returns ------- coherence : complex Quantity array contains the coherence values calculated for each analog signal trace in combination with the spike train. The first dimension corresponds to the frequency, the second to the number of the signal trace. frequencies : Quantity array contains the frequency values corresponding to the first dimension of the 'coherence' array Examples -------- Plot the SFC between a regular spike train at 20 Hz, and two sinusoidal time series at 20 Hz and 23 Hz, respectively. >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from quantities import s, ms, mV, Hz, kHz >>> import neo, elephant >>> t = pq.Quantity(range(10000),units='ms') >>> f1, f2 = 20. * Hz, 23. * Hz >>> signal = neo.AnalogSignal(np.array([ np.sin(f1 * 2. * np.pi * t.rescale(s)), np.sin(f2 * 2. * np.pi * t.rescale(s))]).T, units=pq.mV, sampling_rate=1. * kHz) >>> spiketrain = neo.SpikeTrain( range(t[0], t[-1], 50), units='ms', t_start=t[0], t_stop=t[-1]) >>> sfc, freqs = elephant.sta.spike_field_coherence( signal, spiketrain, window='boxcar') >>> plt.plot(freqs, sfc[:,0]) >>> plt.plot(freqs, sfc[:,1]) >>> plt.xlabel('Frequency [Hz]') >>> plt.ylabel('SFC') >>> plt.xlim((0, 60)) >>> plt.show() """ if not hasattr(scipy.signal, 'coherence'): raise AttributeError('scipy.signal.coherence is not available. The sfc ' 'function uses scipy.signal.coherence for ' 'the coherence calculation. This function is ' 'available for scipy version 0.16 or newer. ' 'Please update you scipy version.') # spiketrains type check if not isinstance(spiketrain, (SpikeTrain, BinnedSpikeTrain)): raise TypeError( "spiketrain must be of type SpikeTrain or BinnedSpikeTrain, " "not %s." % type(spiketrain)) # checks on analogsignal if not isinstance(signal, AnalogSignal): raise TypeError( "Signal must be an AnalogSignal, not %s." % type(signal)) if len(signal.shape) > 1: # num_signals: number of individual traces in the analog signal num_signals = signal.shape[1] elif len(signal.shape) == 1: num_signals = 1 else: raise ValueError("Empty analog signal.") len_signals = signal.shape[0] # bin spiketrain if necessary if isinstance(spiketrain, SpikeTrain): spiketrain = BinnedSpikeTrain( spiketrain, binsize=signal.sampling_period) # check the start and stop times of signal and spike trains if spiketrain.t_start < signal.t_start: raise ValueError( "The spiketrain starts earlier than the analog signal.") if spiketrain.t_stop > signal.t_stop: raise ValueError( "The spiketrain stops later than the analog signal.") # check equal time resolution for both signals if spiketrain.binsize != signal.sampling_period: raise ValueError( "The spiketrain and signal must have a " "common sampling frequency / binsize") # calculate how many bins to add on the left of the binned spike train delta_t = spiketrain.t_start - signal.t_start if delta_t % spiketrain.binsize == 0: left_edge = int((delta_t / spiketrain.binsize).magnitude) else: raise ValueError("Incompatible binning of spike train and LFP") right_edge = int(left_edge + spiketrain.num_bins) # duplicate spike trains spiketrain_array = np.zeros((1, len_signals)) spiketrain_array[0, left_edge:right_edge] = spiketrain.to_array() spiketrains_array = np.repeat(spiketrain_array, repeats=num_signals, axis=0).transpose() # calculate coherence frequencies, sfc = scipy.signal.coherence( spiketrains_array, signal.magnitude, fs=signal.sampling_rate.rescale('Hz').magnitude, axis=0, **kwargs) return (pq.Quantity(sfc, units=pq.dimensionless), pq.Quantity(frequencies, units=pq.Hz))
""" Generic helpers for LLVM code generation. """ from __future__ import print_function, division, absolute_import import collections from contextlib import contextmanager import functools import re from llvmlite import ir from llvmlite.llvmpy.core import Constant, Type import llvmlite.llvmpy.core as lc from . import utils true_bit = Constant.int(Type.int(1), 1) false_bit = Constant.int(Type.int(1), 0) true_byte = Constant.int(Type.int(8), 1) false_byte = Constant.int(Type.int(8), 0) intp_t = Type.int(utils.MACHINE_BITS) def as_bool_byte(builder, value): return builder.zext(value, Type.int(8)) def as_bool_bit(builder, value): return builder.icmp(lc.ICMP_NE, value, Constant.null(value.type)) def make_anonymous_struct(builder, values, struct_type=None): """ Create an anonymous struct containing the given LLVM *values*. """ if struct_type is None: struct_type = Type.struct([v.type for v in values]) struct_val = Constant.undef(struct_type) for i, v in enumerate(values): struct_val = builder.insert_value(struct_val, v, i) return struct_val def make_bytearray(buf): """ Make a byte array constant from *buf*. """ b = bytearray(buf) n = len(b) return ir.Constant(ir.ArrayType(ir.IntType(8), n), b) _struct_proxy_cache = {} def create_struct_proxy(fe_type, kind='value'): """ Returns a specialized StructProxy subclass for the given fe_type. """ cache_key = (fe_type, kind) res = _struct_proxy_cache.get(cache_key) if res is None: base = {'value': ValueStructProxy, 'data': DataStructProxy, }[kind] clsname = base.__name__ + '_' + str(fe_type) bases = (base,) clsmembers = dict(_fe_type=fe_type) res = type(clsname, bases, clsmembers) _struct_proxy_cache[cache_key] = res return res class _StructProxy(object): """ Creates a `Structure` like interface that is constructed with information from DataModel instance. FE type must have a data model that is a subclass of StructModel. """ # The following class members must be overridden by subclass _fe_type = None def __init__(self, context, builder, value=None, ref=None): from numba import datamodel # Avoid circular import self._context = context self._datamodel = self._context.data_model_manager[self._fe_type] if not isinstance(self._datamodel, datamodel.StructModel): raise TypeError("Not a structure model: {0}".format(self._datamodel)) self._builder = builder self._be_type = self._get_be_type(self._datamodel) assert not is_pointer(self._be_type) if ref is not None: assert value is None if ref.type.pointee != self._be_type: raise AssertionError("bad ref type: expected %s, got %s" % (self._be_type.as_pointer(), ref.type)) self._value = ref else: self._value = alloca_once(self._builder, self._be_type, zfill=True) if value is not None: self._builder.store(value, self._value) def _get_be_type(self, datamodel): raise NotImplementedError def _cast_member_to_value(self, index, val): raise NotImplementedError def _cast_member_from_value(self, index, val): raise NotImplementedError def _get_ptr_by_index(self, index): return gep_inbounds(self._builder, self._value, 0, index) def _get_ptr_by_name(self, attrname): index = self._datamodel.get_field_position(attrname) return self._get_ptr_by_index(index) def __getattr__(self, field): """ Load the LLVM value of the named *field*. """ if not field.startswith('_'): return self[self._datamodel.get_field_position(field)] else: raise AttributeError(field) def __setattr__(self, field, value): """ Store the LLVM *value* into the named *field*. """ if field.startswith('_'): return super(_StructProxy, self).__setattr__(field, value) self[self._datamodel.get_field_position(field)] = value def __getitem__(self, index): """ Load the LLVM value of the field at *index*. """ member_val = self._builder.load(self._get_ptr_by_index(index)) return self._cast_member_to_value(index, member_val) def __setitem__(self, index, value): """ Store the LLVM *value* into the field at *index*. """ ptr = self._get_ptr_by_index(index) value = self._cast_member_from_value(index, value) if value.type != ptr.type.pointee: if (is_pointer(value.type) and is_pointer(ptr.type.pointee) and value.type.pointee == ptr.type.pointee.pointee): # Differ by address-space only # Auto coerce it value = self._context.addrspacecast(self._builder, value, ptr.type.pointee.addrspace) else: raise TypeError("Invalid store of {value.type} to " "{ptr.type.pointee} in " "{self._datamodel}".format(value=value, ptr=ptr, self=self)) self._builder.store(value, ptr) def __len__(self): """ Return the number of fields. """ return self._datamodel.field_count def _getpointer(self): """ Return the LLVM pointer to the underlying structure. """ return self._value def _getvalue(self): """ Load and return the value of the underlying LLVM structure. """ return self._builder.load(self._value) def _setvalue(self, value): """Store the value in this structure""" assert not is_pointer(value.type) assert value.type == self._type, (value.type, self._type) self._builder.store(value, self._value) class ValueStructProxy(_StructProxy): """ Create a StructProxy suitable for accessing regular values (e.g. LLVM values or alloca slots). """ def _get_be_type(self, datamodel): return datamodel.get_value_type() def _cast_member_to_value(self, index, val): return val def _cast_member_from_value(self, index, val): return val class DataStructProxy(_StructProxy): """ Create a StructProxy suitable for accessing data persisted in memory. """ def _get_be_type(self, datamodel): return datamodel.get_data_type() def _cast_member_to_value(self, index, val): model = self._datamodel.get_model(index) return model.from_data(self._builder, val) def _cast_member_from_value(self, index, val): model = self._datamodel.get_model(index) return model.as_data(self._builder, val) class Structure(object): """ A high-level object wrapping a alloca'ed LLVM structure, including named fields and attribute access. """ # XXX Should this warrant several separate constructors? def __init__(self, context, builder, value=None, ref=None, cast_ref=False): self._type = context.get_struct_type(self) self._context = context self._builder = builder if ref is None: self._value = alloca_once(builder, self._type) if value is not None: assert not is_pointer(value.type) assert value.type == self._type, (value.type, self._type) builder.store(value, self._value) else: assert value is None assert is_pointer(ref.type) if self._type != ref.type.pointee: if cast_ref: ref = builder.bitcast(ref, Type.pointer(self._type)) else: raise TypeError( "mismatching pointer type: got %s, expected %s" % (ref.type.pointee, self._type)) self._value = ref self._namemap = {} self._fdmap = [] self._typemap = [] base = Constant.int(Type.int(), 0) for i, (k, tp) in enumerate(self._fields): self._namemap[k] = i self._fdmap.append((base, Constant.int(Type.int(), i))) self._typemap.append(tp) def _get_ptr_by_index(self, index): ptr = self._builder.gep(self._value, self._fdmap[index], inbounds=True) return ptr def _get_ptr_by_name(self, attrname): return self._get_ptr_by_index(self._namemap[attrname]) def __getattr__(self, field): """ Load the LLVM value of the named *field*. """ if not field.startswith('_'): return self[self._namemap[field]] else: raise AttributeError(field) def __setattr__(self, field, value): """ Store the LLVM *value* into the named *field*. """ if field.startswith('_'): return super(Structure, self).__setattr__(field, value) self[self._namemap[field]] = value def __getitem__(self, index): """ Load the LLVM value of the field at *index*. """ return self._builder.load(self._get_ptr_by_index(index)) def __setitem__(self, index, value): """ Store the LLVM *value* into the field at *index*. """ ptr = self._get_ptr_by_index(index) if ptr.type.pointee != value.type: fmt = "Type mismatch: __setitem__(%d, ...) expected %r but got %r" raise AssertionError(fmt % (index, str(ptr.type.pointee), str(value.type))) self._builder.store(value, ptr) def __len__(self): """ Return the number of fields. """ return len(self._namemap) def _getpointer(self): """ Return the LLVM pointer to the underlying structure. """ return self._value def _getvalue(self): """ Load and return the value of the underlying LLVM structure. """ return self._builder.load(self._value) def _setvalue(self, value): """Store the value in this structure""" assert not is_pointer(value.type) assert value.type == self._type, (value.type, self._type) self._builder.store(value, self._value) # __iter__ is derived by Python from __len__ and __getitem__ def alloca_once(builder, ty, size=None, name='', zfill=False): """Allocate stack memory at the entry block of the current function pointed by ``builder`` withe llvm type ``ty``. The optional ``size`` arg set the number of element to allocate. The default is 1. The optional ``name`` arg set the symbol name inside the llvm IR for debugging. If ``zfill`` is set, also filling zeros to the memory. """ with builder.goto_entry_block(): ptr = builder.alloca(ty, size=size, name=name) if zfill: builder.store(Constant.null(ty), ptr) return ptr def alloca_once_value(builder, value, name=''): """ Like alloca_once(), but passing a *value* instead of a type. The type is inferred and the allocated slot is also initialized with the given value. """ storage = alloca_once(builder, value.type) builder.store(value, storage) return storage def insert_pure_function(module, fnty, name): """ Insert a pure function (in the functional programming sense) in the given module. """ fn = module.get_or_insert_function(fnty, name=name) fn.attributes.add("readonly") fn.attributes.add("nounwind") return fn def terminate(builder, bbend): bb = builder.basic_block if bb.terminator is None: builder.branch(bbend) def get_null_value(ltype): return Constant.null(ltype) def is_null(builder, val): null = get_null_value(val.type) return builder.icmp(lc.ICMP_EQ, null, val) def is_not_null(builder, val): null = get_null_value(val.type) return builder.icmp(lc.ICMP_NE, null, val) def if_unlikely(builder, pred): return builder.if_then(pred, likely=False) def if_likely(builder, pred): return builder.if_then(pred, likely=True) def ifnot(builder, pred): return builder.if_then(builder.not_(pred)) class IfBranchObj(object): def __init__(self, builder, bbenter, bbend): self.builder = builder self.bbenter = bbenter self.bbend = bbend def __enter__(self): self.builder.position_at_end(self.bbenter) def __exit__(self, exc_type, exc_val, exc_tb): terminate(self.builder, self.bbend) Loop = collections.namedtuple('Loop', ('index', 'do_break')) @contextmanager def for_range(builder, count, intp=None): """ Generate LLVM IR for a for-loop in [0, count). Yields a Loop namedtuple with the following members: - `index` is the loop index's value - `do_break` is a no-argument callable to break out of the loop """ if intp is None: intp = count.type start = Constant.int(intp, 0) stop = count bbcond = builder.append_basic_block("for.cond") bbbody = builder.append_basic_block("for.body") bbend = builder.append_basic_block("for.end") def do_break(): builder.branch(bbend) bbstart = builder.basic_block builder.branch(bbcond) ONE = Constant.int(intp, 1) with builder.goto_block(bbcond): index = builder.phi(intp, name="loop.index") pred = builder.icmp(lc.ICMP_SLT, index, stop) builder.cbranch(pred, bbbody, bbend) with builder.goto_block(bbbody): yield Loop(index, do_break) # Update bbbody as a new basic block may have been activated bbbody = builder.basic_block incr = builder.add(index, ONE) terminate(builder, bbcond) index.add_incoming(start, bbstart) index.add_incoming(incr, bbbody) builder.position_at_end(bbend) @contextmanager def for_range_slice(builder, start, stop, step, intp=None, inc=True): """ Generate LLVM IR for a for-loop based on a slice. Yields a (index, count) tuple where `index` is the slice index's value inside the loop, and `count` the iteration count. Parameters ------------- builder : object Builder object start : int The beginning value of the slice stop : int The end value of the slice step : int The step value of the slice intp : The data type inc : boolean, optional Signals whether the step is positive (True) or negative (False). Returns ----------- None """ if intp is None: intp = start.type bbcond = builder.append_basic_block("for.cond") bbbody = builder.append_basic_block("for.body") bbend = builder.append_basic_block("for.end") bbstart = builder.basic_block builder.branch(bbcond) with builder.goto_block(bbcond): index = builder.phi(intp, name="loop.index") count = builder.phi(intp, name="loop.count") if (inc): pred = builder.icmp(lc.ICMP_SLT, index, stop) else: pred = builder.icmp(lc.ICMP_SGT, index, stop) builder.cbranch(pred, bbbody, bbend) with builder.goto_block(bbbody): yield index, count bbbody = builder.basic_block incr = builder.add(index, step) next_count = builder.add(count, ir.Constant(intp, 1)) terminate(builder, bbcond) index.add_incoming(start, bbstart) index.add_incoming(incr, bbbody) count.add_incoming(ir.Constant(intp, 0), bbstart) count.add_incoming(next_count, bbbody) builder.position_at_end(bbend) @contextmanager def for_range_slice_generic(builder, start, stop, step): """ A helper wrapper for for_range_slice(). This is a context manager which yields two for_range_slice()-alike context managers, the first for the positive step case, the second for the negative step case. Use: with for_range_slice_generic(...) as (pos_range, neg_range): with pos_range as (idx, count): ... with neg_range as (idx, count): ... """ intp = start.type is_pos_step = builder.icmp_signed('>=', step, ir.Constant(intp, 0)) pos_for_range = for_range_slice(builder, start, stop, step, intp, inc=True) neg_for_range = for_range_slice(builder, start, stop, step, intp, inc=False) @contextmanager def cm_cond(cond, inner_cm): with cond: with inner_cm as value: yield value with builder.if_else(is_pos_step, likely=True) as (then, otherwise): yield cm_cond(then, pos_for_range), cm_cond(otherwise, neg_for_range) @contextmanager def loop_nest(builder, shape, intp): """ Generate a loop nest walking a N-dimensional array. Yields a tuple of N indices for use in the inner loop body. """ if not shape: # 0-d array yield () else: with _loop_nest(builder, shape, intp) as indices: assert len(indices) == len(shape) yield indices @contextmanager def _loop_nest(builder, shape, intp): with for_range(builder, shape[0], intp) as loop: if len(shape) > 1: with _loop_nest(builder, shape[1:], intp) as indices: yield (loop.index,) + indices else: yield (loop.index,) def pack_array(builder, values, ty=None): """ Pack an array of values. *ty* should be given if the array may be empty, in which case the type can't be inferred from the values. """ n = len(values) if ty is None: ty = values[0].type ary = Constant.undef(Type.array(ty, n)) for i, v in enumerate(values): ary = builder.insert_value(ary, v, i) return ary def unpack_tuple(builder, tup, count=None): """ Unpack an array or structure of values, return a Python tuple. """ if count is None: # Assuming *tup* is an aggregate count = len(tup.type.elements) vals = [builder.extract_value(tup, i) for i in range(count)] return vals def get_item_pointer(builder, aryty, ary, inds, wraparound=False): shapes = unpack_tuple(builder, ary.shape, count=aryty.ndim) strides = unpack_tuple(builder, ary.strides, count=aryty.ndim) return get_item_pointer2(builder, data=ary.data, shape=shapes, strides=strides, layout=aryty.layout, inds=inds, wraparound=wraparound) def get_item_pointer2(builder, data, shape, strides, layout, inds, wraparound=False): if wraparound: # Wraparound indices = [] for ind, dimlen in zip(inds, shape): ZERO = Constant.null(ind.type) negative = builder.icmp(lc.ICMP_SLT, ind, ZERO) wrapped = builder.add(dimlen, ind) selected = builder.select(negative, wrapped, ind) indices.append(selected) else: indices = inds if not indices: # Indexing with empty tuple return builder.gep(data, [get_null_value(Type.int(32))]) intp = indices[0].type # Indexing code if layout in 'CF': steps = [] # Compute steps for each dimension if layout == 'C': # C contiguous for i in range(len(shape)): last = Constant.int(intp, 1) for j in shape[i + 1:]: last = builder.mul(last, j) steps.append(last) elif layout == 'F': # F contiguous for i in range(len(shape)): last = Constant.int(intp, 1) for j in shape[:i]: last = builder.mul(last, j) steps.append(last) else: raise Exception("unreachable") # Compute index loc = Constant.int(intp, 0) for i, s in zip(indices, steps): tmp = builder.mul(i, s) loc = builder.add(loc, tmp) ptr = builder.gep(data, [loc]) return ptr else: # Any layout dimoffs = [builder.mul(s, i) for s, i in zip(strides, indices)] offset = functools.reduce(builder.add, dimoffs) return pointer_add(builder, data, offset) def is_scalar_zero(builder, value): """ Return a predicate representing whether *value* is equal to zero. """ assert not is_pointer(value.type) assert not is_struct(value.type) nullval = Constant.null(value.type) if value.type in (Type.float(), Type.double()): isnull = builder.fcmp(lc.FCMP_OEQ, nullval, value) else: isnull = builder.icmp(lc.ICMP_EQ, nullval, value) return isnull def is_not_scalar_zero(builder, value): """ Return a predicate representin whether a *value* is not equal to zero. not exactly "not is_scalar_zero" because of nans """ assert not is_pointer(value.type) assert not is_struct(value.type) nullval = Constant.null(value.type) if value.type in (Type.float(), Type.double()): isnull = builder.fcmp(lc.FCMP_UNE, nullval, value) else: isnull = builder.icmp(lc.ICMP_NE, nullval, value) return isnull def is_scalar_zero_or_nan(builder, value): """ Return a predicate representing whether *value* is equal to either zero or NaN. """ assert not is_pointer(value.type) assert not is_struct(value.type) nullval = Constant.null(value.type) if value.type in (Type.float(), Type.double()): isnull = builder.fcmp(lc.FCMP_UEQ, nullval, value) else: isnull = builder.icmp(lc.ICMP_EQ, nullval, value) return isnull is_true = is_not_scalar_zero is_false = is_scalar_zero def is_scalar_neg(builder, value): """is _value_ negative?. Assumes _value_ is signed""" nullval = Constant.null(value.type) if value.type in (Type.float(), Type.double()): isneg = builder.fcmp(lc.FCMP_OLT, value, nullval) else: isneg = builder.icmp(lc.ICMP_SLT, value, nullval) return isneg def guard_null(context, builder, value, exc_tuple): """ Guard against *value* being null or zero. *exc_tuple* should be a (exception type, arguments...) tuple. """ with builder.if_then(is_scalar_zero(builder, value), likely=False): exc = exc_tuple[0] exc_args = exc_tuple[1:] or None context.call_conv.return_user_exc(builder, exc, exc_args) def guard_invalid_slice(context, builder, slicestruct): """ Guard against *slicestruct* having a zero step (and raise ValueError). """ guard_null(context, builder, slicestruct.step, (ValueError, "slice step cannot be zero")) def guard_memory_error(context, builder, pointer, msg=None): """ Guard against *pointer* being NULL (and raise a MemoryError). """ assert isinstance(pointer.type, ir.PointerType), pointer.type exc_args = (msg,) if msg else () with builder.if_then(is_null(builder, pointer), likely=False): context.call_conv.return_user_exc(builder, MemoryError, exc_args) @contextmanager def if_zero(builder, value, likely=False): """ Execute the given block if the scalar value is zero. """ with builder.if_then(is_scalar_zero(builder, value), likely=likely): yield guard_zero = guard_null def is_struct(ltyp): """ Whether the LLVM type *typ* is a pointer type. """ return ltyp.kind == lc.TYPE_STRUCT def is_pointer(ltyp): """ Whether the LLVM type *typ* is a struct type. """ return ltyp.kind == lc.TYPE_POINTER def is_struct_ptr(ltyp): """ Whether the LLVM type *typ* is a pointer-to-struct type. """ return is_pointer(ltyp) and is_struct(ltyp.pointee) def get_record_member(builder, record, offset, typ): pval = gep_inbounds(builder, record, 0, offset) assert not is_pointer(pval.type.pointee) return builder.bitcast(pval, Type.pointer(typ)) def is_neg_int(builder, val): return builder.icmp(lc.ICMP_SLT, val, get_null_value(val.type)) def gep_inbounds(builder, ptr, *inds, **kws): """ Same as *gep*, but add the `inbounds` keyword. """ return gep(builder, ptr, *inds, inbounds=True, **kws) def gep(builder, ptr, *inds, **kws): """ Emit a getelementptr instruction for the given pointer and indices. The indices can be LLVM values or Python int constants. """ name = kws.pop('name', '') inbounds = kws.pop('inbounds', False) assert not kws idx = [] for i in inds: if isinstance(i, int): # NOTE: llvm only accepts int32 inside structs, not int64 ind = Constant.int(Type.int(32), i) else: ind = i idx.append(ind) return builder.gep(ptr, idx, name=name, inbounds=inbounds) def pointer_add(builder, ptr, offset, return_type=None): """ Add an integral *offset* to pointer *ptr*, and return a pointer of *return_type* (or, if omitted, the same type as *ptr*). Note the computation is done in bytes, and ignores the width of the pointed item type. """ intptr = builder.ptrtoint(ptr, intp_t) if isinstance(offset, int): offset = Constant.int(intp_t, offset) intptr = builder.add(intptr, offset) return builder.inttoptr(intptr, return_type or ptr.type) def memset(builder, ptr, size, value): """ Fill *size* bytes starting from *ptr* with *value*. """ sizety = size.type memset = "llvm.memset.p0i8.i%d" % (sizety.width) i32 = lc.Type.int(32) i8 = lc.Type.int(8) i8_star = i8.as_pointer() i1 = lc.Type.int(1) fn = builder.module.declare_intrinsic('llvm.memset', (i8_star, size.type)) ptr = builder.bitcast(ptr, i8_star) if isinstance(value, int): value = Constant.int(i8, value) builder.call(fn, [ptr, value, size, Constant.int(i32, 0), Constant.int(i1, 0)]) def global_constant(builder_or_module, name, value, linkage=lc.LINKAGE_INTERNAL): """ Get or create a (LLVM module-)global constant with *name* or *value*. """ if isinstance(builder_or_module, lc.Module): module = builder_or_module else: module = builder_or_module.module data = module.add_global_variable(value.type, name=name) data.linkage = linkage data.global_constant = True data.initializer = value return data def divmod_by_constant(builder, val, divisor): """ Compute the (quotient, remainder) of *val* divided by the constant positive *divisor*. The semantics reflects those of Python integer floor division, rather than C's / LLVM's signed division and modulo. The difference lies with a negative *val*. """ assert divisor > 0 divisor = Constant.int(val.type, divisor) one = Constant.int(val.type, 1) quot = alloca_once(builder, val.type) with builder.if_else(is_neg_int(builder, val)) as (if_neg, if_pos): with if_pos: # quot = val / divisor quot_val = builder.sdiv(val, divisor) builder.store(quot_val, quot) with if_neg: # quot = -1 + (val + 1) / divisor val_plus_one = builder.add(val, one) quot_val = builder.sdiv(val_plus_one, divisor) builder.store(builder.sub(quot_val, one), quot) # rem = val - quot * divisor # (should be slightly faster than a separate modulo operation) quot_val = builder.load(quot) rem_val = builder.sub(val, builder.mul(quot_val, divisor)) return quot_val, rem_val def cbranch_or_continue(builder, cond, bbtrue): """ Branch conditionally or continue. Note: a new block is created and builder is moved to the end of the new block. """ bbcont = builder.append_basic_block('.continue') builder.cbranch(cond, bbtrue, bbcont) builder.position_at_end(bbcont) return bbcont def add_postfix(name, postfix): """Add postfix to string. If the postfix is already there, add a counter. """ regex = "(.*{0})([0-9]*)$".format(postfix) m = re.match(regex, name) if m: head, ct = m.group(1), m.group(2) if len(ct): ct = int(ct) + 1 else: ct = 1 return "{head}{ct}".format(head=head, ct=ct) return name + postfix def memcpy(builder, dst, src, count): """ Emit a memcpy to the builder. Copies each element of dst to src. Unlike the C equivalent, each element can be any LLVM type. Assumes ------- * dst.type == src.type * count is positive """ assert dst.type == src.type with for_range(builder, count, count.type) as loop: out_ptr = builder.gep(dst, [loop.index]) in_ptr = builder.gep(src, [loop.index]) builder.store(builder.load(in_ptr), out_ptr) def memmove(builder, dst, src, count, itemsize, align=1): """ Emit a memmove() call for `count` items of size `itemsize` from `src` to `dest`. """ ptr_t = ir.IntType(8).as_pointer() size_t = count.type memmove = builder.module.declare_intrinsic('llvm.memmove', [ptr_t, ptr_t, size_t]) align = ir.Constant(ir.IntType(32), align) is_volatile = false_bit builder.call(memmove, [builder.bitcast(dst, ptr_t), builder.bitcast(src, ptr_t), builder.mul(count, ir.Constant(size_t, itemsize)), align, is_volatile]) def muladd_with_overflow(builder, a, b, c): """ Compute (a * b + c) and return a (result, overflow bit) pair. The operands must be signed integers. """ p = builder.smul_with_overflow(a, b) prod = builder.extract_value(p, 0) prod_ovf = builder.extract_value(p, 1) s = builder.sadd_with_overflow(prod, c) res = builder.extract_value(s, 0) ovf = builder.or_(prod_ovf, builder.extract_value(s, 1)) return res, ovf def printf(builder, format, *args): """ Calls printf(). Argument `format` is expected to be a Python string. Values to be printed are listed in `args`. Note: There is no checking to ensure there is correct number of values in `args` and there type matches the declaration in the format string. """ assert isinstance(format, str) mod = builder.module # Make global constant for format string cstring = ir.IntType(8).as_pointer() fmt_bytes = make_bytearray((format + '\00').encode('ascii')) global_fmt = global_constant(mod, "printf_format", fmt_bytes) fnty = ir.FunctionType(Type.int(), [cstring], var_arg=True) # Insert printf() fn = mod.get_global('printf') if fn is None: fn = ir.Function(mod, fnty, name="printf") # Call ptr_fmt = builder.bitcast(global_fmt, cstring) return builder.call(fn, [ptr_fmt] + list(args))
"""Resource class containing all logic for creating, checking, and updating resources.""" import datetime import logging from os import remove from os.path import join from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union from hdx.utilities.downloader import Download from hdx.utilities.loader import load_json, load_yaml from hdx.utilities.path import script_dir_plus_file from hdx.utilities.uuid import is_valid_uuid import hdx.data.dataset import hdx.data.filestore_helper as filestore_helper from hdx.api.configuration import Configuration from hdx.data.date_helper import DateHelper from hdx.data.hdxobject import HDXError, HDXObject from hdx.data.resource_view import ResourceView logger = logging.getLogger(__name__) class Resource(HDXObject): """Resource class containing all logic for creating, checking, and updating resources. Args: initial_data (Optional[Dict]): Initial resource metadata dictionary. Defaults to None. configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration. """ _formats_dict = None def __init__( self, initial_data: Optional[Dict] = None, configuration: Optional[Configuration] = None, ) -> None: if not initial_data: initial_data = dict() super().__init__(initial_data, configuration=configuration) self.file_to_upload = None @staticmethod def actions() -> Dict[str, str]: """Dictionary of actions that can be performed on object Returns: Dict[str, str]: Dictionary of actions that can be performed on object """ return { "show": "resource_show", "update": "resource_update", "create": "resource_create", "patch": "resource_patch", "delete": "resource_delete", "search": "resource_search", "datastore_delete": "datastore_delete", "datastore_create": "datastore_create", "datastore_insert": "datastore_insert", "datastore_upsert": "datastore_upsert", "datastore_search": "datastore_search", } def update_from_yaml( self, path: str = join("config", "hdx_resource_static.yml") ) -> None: """Update resource metadata with static metadata from YAML file Args: path (Optional[str]): Path to YAML dataset metadata. Defaults to config/hdx_resource_static.yml. Returns: None """ super().update_from_yaml(path) def update_from_json( self, path: str = join("config", "hdx_resource_static.json") ) -> None: """Update resource metadata with static metadata from JSON file Args: path (Optional[str]): Path to JSON dataset metadata. Defaults to config/hdx_resource_static.json. Returns: None """ super().update_from_json(path) @classmethod def read_from_hdx( cls, identifier: str, configuration: Optional[Configuration] = None ) -> Optional["Resource"]: """Reads the resource given by identifier from HDX and returns Resource object Args: identifier (str): Identifier of resource configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration. Returns: Optional[Resource]: Resource object if successful read, None if not """ if is_valid_uuid(identifier) is False: raise HDXError(f"{identifier} is not a valid resource id!") return cls._read_from_hdx_class("resource", identifier, configuration) def get_date_of_resource( self, date_format: Optional[str] = None, today: datetime.date = datetime.date.today(), ) -> Dict: """Get resource date as datetimes and strings in specified format. If no format is supplied, the ISO 8601 format is used. Returns a dictionary containing keys startdate (start date as datetime), enddate (end date as datetime), startdate_str (start date as string), enddate_str (end date as string) and ongoing (whether the end date is a rolls forward every day). Args: date_format (Optional[str]): Date format. None is taken to be ISO 8601. Defaults to None. today (datetime.date): Date to use for today. Defaults to date.today. Returns: Dict: Dictionary of date information """ return DateHelper.get_date_info( self.data.get("daterange_for_data"), date_format, today ) def set_date_of_resource( self, startdate: Union[datetime.datetime, str], enddate: Union[datetime.datetime, str], ) -> None: """Set resource date from either datetime.datetime objects or strings. Args: startdate (Union[datetime.datetime, str]): Dataset start date enddate (Union[datetime.datetime, str]): Dataset end date Returns: None """ self.data["daterange_for_data"] = DateHelper.get_hdx_date( startdate, enddate ) @classmethod def read_formats_mappings( cls, configuration: Optional[Configuration] = None, url: Optional[str] = None, ) -> Dict: """ Read HDX formats list Args: configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration. url (Optional[str]): Url of tags cleanup spreadsheet. Defaults to None (internal configuration parameter). Returns: Dict: Returns formats dictionary """ if not cls._formats_dict: if configuration is None: configuration = Configuration.read() with Download( full_agent=configuration.get_user_agent() ) as downloader: if url is None: url = configuration["formats_mapping_url"] downloader.download(url) cls._formats_dict = dict() for format_data in downloader.get_json(): format = format_data[0].lower() if format == "_comment": continue cls._formats_dict[format] = format for file_type in format_data[3]: cls._formats_dict[file_type.lower()] = format return cls._formats_dict @classmethod def set_formatsdict(cls, formats_dict: Dict) -> None: """ Set formats dictionary Args: formats_dict (Dict): Formats dictionary Returns: None """ cls._formats_dict = formats_dict @classmethod def get_mapped_format( cls, file_type: str, configuration: Optional[Configuration] = None ) -> Optional[str]: """Given a format, return a format to which it maps Args: file_type (str): File type to map configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration. Returns: Optional[str]: Mapped format or None if no mapping found """ if configuration is None: configuration = Configuration.read() if not file_type: return None file_type = file_type.lower() mappings = cls.read_formats_mappings(configuration=configuration) format = mappings.get(file_type) if format is None: if file_type[0] == ".": file_type = file_type[1:] else: file_type = f".{file_type}" format = mappings.get(file_type) return format def get_file_type(self) -> Optional[str]: """Get the resource's file type Returns: Optional[str]: Resource's file type or None if it has not been set """ format = self.data.get("format") if format: format = format.lower() return format def set_file_type(self, file_type: str) -> str: """Set the resource's file type Args: file_type (str): File type to set on resource log_none (bool): Whether to log an informational message about the file type being None. Defaults to True. Returns: str: Format that was set """ format = self.get_mapped_format( file_type, configuration=self.configuration ) if not format: raise HDXError( f"Supplied file type {file_type} is invalid and could not be mapped to a known type!" ) self.data["format"] = format return format def clean_file_type(self) -> str: """Clean the resource's file type, setting it to None if it is invalid and cannot be mapped Returns: str: Format that was set """ return self.set_file_type(self.data.get("format")) def get_file_to_upload(self) -> Optional[str]: """Get the file uploaded Returns: Optional[str]: The file that will be or has been uploaded or None if there isn't one """ return self.file_to_upload def set_file_to_upload( self, file_to_upload: str, guess_format_from_suffix: bool = False ) -> str: """Delete any existing url and set the file uploaded to the local path provided Args: file_to_upload (str): Local path to file to upload guess_format_from_suffix (bool): Whether to try to set format based on file suffix. Defaults to False. Returns: Optional[str]: The format that was guessed or None if no format was set """ if "url" in self.data: del self.data["url"] self.file_to_upload = file_to_upload format = None if guess_format_from_suffix: format = self.set_file_type(Path(file_to_upload).suffix) return format def check_url_filetoupload(self) -> None: """Check if url or file to upload provided for resource and add resource_type and url_type if not supplied. Correct the file type. Returns: None """ if self.file_to_upload is None: if "url" in self.data: if "resource_type" not in self.data: self.data["resource_type"] = "api" if "url_type" not in self.data: self.data["url_type"] = "api" else: raise HDXError( "Either a url or a file to upload must be supplied!" ) else: if "url" in self.data: if ( self.data["url"] != filestore_helper.FilestoreHelper.temporary_url ): raise HDXError( "Either a url or a file to upload must be supplied not both!" ) if "resource_type" not in self.data: self.data["resource_type"] = "file.upload" if "url_type" not in self.data: self.data["url_type"] = "upload" if "tracking_summary" in self.data: del self.data["tracking_summary"] self.clean_file_type() def check_required_fields(self, ignore_fields: List[str] = list()) -> None: """Check that metadata for resource is complete. The parameter ignore_fields should be set if required to any fields that should be ignored for the particular operation. Args: ignore_fields (List[str]): Fields to ignore. Default is []. Returns: None """ self.check_url_filetoupload() self._check_required_fields("resource", ignore_fields) def _get_files(self) -> Dict: """Return the files parameter for CKANAPI Returns: Dict: files parameter for CKANAPI """ if self.file_to_upload is None: return dict() return {"upload": self.file_to_upload} def update_in_hdx(self, **kwargs: Any) -> None: """Check if resource exists in HDX and if so, update it Args: **kwargs: See below operation (string): Operation to perform eg. patch. Defaults to update. Returns: None """ self._check_load_existing_object("resource", "id") if self.file_to_upload and "url" in self.data: del self.data["url"] self._merge_hdx_update( "resource", "id", self._get_files(), True, **kwargs ) def create_in_hdx(self, **kwargs: Any) -> None: """Check if resource exists in HDX and if so, update it, otherwise create it Returns: None """ if "ignore_check" not in kwargs: # allow ignoring of field checks self.check_required_fields() id = self.data.get("id") files = self._get_files() if id and self._load_from_hdx("resource", id): logger.warning(f"{'resource'} exists. Updating {id}") if self.file_to_upload and "url" in self.data: del self.data["url"] self._merge_hdx_update("resource", "id", files, True, **kwargs) else: self._save_to_hdx("create", "name", files, True) def delete_from_hdx(self) -> None: """Deletes a resource from HDX Returns: None """ self._delete_from_hdx("resource", "id") def get_dataset(self) -> "Dataset": # noqa: F821 """Return dataset containing this resource Returns: Dataset: Dataset containing this resource """ package_id = self.data.get("package_id") if package_id is None: raise HDXError("Resource has no package id!") return hdx.data.dataset.Dataset.read_from_hdx(package_id) @staticmethod def search_in_hdx( query: str, configuration: Optional[Configuration] = None, **kwargs: Any, ) -> List["Resource"]: """Searches for resources in HDX. NOTE: Does not search dataset metadata! Args: query (str): Query configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration. **kwargs: See below order_by (str): A field on the Resource model that orders the results offset (int): Apply an offset to the query limit (int): Apply a limit to the query Returns: List[Resource]: List of resources resulting from query """ resources = [] resource = Resource(configuration=configuration) success, result = resource._read_from_hdx( "resource", query, "query", Resource.actions()["search"] ) if result: count = result.get("count", None) if count: for resourcedict in result["results"]: resource = Resource( resourcedict, configuration=configuration ) resources.append(resource) else: logger.debug(result) return resources def download(self, folder: Optional[str] = None) -> Tuple[str, str]: """Download resource store to provided folder or temporary folder if no folder supplied Args: folder (Optional[str]): Folder to download resource to. Defaults to None. Returns: Tuple[str, str]: (URL downloaded, Path to downloaded file) """ # Download the resource url = self.data.get("url", None) if not url: raise HDXError("No URL to download!") logger.debug(f"Downloading {url}") filename = self.data["name"] format = f".{self.data['format']}" if format not in filename: filename = f"{filename}{format}" apikey = self.configuration.get_api_key() if apikey: headers = {"Authorization": self.configuration.get_api_key()} else: headers = None with Download( full_agent=self.configuration.get_user_agent(), headers=headers ) as downloader: path = downloader.download_file(url, folder, filename) return url, path @staticmethod def get_all_resource_ids_in_datastore( configuration: Optional[Configuration] = None, ) -> List[str]: """Get list of resources that have a datastore returning their ids. Args: configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration. Returns: List[str]: List of resource ids that are in the datastore """ resource = Resource(configuration=configuration) success, result = resource._read_from_hdx( "datastore", "_table_metadata", "resource_id", Resource.actions()["datastore_search"], limit=10000, ) resource_ids = list() if not success: logger.debug(result) else: for record in result["records"]: resource_ids.append(record["name"]) return resource_ids def has_datastore(self) -> bool: """Check if the resource has a datastore. Returns: bool: Whether the resource has a datastore or not """ success, result = self._read_from_hdx( "datastore", self.data["id"], "resource_id", self.actions()["datastore_search"], ) if not success: logger.debug(result) else: if result: return True return False def delete_datastore(self) -> None: """Delete a resource from the HDX datastore Returns: None """ success, result = self._read_from_hdx( "datastore", self.data["id"], "resource_id", self.actions()["datastore_delete"], force=True, ) if not success: logger.debug(result) def create_datastore( self, schema: Optional[List[Dict]] = None, primary_key: Optional[str] = None, delete_first: int = 0, path: Optional[str] = None, ) -> None: """For tabular data, create a resource in the HDX datastore which enables data preview in HDX. If no schema is provided all fields are assumed to be text. If path is not supplied, the file is first downloaded from HDX. Args: schema (List[Dict]): List of fields and types of form {'id': 'FIELD', 'type': 'TYPE'}. Defaults to None. primary_key (Optional[str]): Primary key of schema. Defaults to None. delete_first (int): Delete datastore before creation. 0 = No, 1 = Yes, 2 = If no primary key. Defaults to 0. path (Optional[str]): Local path to file that was uploaded. Defaults to None. Returns: None """ if delete_first == 0: pass elif delete_first == 1: self.delete_datastore() elif delete_first == 2: if primary_key is None: self.delete_datastore() else: raise HDXError( "delete_first must be 0, 1 or 2! (0 = No, 1 = Yes, 2 = Delete if no primary key)" ) if path is None: # Download the resource url, path = self.download() delete_after_download = True else: url = path delete_after_download = False def convert_to_text(extended_rows): for number, headers, row in extended_rows: for i, val in enumerate(row): row[i] = str(val) yield (number, headers, row) with Download( full_agent=self.configuration.get_user_agent() ) as downloader: try: stream = downloader.get_tabular_stream( path, headers=1, post_parse=[convert_to_text], bytes_sample_size=1000000, ) nonefieldname = False if schema is None: schema = list() for fieldname in stream.headers: if fieldname is not None: schema.append({"id": fieldname, "type": "text"}) else: nonefieldname = True data = { "resource_id": self.data["id"], "force": True, "fields": schema, "primary_key": primary_key, } self._write_to_hdx("datastore_create", data, "resource_id") if primary_key is None: method = "insert" else: method = "upsert" logger.debug(f"Uploading data from {url} to datastore") offset = 0 chunksize = 100 rowset = stream.read(keyed=True, limit=chunksize) while len(rowset) != 0: if nonefieldname: for row in rowset: del row[None] data = { "resource_id": self.data["id"], "force": True, "method": method, "records": rowset, } self._write_to_hdx("datastore_upsert", data, "resource_id") rowset = stream.read(keyed=True, limit=chunksize) logger.debug(f"Uploading: {offset}") offset += chunksize except Exception as e: raise HDXError(f"Upload to datastore of {url} failed!") from e finally: if delete_after_download: remove(path) def create_datastore_from_dict_schema( self, data: dict, delete_first: int = 0, path: Optional[str] = None ) -> None: """For tabular data, create a resource in the HDX datastore which enables data preview in HDX from a dictionary containing a list of fields and types of form {'id': 'FIELD', 'type': 'TYPE'} and optionally a primary key. If path is not supplied, the file is first downloaded from HDX. Args: data (dict): Dictionary containing list of fields and types of form {'id': 'FIELD', 'type': 'TYPE'} delete_first (int): Delete datastore before creation. 0 = No, 1 = Yes, 2 = If no primary key. Defaults to 0. path (Optional[str]): Local path to file that was uploaded. Defaults to None. Returns: None """ schema = data["schema"] primary_key = data.get("primary_key") self.create_datastore(schema, primary_key, delete_first, path=path) def create_datastore_from_yaml_schema( self, yaml_path: str, delete_first: Optional[int] = 0, path: Optional[str] = None, ) -> None: """For tabular data, create a resource in the HDX datastore which enables data preview in HDX from a YAML file containing a list of fields and types of form {'id': 'FIELD', 'type': 'TYPE'} and optionally a primary key. If path is not supplied, the file is first downloaded from HDX. Args: yaml_path (str): Path to YAML file containing list of fields and types of form {'id': 'FIELD', 'type': 'TYPE'} delete_first (int): Delete datastore before creation. 0 = No, 1 = Yes, 2 = If no primary key. Defaults to 0. path (Optional[str]): Local path to file that was uploaded. Defaults to None. Returns: None """ data = load_yaml(yaml_path) self.create_datastore_from_dict_schema(data, delete_first, path=path) def create_datastore_from_json_schema( self, json_path: str, delete_first: int = 0, path: Optional[str] = None ) -> None: """For tabular data, create a resource in the HDX datastore which enables data preview in HDX from a JSON file containing a list of fields and types of form {'id': 'FIELD', 'type': 'TYPE'} and optionally a primary key. If path is not supplied, the file is first downloaded from HDX. Args: json_path (str): Path to JSON file containing list of fields and types of form {'id': 'FIELD', 'type': 'TYPE'} delete_first (int): Delete datastore before creation. 0 = No, 1 = Yes, 2 = If no primary key. Defaults to 0. path (Optional[str]): Local path to file that was uploaded. Defaults to None. Returns: None """ data = load_json(json_path) self.create_datastore_from_dict_schema(data, delete_first, path=path) def create_datastore_for_topline( self, delete_first: int = 0, path: Optional[str] = None ) -> None: """For tabular data, create a resource in the HDX datastore which enables data preview in HDX using the built in YAML definition for a topline. If path is not supplied, the file is first downloaded from HDX. Args: delete_first (int): Delete datastore before creation. 0 = No, 1 = Yes, 2 = If no primary key. Defaults to 0. path (Optional[str]): Local path to file that was uploaded. Defaults to None. Returns: None """ data = load_yaml( script_dir_plus_file("hdx_datasource_topline.yml", Resource) ) self.create_datastore_from_dict_schema(data, delete_first, path=path) def update_datastore( self, schema: Optional[List[Dict]] = None, primary_key: Optional[str] = None, path: Optional[str] = None, ) -> None: """For tabular data, update a resource in the HDX datastore which enables data preview in HDX. If no schema is provided all fields are assumed to be text. If path is not supplied, the file is first downloaded from HDX. Args: schema (List[Dict]): List of fields and types of form {'id': 'FIELD', 'type': 'TYPE'}. Defaults to None. primary_key (Optional[str]): Primary key of schema. Defaults to None. path (Optional[str]): Local path to file that was uploaded. Defaults to None. Returns: None """ self.create_datastore(schema, primary_key, 2, path=path) def update_datastore_from_dict_schema( self, data: dict, path: Optional[str] = None ) -> None: """For tabular data, update a resource in the HDX datastore which enables data preview in HDX from a dictionary containing a list of fields and types of form {'id': 'FIELD', 'type': 'TYPE'} and optionally a primary key. If path is not supplied, the file is first downloaded from HDX. Args: data (dict): Dictionary containing list of fields and types of form {'id': 'FIELD', 'type': 'TYPE'} path (Optional[str]): Local path to file that was uploaded. Defaults to None. Returns: None """ self.create_datastore_from_dict_schema(data, 2, path=path) def update_datastore_from_yaml_schema( self, yaml_path: str, path: Optional[str] = None ) -> None: """For tabular data, update a resource in the HDX datastore which enables data preview in HDX from a YAML file containing a list of fields and types of form {'id': 'FIELD', 'type': 'TYPE'} and optionally a primary key. If path is not supplied, the file is first downloaded from HDX. Args: yaml_path (str): Path to YAML file containing list of fields and types of form {'id': 'FIELD', 'type': 'TYPE'} path (Optional[str]): Local path to file that was uploaded. Defaults to None. Returns: None """ self.create_datastore_from_yaml_schema(yaml_path, 2, path=path) def update_datastore_from_json_schema( self, json_path: str, path: Optional[str] = None ) -> None: """For tabular data, update a resource in the HDX datastore which enables data preview in HDX from a JSON file containing a list of fields and types of form {'id': 'FIELD', 'type': 'TYPE'} and optionally a primary key. If path is not supplied, the file is first downloaded from HDX. Args: json_path (str): Path to JSON file containing list of fields and types of form {'id': 'FIELD', 'type': 'TYPE'} path (Optional[str]): Local path to file that was uploaded. Defaults to None. Returns: None """ self.create_datastore_from_json_schema(json_path, 2, path=path) def update_datastore_for_topline(self, path: Optional[str] = None) -> None: """For tabular data, update a resource in the HDX datastore which enables data preview in HDX using the built in YAML definition for a topline. If path is not supplied, the file is first downloaded from HDX. Args: path (Optional[str]): Local path to file that was uploaded. Defaults to None. Returns: None """ self.create_datastore_for_topline(2, path=path) def get_resource_views(self) -> List[ResourceView]: """Get any resource views in the resource Returns: List[ResourceView]: List of resource views """ return ResourceView.get_all_for_resource(self.data["id"]) def _get_resource_view( self, resource_view: Union[ResourceView, Dict] ) -> ResourceView: """Get resource view id Args: resource_view (Union[ResourceView,Dict]): ResourceView metadata from a ResourceView object or dictionary Returns: ResourceView: ResourceView object """ if isinstance(resource_view, dict): resource_view = ResourceView( resource_view, configuration=self.configuration ) if isinstance(resource_view, ResourceView): return resource_view raise HDXError( f"Type {type(resource_view).__name__} is not a valid resource view!" ) def add_update_resource_view( self, resource_view: Union[ResourceView, Dict] ) -> None: """Add new resource view in resource with new metadata Args: resource_view (Union[ResourceView,Dict]): Resource view metadata either from a ResourceView object or a dictionary Returns: None """ resource_view = self._get_resource_view(resource_view) resource_view.create_in_hdx() def add_update_resource_views( self, resource_views: List[Union[ResourceView, Dict]] ) -> None: """Add new or update existing resource views in resource with new metadata. Args: resource_views (List[Union[ResourceView,Dict]]): A list of resource views metadata from ResourceView objects or dictionaries Returns: None """ if not isinstance(resource_views, list): raise HDXError("ResourceViews should be a list!") for resource_view in resource_views: self.add_update_resource_view(resource_view) def reorder_resource_views( self, resource_views: List[Union[ResourceView, Dict, str]] ) -> None: """Order resource views in resource. Args: resource_views (List[Union[ResourceView,Dict,str]]): A list of either resource view ids or resource views metadata from ResourceView objects or dictionaries Returns: None """ if not isinstance(resource_views, list): raise HDXError("ResourceViews should be a list!") ids = list() for resource_view in resource_views: if isinstance(resource_view, str): resource_view_id = resource_view else: resource_view_id = resource_view["id"] if is_valid_uuid(resource_view_id) is False: raise HDXError( f"{resource_view} is not a valid resource view id!" ) ids.append(resource_view_id) _, result = self._read_from_hdx( "resource view", self.data["id"], "id", ResourceView.actions()["reorder"], order=ids, ) def delete_resource_view( self, resource_view: Union[ResourceView, Dict, str] ) -> None: """Delete a resource view from the resource and HDX Args: resource_view (Union[ResourceView,Dict,str]): Either a resource view id or resource view metadata either from a ResourceView object or a dictionary Returns: None """ if isinstance(resource_view, str): if is_valid_uuid(resource_view) is False: raise HDXError( f"{resource_view} is not a valid resource view id!" ) resource_view = ResourceView( {"id": resource_view}, configuration=self.configuration ) else: resource_view = self._get_resource_view(resource_view) if "id" not in resource_view: found = False title = resource_view.get("title") for rv in self.get_resource_views(): if resource_view["title"] == rv["title"]: resource_view = rv found = True break if not found: raise HDXError( f"No resource views have title {title} in this resource!" ) resource_view.delete_from_hdx() def enable_dataset_preview(self) -> None: """Enable dataset preview of resource Returns: None """ self.data["dataset_preview_enabled"] = "True" def disable_dataset_preview(self) -> None: """Disable dataset preview of resource Returns: None """ self.data["dataset_preview_enabled"] = "False"
'''estimate distribution parameters by various methods method of moments or matching quantiles, and Maximum Likelihood estimation based on binned data and Maximum Product-of-Spacings Warning: I'm still finding cut-and-paste and refactoring errors, e.g. hardcoded variables from outer scope in functions some results don't seem to make sense for Pareto case, looks better now after correcting some name errors initially loosely based on a paper and blog for quantile matching by John D. Cook formula for gamma quantile (ppf) matching by him (from paper) http://www.codeproject.com/KB/recipes/ParameterPercentile.aspx http://www.johndcook.com/blog/2010/01/31/parameters-from-percentiles/ this is what I actually used (in parts): http://www.bepress.com/mdandersonbiostat/paper55/ quantile based estimator ^^^^^^^^^^^^^^^^^^^^^^^^ only special cases for number or parameters so far Is there a literature for GMM estimation of distribution parameters? check found one: Wu/Perloff 2007 binned estimator ^^^^^^^^^^^^^^^^ * I added this also * use it for chisquare tests with estimation distribution parameters * move this to distribution_extras (next to gof tests powerdiscrepancy and continuous) or add to distribution_patch example: t-distribution * works with quantiles if they contain tail quantiles * results with momentcondquant don't look as good as mle estimate TODOs * rearange and make sure I don't use module globals (as I did initially) DONE make two version exactly identified method of moments with fsolve and GMM (?) version with fmin and maybe the special cases of JD Cook update: maybe exact (MM) version is not so interesting compared to GMM * add semifrozen version of moment and quantile based estimators, e.g. for beta (both loc and scale fixed), or gamma (loc fixed) * add beta example to the semifrozen MLE, fitfr, code -> added method of moment estimator to _fitstart for beta * start a list of how well different estimators, especially current mle work for the different distributions * need general GMM code (with optimal weights ?), looks like a good example for it * get example for binned data estimation, mailing list a while ago * any idea when these are better than mle ? * check language: I use quantile to mean the value of the random variable, not quantile between 0 and 1. * for GMM: move moment conditions to separate function, so that they can be used for further analysis, e.g. covariance matrix of parameter estimates * question: Are GMM properties different for matching quantiles with cdf or ppf? Estimate should be the same, but derivatives of moment conditions differ. * add maximum spacings estimator, Wikipedia, Per Brodtkorb -> basic version Done * add parameter estimation based on empirical characteristic function (Carrasco/Florens), especially for stable distribution * provide a model class based on estimating all distributions, and collect all distribution specific information References ---------- Ximing Wu, Jeffrey M. Perloff, GMM estimation of a maximum entropy distribution with interval data, Journal of Econometrics, Volume 138, Issue 2, 'Information and Entropy Econometrics' - A Volume in Honor of Arnold Zellner, June 2007, Pages 532-546, ISSN 0304-4076, DOI: 10.1016/j.jeconom.2006.05.008. http://www.sciencedirect.com/science/article/B6VC0-4K606TK-4/2/78bc07c6245546374490f777a6bdbbcc http://escholarship.org/uc/item/7jf5w1ht (working paper) Johnson, Kotz, Balakrishnan: Volume 2 Author : josef-pktd License : BSD created : 2010-04-20 changes: added Maximum Product-of-Spacings 2010-05-12 ''' import numpy as np from scipy import stats, optimize, special cache = {} #module global storage for temp results, not used # the next two use distfn from module scope - not anymore def gammamomentcond(distfn, params, mom2, quantile=None): '''estimate distribution parameters based method of moments (mean, variance) for distributions with 1 shape parameter and fixed loc=0. Returns ------- cond : function Notes ----- first test version, quantile argument not used ''' def cond(params): alpha, scale = params mom2s = distfn.stats(alpha, 0.,scale) #quantil return np.array(mom2)-mom2s return cond def gammamomentcond2(distfn, params, mom2, quantile=None): '''estimate distribution parameters based method of moments (mean, variance) for distributions with 1 shape parameter and fixed loc=0. Returns ------- difference : array difference between theoretical and empirical moments Notes ----- first test version, quantile argument not used The only difference to previous function is return type. ''' alpha, scale = params mom2s = distfn.stats(alpha, 0.,scale) return np.array(mom2)-mom2s ######### fsolve doesn't move in small samples, fmin not very accurate def momentcondunbound(distfn, params, mom2, quantile=None): '''moment conditions for estimating distribution parameters using method of moments, uses mean, variance and one quantile for distributions with 1 shape parameter. Returns ------- difference : array difference between theoretical and empirical moments and quantiles ''' shape, loc, scale = params mom2diff = np.array(distfn.stats(shape, loc,scale)) - mom2 if not quantile is None: pq, xq = quantile #ppfdiff = distfn.ppf(pq, alpha) cdfdiff = distfn.cdf(xq, shape, loc, scale) - pq return np.concatenate([mom2diff, cdfdiff[:1]]) return mom2diff ###### loc scale only def momentcondunboundls(distfn, params, mom2, quantile=None, shape=None): '''moment conditions for estimating loc and scale of a distribution with method of moments using either 2 quantiles or 2 moments (not both). Returns ------- difference : array difference between theoretical and empirical moments or quantiles ''' loc, scale = params mom2diff = np.array(distfn.stats(shape, loc, scale)) - mom2 if not quantile is None: pq, xq = quantile #ppfdiff = distfn.ppf(pq, alpha) cdfdiff = distfn.cdf(xq, shape, loc, scale) - pq #return np.concatenate([mom2diff, cdfdiff[:1]]) return cdfdiff return mom2diff ######### try quantile GMM with identity weight matrix #(just a guess that's what it is def momentcondquant(distfn, params, mom2, quantile=None, shape=None): '''moment conditions for estimating distribution parameters by matching quantiles, defines as many moment conditions as quantiles. Returns ------- difference : array difference between theoretical and empirical quantiles Notes ----- This can be used for method of moments or for generalized method of moments. ''' #this check looks redundant/unused know if len(params) == 2: loc, scale = params elif len(params) == 3: shape, loc, scale = params else: #raise NotImplementedError pass #see whether this might work, seems to work for beta with 2 shape args #mom2diff = np.array(distfn.stats(*params)) - mom2 #if not quantile is None: pq, xq = quantile #ppfdiff = distfn.ppf(pq, alpha) cdfdiff = distfn.cdf(xq, *params) - pq #return np.concatenate([mom2diff, cdfdiff[:1]]) return cdfdiff #return mom2diff def fitquantilesgmm(distfn, x, start=None, pquant=None, frozen=None): if pquant is None: pquant = np.array([0.01, 0.05,0.1,0.4,0.6,0.9,0.95,0.99]) if start is None: if hasattr(distfn, '_fitstart'): start = distfn._fitstart(x) else: start = [1]*distfn.numargs + [0.,1.] #TODO: vectorize this: xqs = [stats.scoreatpercentile(x, p) for p in pquant*100] mom2s = None parest = optimize.fmin(lambda params:np.sum( momentcondquant(distfn, params, mom2s,(pquant,xqs), shape=None)**2), start) return parest def fitbinned(distfn, freq, binedges, start, fixed=None): '''estimate parameters of distribution function for binned data using MLE Parameters ---------- distfn : distribution instance needs to have cdf method, as in scipy.stats freq : array, 1d frequency count, e.g. obtained by histogram binedges : array, 1d binedges including lower and upper bound start : tuple or array_like ? starting values, needs to have correct length Returns ------- paramest : array estimated parameters Notes ----- todo: add fixed parameter option added factorial ''' if not fixed is None: raise NotImplementedError nobs = np.sum(freq) lnnobsfact = special.gammaln(nobs+1) def nloglike(params): '''negative loglikelihood function of binned data corresponds to multinomial ''' prob = np.diff(distfn.cdf(binedges, *params)) return -(lnnobsfact + np.sum(freq*np.log(prob)- special.gammaln(freq+1))) return optimize.fmin(nloglike, start) def fitbinnedgmm(distfn, freq, binedges, start, fixed=None, weightsoptimal=True): '''estimate parameters of distribution function for binned data using GMM Parameters ---------- distfn : distribution instance needs to have cdf method, as in scipy.stats freq : array, 1d frequency count, e.g. obtained by histogram binedges : array, 1d binedges including lower and upper bound start : tuple or array_like ? starting values, needs to have correct length fixed : None not used yet weightsoptimal : boolean If true, then the optimal weighting matrix for GMM is used. If false, then the identity matrix is used Returns ------- paramest : array estimated parameters Notes ----- todo: add fixed parameter option added factorial ''' if not fixed is None: raise NotImplementedError nobs = np.sum(freq) if weightsoptimal: weights = freq/float(nobs) else: weights = np.ones(len(freq)) freqnormed = freq/float(nobs) # skip turning weights into matrix diag(freq/float(nobs)) def gmmobjective(params): '''negative loglikelihood function of binned data corresponds to multinomial ''' prob = np.diff(distfn.cdf(binedges, *params)) momcond = freqnormed - prob return np.dot(momcond*weights, momcond) return optimize.fmin(gmmobjective, start) #Addition from try_maxproductspacings: """Estimating Parameters of Log-Normal Distribution with Maximum Likelihood and Maximum Product-of-Spacings MPS definiton from JKB page 233 Created on Tue May 11 13:52:50 2010 Author: josef-pktd License: BSD """ def hess_ndt(fun, pars, args, options): import numdifftools as ndt if not ('stepMax' in options or 'stepFix' in options): options['stepMax'] = 1e-5 f = lambda params: fun(params, *args) h = ndt.Hessian(f, **options) return h(pars), h def logmps(params, xsorted, dist): '''calculate negative log of Product-of-Spacings Parameters ---------- params : array_like, tuple ? parameters of the distribution funciton xsorted : array_like data that is already sorted dist : instance of a distribution class only cdf method is used Returns ------- mps : float negative log of Product-of-Spacings Notes ----- MPS definiton from JKB page 233 ''' xcdf = np.r_[0., dist.cdf(xsorted, *params), 1.] D = np.diff(xcdf) return -np.log(D).mean() def getstartparams(dist, data): '''get starting values for estimation of distribution parameters Parameters ---------- dist : distribution instance the distribution instance needs to have either a method fitstart or an attribute numargs data : ndarray data for which preliminary estimator or starting value for parameter estimation is desired Returns ------- x0 : ndarray preliminary estimate or starting value for the parameters of the distribution given the data, including loc and scale ''' if hasattr(dist, 'fitstart'): #x0 = getattr(dist, 'fitstart')(data) x0 = dist.fitstart(data) else: if np.isfinite(dist.a): x0 = np.r_[[1.]*dist.numargs, (data.min()-1), 1.] else: x0 = np.r_[[1.]*dist.numargs, (data.mean()-1), 1.] return x0 def fit_mps(dist, data, x0=None): '''Estimate distribution parameters with Maximum Product-of-Spacings Parameters ---------- params : array_like, tuple ? parameters of the distribution funciton xsorted : array_like data that is already sorted dist : instance of a distribution class only cdf method is used Returns ------- x : ndarray estimates for the parameters of the distribution given the data, including loc and scale ''' xsorted = np.sort(data) if x0 is None: x0 = getstartparams(dist, xsorted) args = (xsorted, dist) print x0 #print args return optimize.fmin(logmps, x0, args=args) if __name__ == '__main__': #Example: gamma - distribution #----------------------------- alpha = 2 xq = [0.5, 4] pq = [0.1, 0.9] print stats.gamma.ppf(pq, alpha) xq = stats.gamma.ppf(pq, alpha) print np.diff((stats.gamma.ppf(pq, np.linspace(0.01,4,10)[:,None])*xq[::-1])) #optimize.bisect(lambda alpha: np.diff((stats.gamma.ppf(pq, alpha)*xq[::-1]))) print optimize.fsolve(lambda alpha: np.diff((stats.gamma.ppf(pq, alpha)*xq[::-1])), 3.) distfn = stats.gamma mcond = gammamomentcond(distfn, [5.,10], mom2=stats.gamma.stats(alpha, 0.,1.), quantile=None) print optimize.fsolve(mcond, [1.,2.]) mom2 = stats.gamma.stats(alpha, 0.,1.) print optimize.fsolve(lambda params:gammamomentcond2(distfn, params, mom2), [1.,2.]) grvs = stats.gamma.rvs(alpha, 0.,2., size=1000) mom2 = np.array([grvs.mean(), grvs.var()]) alphaestq = optimize.fsolve(lambda params:gammamomentcond2(distfn, params, mom2), [1.,3.]) print alphaestq print 'scale = ', xq/stats.gamma.ppf(pq, alphaestq) #Example beta - distribution #--------------------------- #Warning: this example had cut-and-paste errors pq = np.array([0.01, 0.05,0.1,0.4,0.6,0.9,0.95,0.99]) rvsb = stats.beta.rvs(5,15,size=200) print stats.beta.fit(rvsb) xqsb = [stats.scoreatpercentile(rvsb, p) for p in pq*100] mom2s = np.array([rvsb.mean(), rvsb.var()]) betaparest_gmmquantile = optimize.fmin(lambda params:np.sum(momentcondquant(stats.beta, params, mom2s,(pq,xqsb), shape=None)**2), [10,10, 0., 1.]) print 'betaparest_gmmquantile', betaparest_gmmquantile #result sensitive to initial condition #Example t - distribution #------------------------ nobs = 1000 distfn = stats.t pq = np.array([0.1,0.9]) paramsdgp = (5, 0, 1) trvs = distfn.rvs(5, 0, 1, size=nobs) xqs = [stats.scoreatpercentile(trvs, p) for p in pq*100] mom2th = distfn.stats(*paramsdgp) mom2s = np.array([trvs.mean(), trvs.var()]) tparest_gmm3quantilefsolve = optimize.fsolve(lambda params:momentcondunbound(distfn,params, mom2s,(pq,xqs)), [10,1.,2.]) print 'tparest_gmm3quantilefsolve', tparest_gmm3quantilefsolve tparest_gmm3quantile = optimize.fmin(lambda params:np.sum(momentcondunbound(distfn,params, mom2s,(pq,xqs))**2), [10,1.,2.]) print 'tparest_gmm3quantile', tparest_gmm3quantile print distfn.fit(trvs) ## ##distfn = stats.t ##pq = np.array([0.1,0.9]) ##paramsdgp = (5, 0, 1) ##trvs = distfn.rvs(5, 0, 1, size=nobs) ##xqs = [stats.scoreatpercentile(trvs, p) for p in pq*100] ##mom2th = distfn.stats(*paramsdgp) ##mom2s = np.array([trvs.mean(), trvs.var()]) print optimize.fsolve(lambda params:momentcondunboundls(distfn, params, mom2s,shape=5), [1.,2.]) print optimize.fmin(lambda params:np.sum(momentcondunboundls(distfn, params, mom2s,shape=5)**2), [1.,2.]) print distfn.fit(trvs) #loc, scale, based on quantiles print optimize.fsolve(lambda params:momentcondunboundls(distfn, params, mom2s,(pq,xqs),shape=5), [1.,2.]) ## pq = np.array([0.01, 0.05,0.1,0.4,0.6,0.9,0.95,0.99]) #paramsdgp = (5, 0, 1) xqs = [stats.scoreatpercentile(trvs, p) for p in pq*100] tparest_gmmquantile = optimize.fmin(lambda params:np.sum(momentcondquant(distfn, params, mom2s,(pq,xqs), shape=None)**2), [10, 1.,2.]) print 'tparest_gmmquantile', tparest_gmmquantile tparest_gmmquantile2 = fitquantilesgmm(distfn, trvs, start=[10, 1.,2.], pquant=None, frozen=None) print 'tparest_gmmquantile2', tparest_gmmquantile2 ## #use trvs from before bt = stats.t.ppf(np.linspace(0,1,21),5) ft,bt = np.histogram(trvs,bins=bt) print 'fitbinned t-distribution' tparest_mlebinew = fitbinned(stats.t, ft, bt, [10, 0, 1]) tparest_gmmbinewidentity = fitbinnedgmm(stats.t, ft, bt, [10, 0, 1]) tparest_gmmbinewoptimal = fitbinnedgmm(stats.t, ft, bt, [10, 0, 1], weightsoptimal=False) print paramsdgp #Note: this can be used for chisquare test and then has correct asymptotic # distribution for a distribution with estimated parameters, find ref again #TODO combine into test with binning included, check rule for number of bins #bt2 = stats.t.ppf(np.linspace(trvs.,1,21),5) ft2,bt2 = np.histogram(trvs,bins=50) 'fitbinned t-distribution' tparest_mlebinel = fitbinned(stats.t, ft2, bt2, [10, 0, 1]) tparest_gmmbinelidentity = fitbinnedgmm(stats.t, ft2, bt2, [10, 0, 1]) tparest_gmmbineloptimal = fitbinnedgmm(stats.t, ft2, bt2, [10, 0, 1], weightsoptimal=False) tparest_mle = stats.t.fit(trvs) np.set_printoptions(precision=6) print 'sample size', nobs print 'true (df, loc, scale) ', paramsdgp print 'parest_mle ', tparest_mle print print 'tparest_mlebinel ', tparest_mlebinel print 'tparest_gmmbinelidentity ', tparest_gmmbinelidentity print 'tparest_gmmbineloptimal ', tparest_gmmbineloptimal print print 'tparest_mlebinew ', tparest_mlebinew print 'tparest_gmmbinewidentity ', tparest_gmmbinewidentity print 'tparest_gmmbinewoptimal ', tparest_gmmbinewoptimal print print 'tparest_gmmquantileidentity', tparest_gmmquantile print 'tparest_gmm3quantilefsolve ', tparest_gmm3quantilefsolve print 'tparest_gmm3quantile ', tparest_gmm3quantile ''' example results: standard error for df estimate looks large note: iI don't impose that df is an integer, (b/c not necessary) need Monte Carlo to check variance of estimators sample size 1000 true (df, loc, scale) (5, 0, 1) parest_mle [ 4.571405 -0.021493 1.028584] tparest_mlebinel [ 4.534069 -0.022605 1.02962 ] tparest_gmmbinelidentity [ 2.653056 0.012807 0.896958] tparest_gmmbineloptimal [ 2.437261 -0.020491 0.923308] tparest_mlebinew [ 2.999124 -0.0199 0.948811] tparest_gmmbinewidentity [ 2.900939 -0.020159 0.93481 ] tparest_gmmbinewoptimal [ 2.977764 -0.024925 0.946487] tparest_gmmquantileidentity [ 3.940797 -0.046469 1.002001] tparest_gmm3quantilefsolve [ 10. 1. 2.] tparest_gmm3quantile [ 6.376101 -0.029322 1.112403] ''' #Example with Maximum Product of Spacings Estimation #=================================================== #Example: Lognormal Distribution #------------------------------- #tough problem for MLE according to JKB #but not sure for which parameters sh = np.exp(10) sh = 0.01 print sh x = stats.lognorm.rvs(sh,loc=100, scale=10,size=200) print x.min() print stats.lognorm.fit(x, 1.,loc=x.min()-1,scale=1) xsorted = np.sort(x) x0 = [1., x.min()-1, 1] args = (xsorted, stats.lognorm) print optimize.fmin(logmps,x0,args=args) #Example: Lomax, Pareto, Generalized Pareto Distributions #-------------------------------------------------------- #partially a follow-up to the discussion about numpy.random.pareto #Reference: JKB #example Maximum Product of Spacings Estimation # current results: # doesn't look very good yet sensitivity to starting values # Pareto and Generalized Pareto look like a tough estimation problem #p2rvs = np.random.pareto(2,size=500)# + 1 p2rvs = stats.genpareto.rvs(2, size=500) #Note: is Lomax without +1; and classical Pareto with +1 p2rvssorted = np.sort(p2rvs) argsp = (p2rvssorted, stats.pareto) x0p = [1., p2rvs.min()-5, 1] print optimize.fmin(logmps,x0p,args=argsp) print stats.pareto.fit(p2rvs, 0.5, loc=-20, scale=0.5) print 'gpdparest_ mle', stats.genpareto.fit(p2rvs) parsgpd = fit_mps(stats.genpareto, p2rvs) print 'gpdparest_ mps', parsgpd argsgpd = (p2rvssorted, stats.genpareto) options = dict(stepFix=1e-7) #hess_ndt(fun, pars, argsgdp, options) #the results for the following look strange, maybe refactoring error he, h = hess_ndt(logmps, parsgpd, argsgpd, options) print np.linalg.eigh(he)[0] f = lambda params: logmps(params, *argsgpd) print f(parsgpd) #add binned fp2, bp2 = np.histogram(p2rvs, bins=50) 'fitbinned t-distribution' gpdparest_mlebinel = fitbinned(stats.genpareto, fp2, bp2, x0p) gpdparest_gmmbinelidentity = fitbinnedgmm(stats.genpareto, fp2, bp2, x0p) print 'gpdparest_mlebinel', gpdparest_mlebinel print 'gpdparest_gmmbinelidentity', gpdparest_gmmbinelidentity gpdparest_gmmquantile2 = fitquantilesgmm(stats.genpareto, p2rvs, start=x0p, pquant=None, frozen=None) print 'gpdparest_gmmquantile2', gpdparest_gmmquantile2 #something wrong : something hard coded ? ''' >>> fitquantilesgmm(stats.genpareto, p2rvs, start=x0p, pquant=np.linspace(0.5,0.95,10), frozen=None) Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> fitquantilesgmm(stats.genpareto, p2rvs, start=x0p, pquant=np.linspace(0.5,0.95,10), frozen=None) File "C:\...\scikits\statsmodels\sandbox\stats\distribution_estimators.py", line 224, in fitquantilesgmm parest = optimize.fmin(lambda params:np.sum(momentcondquant(distfn, params, mom2s,(pq,xqs), shape=None)**2), start) File "c:\...\scipy-trunk_after\trunk\dist\scipy-0.8.0.dev6156.win32\programs\python25\lib\site-packages\scipy\optimize\optimize.py", line 183, in fmin fsim[0] = func(x0) File "c:\...\scipy-trunk_after\trunk\dist\scipy-0.8.0.dev6156.win32\programs\python25\lib\site-packages\scipy\optimize\optimize.py", line 103, in function_wrapper return function(x, *args) File "C:\...\scikits\statsmodels\sandbox\stats\distribution_estimators.py", line 224, in <lambda> parest = optimize.fmin(lambda params:np.sum(momentcondquant(distfn, params, mom2s,(pq,xqs), shape=None)**2), start) File "C:\...\scikits\statsmodels\sandbox\stats\distribution_estimators.py", line 210, in momentcondquant cdfdiff = distfn.cdf(xq, *params) - pq ValueError: shape mismatch: objects cannot be broadcast to a single shape ''' print fitquantilesgmm(stats.genpareto, p2rvs, start=x0p, pquant=np.linspace(0.01,0.99,10), frozen=None) fp2, bp2 = np.histogram(p2rvs, bins=stats.genpareto(2).ppf(np.linspace(0,0.99,10))) print 'fitbinnedgmm equal weight bins', print fitbinnedgmm(stats.genpareto, fp2, bp2, x0p)
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests the IamRulesEngine.""" import copy import itertools import mock import yaml from tests.unittest_utils import ForsetiTestCase from google.cloud.security.common.data_access import _db_connector from google.cloud.security.common.data_access import org_resource_rel_dao as org_rel_dao from google.cloud.security.common.gcp_type.iam_policy import IamPolicyBinding from google.cloud.security.common.gcp_type.iam_policy import IamPolicyMember from google.cloud.security.common.gcp_type.organization import Organization from google.cloud.security.common.gcp_type.project import Project from google.cloud.security.common.util import file_loader from google.cloud.security.scanner.audit.errors import InvalidRulesSchemaError from google.cloud.security.scanner.audit import iam_rules_engine as ire from google.cloud.security.scanner.audit import rules as scanner_rules from tests.unittest_utils import get_datafile_path from tests.scanner.audit.data import test_rules class IamRulesEngineTest(ForsetiTestCase): """Tests for the IamRulesEngine.""" def setUp(self): """Set up.""" self.fake_timestamp = '12345' self.org789 = Organization('778899', display_name='My org') self.project1 = Project( 'my-project-1', 12345, display_name='My project 1', parent=self.org789) self.project2 = Project('my-project-2', 12346, display_name='My project 2') # patch the organization resource relation dao self.patcher = mock.patch('google.cloud.security.common.data_access.org_resource_rel_dao.OrgResourceRelDao') self.mock_org_rel_dao = self.patcher.start() self.mock_org_rel_dao.return_value = None def tearDown(self): self.patcher.stop() def test_build_rule_book_from_local_yaml_file_works(self): """Test that a RuleBook is built correctly with a yaml file.""" rules_local_path = get_datafile_path(__file__, 'test_rules_1.yaml') rules_engine = ire.IamRulesEngine(rules_file_path=rules_local_path) rules_engine.build_rule_book({}) self.assertEqual(4, len(rules_engine.rule_book.resource_rules_map)) def test_build_rule_book_from_local_json_file_works(self): """Test that a RuleBook is built correctly with a json file.""" rules_local_path = get_datafile_path(__file__, 'test_rules_1.json') rules_engine = ire.IamRulesEngine(rules_file_path=rules_local_path) rules_engine.build_rule_book({}) self.assertEqual(4, len(rules_engine.rule_book.resource_rules_map)) @mock.patch.object(file_loader, '_read_file_from_gcs', autospec=True) def test_build_rule_book_from_gcs_works(self, mock_load_rules_from_gcs): """Test that a RuleBook is built correctly with a mocked gcs file. Setup: * Create a mocked GCS object from a test yaml file. * Get the yaml file content. Expected results: There are 4 resources that have rules, in the rule book. """ bucket_name = 'bucket-name' rules_path = 'input/test_rules_1.yaml' full_rules_path = 'gs://{}/{}'.format(bucket_name, rules_path) rules_engine = ire.IamRulesEngine(rules_file_path=full_rules_path) # Read in the rules file file_content = None with open(get_datafile_path(__file__, 'test_rules_1.yaml'), 'r') as rules_local_file: try: file_content = yaml.safe_load(rules_local_file) except yaml.YAMLError: raise mock_load_rules_from_gcs.return_value = file_content rules_engine.build_rule_book({}) self.assertEqual(4, len(rules_engine.rule_book.resource_rules_map)) def test_build_rule_book_no_resource_type_fails(self): """Test that a rule without a resource type cannot be created.""" rules_local_path = get_datafile_path(__file__, 'test_rules_2.yaml') rules_engine = ire.IamRulesEngine(rules_file_path=rules_local_path) with self.assertRaises(InvalidRulesSchemaError): rules_engine.build_rule_book({}) def test_add_single_rule_builds_correct_map(self): """Test that adding a single rule builds the correct map.""" rule_book = ire.IamRuleBook( {}, test_rules.RULES1, self.fake_timestamp) actual_rules = rule_book.resource_rules_map # expected rule_bindings = [{ 'role': 'roles/*', 'members': ['user:*@company.com'] }] rule = scanner_rules.Rule('my rule', 0, [IamPolicyBinding.create_from(b) for b in rule_bindings], mode='whitelist') expected_org_rules = ire.ResourceRules(self.org789, rules=set([rule]), applies_to='self_and_children') expected_proj1_rules = ire.ResourceRules(self.project1, rules=set([rule]), applies_to='self') expected_proj2_rules = ire.ResourceRules(self.project2, rules=set([rule]), applies_to='self') expected_rules = { (self.org789, 'self_and_children'): expected_org_rules, (self.project1, 'self'): expected_proj1_rules, (self.project2, 'self'): expected_proj2_rules } self.assertEqual(expected_rules, actual_rules) def test_invalid_rule_mode_raises_when_verify_mode(self): """Test that an invalid rule mode raises error.""" with self.assertRaises(InvalidRulesSchemaError): scanner_rules.RuleMode.verify('nonexistent mode') def test_invalid_rule_mode_raises_when_create_rule(self): """Test that creating a Rule with invalid rule mode raises error.""" with self.assertRaises(InvalidRulesSchemaError): scanner_rules.Rule('exception', 0, []) def test_policy_binding_matches_whitelist_rules(self): """Test that a policy binding matches the whitelist rules. Setup: * Create a test policy binding. * Create a test rule binding. * Create a whitelist rule with the test rules. Expected results: All policy binding members are in the whitelist. """ test_binding = { 'role': 'roles/owner', 'members': [ 'user:foo@company.com', 'user:abc@def.somewhere.com', 'group:some-group@googlegroups.com', 'serviceAccount:12345@iam.gserviceaccount.com', ] } rule_bindings = [ { 'role': 'roles/owner', 'members': [ 'user:*@company.com', 'user:abc@*.somewhere.com', 'group:*@googlegroups.com', 'serviceAccount:*@*.gserviceaccount.com', ] } ] rule = scanner_rules.Rule('test rule', 0, [IamPolicyBinding.create_from(b) for b in rule_bindings], mode='whitelist') resource_rule = ire.ResourceRules(rules=[rule]) results = list(resource_rule.find_mismatches( self.project1, test_binding)) self.assertEqual(0, len(results)) def test_policy_binding_does_not_match_blacklist_rules(self): """Test that a policy binding does not match the blacklist. Setup: * Create a test policy binding. * Create a test rule binding. * Create a blacklist rule with the test rules. Expected results: No policy bindings found in the blacklist. """ test_binding = { 'role': 'roles/owner', 'members': [ 'user:someone@notcompany.com', ] } rule_bindings = [ { 'role': 'roles/owner', 'members': [ 'user:*@company.com', 'user:abc@*.somewhere.com', 'group:*@googlegroups.com', 'serviceAccount:*@*.gserviceaccount.com', ] } ] rule = scanner_rules.Rule('test rule', 0, [IamPolicyBinding.create_from(b) for b in rule_bindings], mode='blacklist') resource_rule = ire.ResourceRules(rules=[rule]) results = list(resource_rule.find_mismatches( self.project1, test_binding)) self.assertEqual(0, len(results)) def test_policy_binding_matches_required_rules(self): """Test that a required list of members are found in policy binding. Setup: * Create a test policy binding. * Create a test rule binding. * Create a required rule with the test rules. Expected results: All required members are found in the policy. """ test_binding = { 'role': 'roles/owner', 'members': [ 'user:foo@company.com', 'user:abc@def.somewhere.com', 'group:some-group@googlegroups.com', 'serviceAccount:12345@iam.gserviceaccount.com', ] } rule_bindings = [ { 'role': 'roles/owner', 'members': [ 'user:foo@company.com', 'user:abc@def.somewhere.com', ] } ] rule = scanner_rules.Rule('test rule', 0, [IamPolicyBinding.create_from(b) for b in rule_bindings], mode='required') resource_rule = ire.ResourceRules(rules=[rule]) results = list(resource_rule.find_mismatches( self.project1, test_binding)) self.assertEqual(0, len(results)) def test_policy_binding_mismatches_required_rules(self): """Test that a required list of members mismatches policy binding. Setup: * Create a test policy binding. * Create a test rule binding. * Create a required rule with the test rules. Expected results: All required members are found in the policy. """ test_binding = { 'role': 'roles/owner', 'members': [ 'user:foo@company.com.abc', 'group:some-group@googlegroups.com', 'serviceAccount:12345@iam.gserviceaccount.com', ] } rule_bindings = [ { 'role': 'roles/owner', 'members': [ 'user:foo@company.com', 'user:abc@def.somewhere.com', ] } ] rule = scanner_rules.Rule('test rule', 0, [IamPolicyBinding.create_from(b) for b in rule_bindings], mode='required') resource_rule = ire.ResourceRules(resource=self.project1) resource_rule.rules.add(rule) results = list(resource_rule.find_mismatches( self.project1, test_binding)) self.assertEqual(1, len(results)) def test_one_member_mismatch(self): """Test a policy where one member mismatches the whitelist. Setup: * Create a RulesEngine and add test_rules.RULES1. * Create the policy binding. * Create the Rule and rule bindings. * Create the resource association for the Rule. Expected results: One policy binding member missing from the whitelist. """ # actual rules_local_path = get_datafile_path(__file__, 'test_rules_1.yaml') rules_engine = ire.IamRulesEngine(rules_local_path) rules_engine.rule_book = ire.IamRuleBook( {}, test_rules.RULES1, self.fake_timestamp) rules_engine.rule_book.org_res_rel_dao = mock.MagicMock() find_ancestor_mock = mock.MagicMock( side_effect=[[self.org789]]) rules_engine.rule_book.org_res_rel_dao.find_ancestors = \ find_ancestor_mock policy = { 'bindings': [{ 'role': 'roles/editor', 'members': ['user:abc@company.com', 'user:def@goggle.com'] }]} actual_violations = set(rules_engine.find_policy_violations( self.project1, policy)) # expected rule_bindings = [{ 'role': 'roles/*', 'members': ['user:*@company.com'] }] rule = scanner_rules.Rule('my rule', 0, [IamPolicyBinding.create_from(b) for b in rule_bindings], mode='whitelist') expected_outstanding = { 'roles/editor': [ IamPolicyMember.create_from('user:def@goggle.com') ] } expected_violations = set([ scanner_rules.RuleViolation( resource_type=self.project1.type, resource_id=self.project1.id, rule_name=rule.rule_name, rule_index=rule.rule_index, role='roles/editor', violation_type=scanner_rules.VIOLATION_TYPE.get(rule.mode), members=tuple(expected_outstanding['roles/editor'])) ]) self.assertEqual(expected_violations, actual_violations) def test_no_mismatch(self): """Test a policy where no members mismatch the whitelist. Setup: * Create a RulesEngine and add test_rules.RULES1. * Create the policy binding. * Create the Rule and rule bindings. * Create the resource association for the Rule. Expected results: No policy binding members missing from the whitelist. """ # actual rules_local_path = get_datafile_path(__file__, 'test_rules_1.yaml') rules_engine = ire.IamRulesEngine(rules_local_path) rules_engine.rule_book = ire.IamRuleBook( {}, test_rules.RULES1, self.fake_timestamp) rules_engine.rule_book.org_res_rel_dao = mock.MagicMock() find_ancestor_mock = mock.MagicMock( side_effect=[[self.org789]]) rules_engine.rule_book.org_res_rel_dao.find_ancestors = \ find_ancestor_mock policy = { 'bindings': [{ 'role': 'roles/editor', 'members': ['user:abc@company.com', 'user:def@company.com'] }] } actual_violations = set(rules_engine.find_policy_violations( self.project1, policy)) # expected expected_violations = set() self.assertEqual(expected_violations, actual_violations) def test_policy_with_no_rules_has_no_violations(self): """Test a policy against an empty RuleBook. Setup: * Create a Rules Engine * Create the policy bindings. * Created expected violations list. Expected results: No policy violations found. """ self.mock_org_rel_dao.find_ancestors = mock.MagicMock( side_effect=[self.org789]) # actual rules_local_path = get_datafile_path(__file__, 'test_rules_1.yaml') rules_engine = ire.IamRulesEngine(rules_local_path) rules_engine.rule_book = ire.IamRuleBook( {}, snapshot_timestamp=self.fake_timestamp) rules_engine.rule_book.org_res_rel_dao = mock.MagicMock() find_ancestor_mock = mock.MagicMock( side_effect=[[self.org789]]) rules_engine.rule_book.org_res_rel_dao.find_ancestors = \ find_ancestor_mock policy = { 'bindings': [{ 'role': 'roles/editor', 'members': ['user:abc@company.com', 'user:def@company.com'] }] } actual_violations = set(rules_engine.find_policy_violations( self.project1, policy)) # expected expected_violations = set() self.assertEqual(expected_violations, actual_violations) def test_empty_policy_with_rules_no_violations(self): """Test an empty policy against the RulesEngine with rules. Setup: * Create a RulesEngine. * Created expected violations list. Expected results: No policy violations found. """ # actual rules_local_path = get_datafile_path(__file__, 'test_rules_1.yaml') rules_engine = ire.IamRulesEngine(rules_local_path) rules_engine.rule_book = ire.IamRuleBook( {}, test_rules.RULES1, self.fake_timestamp) rules_engine.rule_book.org_res_rel_dao = mock.MagicMock() find_ancestor_mock = mock.MagicMock( side_effect=[[self.org789]]) rules_engine.rule_book.org_res_rel_dao.find_ancestors = \ find_ancestor_mock actual_violations = set(rules_engine.find_policy_violations( self.project1, {})) # expected expected_violations = set() self.assertEqual(expected_violations, actual_violations) def test_whitelist_blacklist_rules_vs_policy_has_violations(self): """Test a ruleset with whitelist and blacklist violating rules. Setup: * Mock find_ancestors(). * Create a RulesEngine with RULES2 rule set. * Create policy. Expected result: * Find 1 rule violation. """ # actual rules_local_path = get_datafile_path(__file__, 'test_rules_1.yaml') rules_engine = ire.IamRulesEngine(rules_local_path, self.fake_timestamp) # TODO: mock the rules local path to return RULES2 rules_engine.rule_book = ire.IamRuleBook( {}, test_rules.RULES2, self.fake_timestamp) rules_engine.rule_book.org_res_rel_dao = mock.MagicMock() find_ancestor_mock = mock.MagicMock( side_effect=[[self.org789], []]) rules_engine.rule_book.org_res_rel_dao.find_ancestors = \ find_ancestor_mock policy = { 'bindings': [ { 'role': 'roles/editor', 'members': [ 'user:baduser@company.com', 'user:okuser@company.com', 'user:otheruser@other.com' ] } ] } actual_violations = set(itertools.chain( rules_engine.find_policy_violations(self.project1, policy), rules_engine.find_policy_violations(self.project2, policy))) # expected expected_outstanding1 = { 'roles/editor': [ IamPolicyMember.create_from('user:otheruser@other.com') ] } expected_outstanding2 = { 'roles/editor': [ IamPolicyMember.create_from('user:baduser@company.com') ] } expected_violations = set([ scanner_rules.RuleViolation( rule_index=0, rule_name='my rule', resource_id=self.project1.id, resource_type=self.project1.type, violation_type='ADDED', role=policy['bindings'][0]['role'], members=tuple(expected_outstanding1['roles/editor'])), scanner_rules.RuleViolation( rule_index=0, rule_name='my rule', resource_type=self.project2.type, resource_id=self.project2.id, violation_type='ADDED', role=policy['bindings'][0]['role'], members=tuple(expected_outstanding1['roles/editor'])), scanner_rules.RuleViolation( rule_index=1, rule_name='my other rule', resource_type=self.project2.type, resource_id=self.project2.id, violation_type='ADDED', role=policy['bindings'][0]['role'], members=tuple(expected_outstanding2['roles/editor'])), scanner_rules.RuleViolation( rule_index=2, rule_name='required rule', resource_id=self.project1.id, resource_type=self.project1.type, violation_type='REMOVED', role='roles/viewer', members=tuple([IamPolicyMember.create_from( 'user:project_viewer@company.com')])) ]) self.assertItemsEqual(expected_violations, actual_violations) def test_org_whitelist_rules_vs_policy_no_violations(self): """Test ruleset on an org with whitelist with no rule violations. Setup: * Create a RulesEngine with RULES1 rule set. * Create policy. Expected result: * Find no rule violations. """ # actual rules_local_path = get_datafile_path(__file__, 'test_rules_1.yaml') rules_engine = ire.IamRulesEngine(rules_local_path) rules_engine.rule_book = ire.IamRuleBook( {}, test_rules.RULES1, self.fake_timestamp) rules_engine.rule_book.org_res_rel_dao = mock.MagicMock() find_ancestor_mock = mock.MagicMock( side_effect=[[]]) rules_engine.rule_book.org_res_rel_dao.find_ancestors = \ find_ancestor_mock policy = { 'bindings': [ { 'role': 'roles/editor', 'members': [ 'user:okuser@company.com', ] } ] } actual_violations = set(rules_engine.find_policy_violations( self.org789, policy)) self.assertItemsEqual(set(), actual_violations) def test_org_proj_rules_vs_policy_has_violations(self): """Test rules on org and project with whitelist, blacklist, required. Test whitelist, blacklist, and required rules against an org that has 1 blacklist violation and a project that has 1 whitelist violation and 1 required violation. Setup: * Create a RulesEngine with RULES3 rule set. * Create policy. Expected result: * Find 3 rule violations. """ # actual rules_local_path = get_datafile_path(__file__, 'test_rules_1.yaml') rules_engine = ire.IamRulesEngine(rules_local_path) rules_engine.rule_book = ire.IamRuleBook( {}, test_rules.RULES3, self.fake_timestamp) rules_engine.rule_book.org_res_rel_dao = mock.MagicMock() find_ancestor_mock = mock.MagicMock( side_effect=[[], [self.org789]]) rules_engine.rule_book.org_res_rel_dao.find_ancestors = \ find_ancestor_mock org_policy = { 'bindings': [ { 'role': 'roles/editor', 'members': [ 'user:okuser@company.com', 'user:baduser@company.com', ] } ] } project_policy = { 'bindings': [ { 'role': 'roles/editor', 'members': [ 'user:okuserr2@company.com', 'user:user@other.com', ] } ] } actual_violations = set(itertools.chain( rules_engine.find_policy_violations(self.org789, org_policy), rules_engine.find_policy_violations(self.project1, project_policy), )) # expected expected_outstanding_org = { 'roles/editor': [ IamPolicyMember.create_from('user:baduser@company.com') ] } expected_outstanding_project = { 'roles/editor': [ IamPolicyMember.create_from('user:user@other.com') ], 'roles/viewer': [ IamPolicyMember.create_from('user:project_viewer@company.com') ] } expected_violations = set([ scanner_rules.RuleViolation( rule_index=1, rule_name='my blacklist rule', resource_id=self.org789.id, resource_type=self.org789.type, violation_type='ADDED', role=org_policy['bindings'][0]['role'], members=tuple(expected_outstanding_org['roles/editor'])), scanner_rules.RuleViolation( rule_index=0, rule_name='my whitelist rule', resource_id=self.project1.id, resource_type=self.project1.type, violation_type='ADDED', role=project_policy['bindings'][0]['role'], members=tuple(expected_outstanding_project['roles/editor'])), scanner_rules.RuleViolation( rule_index=2, rule_name='my required rule', resource_id=self.project1.id, resource_type=self.project1.type, violation_type='REMOVED', role='roles/viewer', members=tuple(expected_outstanding_project['roles/viewer'])), ]) self.assertItemsEqual(expected_violations, actual_violations) def test_org_self_rules_work_with_org_child_rules(self): """Test org "self" whitelist works with org "children" whitelist Test hierarchical rules. Setup: * Create a RulesEngine with RULES4 rule set. * Create policy. Expected result: * Find 3 rule violations. """ # actual rules_local_path = get_datafile_path(__file__, 'test_rules_1.yaml') rules_engine = ire.IamRulesEngine(rules_local_path) rules_engine.rule_book = ire.IamRuleBook( {}, test_rules.RULES4, self.fake_timestamp) rules_engine.rule_book.org_res_rel_dao = mock.MagicMock() find_ancestor_mock = mock.MagicMock( side_effect=[[], [self.org789]]) rules_engine.rule_book.org_res_rel_dao.find_ancestors = \ find_ancestor_mock org_policy = { 'bindings': [ { 'role': 'roles/owner', 'members': [ 'user:owner@company.com', 'user:baduser@company.com', ] } ] } project_policy = { 'bindings': [ { 'role': 'roles/editor', 'members': [ 'user:okuser2@company.com', 'user:user@other.com', ] } ] } actual_violations = set(itertools.chain( rules_engine.find_policy_violations(self.org789, org_policy), rules_engine.find_policy_violations(self.project1, project_policy))) # expected expected_outstanding_org = { 'roles/owner': [ IamPolicyMember.create_from('user:baduser@company.com') ] } expected_outstanding_proj = { 'roles/editor': [ IamPolicyMember.create_from('user:user@other.com') ] } expected_violations = set([ scanner_rules.RuleViolation( rule_index=0, rule_name='org whitelist', resource_id=self.org789.id, resource_type=self.org789.type, violation_type='ADDED', role=org_policy['bindings'][0]['role'], members=tuple(expected_outstanding_org['roles/owner'])), scanner_rules.RuleViolation( rule_index=1, rule_name='project whitelist', resource_id=self.project1.id, resource_type=self.project1.type, violation_type='ADDED', role=project_policy['bindings'][0]['role'], members=tuple(expected_outstanding_proj['roles/editor'])), ]) self.assertItemsEqual(expected_violations, actual_violations) def test_org_project_noinherit_project_overrides_org_rule(self): """Test org with blacklist and child with whitelist, no inherit. Test that the project whitelist rule overrides the org blacklist rule when the project does not inherit from parent. Setup: * Create a RulesEngine with RULES5 rule set. * Create policy. Expected result: * Find 0 rule violations. """ # actual rules_local_path = get_datafile_path(__file__, 'test_rules_1.yaml') rules_engine = ire.IamRulesEngine(rules_local_path) rules_engine.rule_book = ire.IamRuleBook( {}, test_rules.RULES5, self.fake_timestamp) rules_engine.rule_book.org_res_rel_dao = mock.MagicMock() find_ancestor_mock = mock.MagicMock( side_effect=[[self.org789]]) rules_engine.rule_book.org_res_rel_dao.find_ancestors = \ find_ancestor_mock project_policy = { 'bindings': [ { 'role': 'roles/owner', 'members': [ 'user:owner@company.com', ] } ] } actual_violations = set( rules_engine.find_policy_violations(self.project1, project_policy) ) # expected expected_outstanding_proj = { 'roles/editor': [ IamPolicyMember.create_from('user:user@other.com') ] } expected_violations = set([]) self.assertItemsEqual(expected_violations, actual_violations) def test_org_2_child_rules_report_violation(self): """Test org "children" whitelist works with org "children" blacklist. Test that org children whitelist with org children blacklist rules report violation. Setup: * Create a RulesEngine with RULES6 rule set. * Create policy. Expected result: * Find 1 rule violation. """ # actual rules_local_path = get_datafile_path(__file__, 'test_rules_1.yaml') rules_engine = ire.IamRulesEngine(rules_local_path) rules_engine.rule_book = ire.IamRuleBook( {}, test_rules.RULES6, self.fake_timestamp) rules_engine.rule_book.org_res_rel_dao = mock.MagicMock() find_ancestor_mock = mock.MagicMock( side_effect=[[self.org789]]) rules_engine.rule_book.org_res_rel_dao.find_ancestors = \ find_ancestor_mock project_policy = { 'bindings': [ { 'role': 'roles/owner', 'members': [ 'user:owner@company.com', ] } ] } actual_violations = set( rules_engine.find_policy_violations(self.project1, project_policy) ) # expected expected_outstanding_proj = { 'roles/owner': [ IamPolicyMember.create_from('user:owner@company.com') ] } expected_violations = set([ scanner_rules.RuleViolation( rule_index=1, rule_name='project blacklist', resource_id=self.project1.id, resource_type=self.project1.type, violation_type='ADDED', role=project_policy['bindings'][0]['role'], members=tuple(expected_outstanding_proj['roles/owner'])), ]) self.assertItemsEqual(expected_violations, actual_violations) def test_org_project_inherit_org_rule_violation(self): """Test org with blacklist and child with whitelist, no inherit. Test that the project whitelist rule overrides the org blacklist rule when the project does not inherit from parent. Setup: * Create a RulesEngine with RULES5 rule set. * Create policy. Expected result: * Find 1 rule violation. """ # actual rules_local_path = get_datafile_path(__file__, 'test_rules_1.yaml') rules_engine = ire.IamRulesEngine(rules_local_path) rules5 = copy.deepcopy(test_rules.RULES5) rules5['rules'][1]['inherit_from_parents'] = True rules_engine.rule_book = ire.IamRuleBook( {}, rules5, self.fake_timestamp) rules_engine.rule_book.org_res_rel_dao = mock.MagicMock() find_ancestor_mock = mock.MagicMock( side_effect=[[self.org789]]) rules_engine.rule_book.org_res_rel_dao.find_ancestors = \ find_ancestor_mock project_policy = { 'bindings': [ { 'role': 'roles/owner', 'members': [ 'user:owner@company.com', ] } ] } actual_violations = set( rules_engine.find_policy_violations(self.project1, project_policy) ) # expected expected_outstanding_proj = { 'roles/owner': [ IamPolicyMember.create_from('user:owner@company.com') ] } expected_violations = set([ scanner_rules.RuleViolation( rule_index=0, rule_name='org blacklist', resource_id=self.project1.id, resource_type=self.project1.type, violation_type='ADDED', role=project_policy['bindings'][0]['role'], members=tuple(expected_outstanding_proj['roles/owner'])), ]) self.assertItemsEqual(expected_violations, actual_violations) def test_org_self_bl_proj_noinherit_wl_no_violation(self): """Test proj policy doesn't violate rule b/l user (org), w/l (project). Test that an org with a blacklist on the org level plus a project whitelist with no rule inheritance allows the user blacklisted by the org, on the project level. Setup: * Create a RulesEngine with RULES5 rule set. * Tweak the rules to make the org blacklist apply to "self". * Create policy. Expected result: * Find 0 rule violations. """ # actual rules_local_path = get_datafile_path(__file__, 'test_rules_1.yaml') rules_engine = ire.IamRulesEngine(rules_local_path) rules5 = copy.deepcopy(test_rules.RULES5) rules5['rules'][0]['resource'][0]['applies_to'] = 'self' rules_engine.rule_book = ire.IamRuleBook( {}, rules5, self.fake_timestamp) rules_engine.rule_book.org_res_rel_dao = mock.MagicMock() find_ancestor_mock = mock.MagicMock( side_effect=[[self.org789]]) rules_engine.rule_book.org_res_rel_dao.find_ancestors = \ find_ancestor_mock project_policy = { 'bindings': [{ 'role': 'roles/owner', 'members': [ 'user:owner@company.com', ] }] } actual_violations = set( rules_engine.find_policy_violations(self.project1, project_policy) ) # expected expected_violations = set([]) self.assertItemsEqual(expected_violations, actual_violations) def test_org_self_wl_proj_noinherit_bl_has_violation(self): """Test org allowing user + proj blacklisting user has violation. Test that org children whitelist with org children blacklist rules report violation. Setup: * Create a RulesEngine with RULES6 rule set. * Create policy. Expected result: * Find 1 rule violation. """ # actual rules_local_path = get_datafile_path(__file__, 'test_rules_1.yaml') rules_engine = ire.IamRulesEngine(rules_local_path) rules6 = copy.deepcopy(test_rules.RULES6) rules6['rules'][0]['resource'][0]['applies_to'] = 'self' rules_engine.rule_book = ire.IamRuleBook( {}, rules6, self.fake_timestamp) rules_engine.rule_book.org_res_rel_dao = mock.MagicMock() find_ancestor_mock = mock.MagicMock( side_effect=[[], [self.org789]]) rules_engine.rule_book.org_res_rel_dao.find_ancestors = \ find_ancestor_mock org_policy = { 'bindings': [ { 'role': 'roles/owner', 'members': [ 'user:owner@company.com', ] } ] } project_policy = { 'bindings': [ { 'role': 'roles/owner', 'members': [ 'user:owner@company.com', ] } ] } actual_violations = set(itertools.chain( rules_engine.find_policy_violations(self.org789, org_policy), rules_engine.find_policy_violations(self.project1, project_policy) )) # expected expected_outstanding_proj = { 'roles/owner': [ IamPolicyMember.create_from('user:owner@company.com') ] } expected_violations = set([ scanner_rules.RuleViolation( rule_index=1, rule_name='project blacklist', resource_id=self.project1.id, resource_type=self.project1.type, violation_type='ADDED', role=project_policy['bindings'][0]['role'], members=tuple(expected_outstanding_proj['roles/owner'])), ]) self.assertItemsEqual(expected_violations, actual_violations) def test_ignore_case_works(self): """Test blacklisted user with different case still violates rule. Test that a project's user with a multi-case identifier still violates the blacklist. Setup: * Create a RulesEngine with RULES6 rule set. * Create policy. Expected result: * Find 1 rule violation. """ # actual rules_local_path = get_datafile_path(__file__, 'test_rules_1.yaml') rules_engine = ire.IamRulesEngine(rules_local_path) rules_engine.rule_book = ire.IamRuleBook( {}, test_rules.RULES6, self.fake_timestamp) rules_engine.rule_book.org_res_rel_dao = mock.MagicMock() find_ancestor_mock = mock.MagicMock( side_effect=[[self.org789]]) rules_engine.rule_book.org_res_rel_dao.find_ancestors = \ find_ancestor_mock project_policy = { 'bindings': [ { 'role': 'roles/owner', 'members': [ 'user:OWNER@company.com', ] } ] } actual_violations = set( rules_engine.find_policy_violations(self.project1, project_policy) ) # expected expected_outstanding_proj = { 'roles/owner': [ IamPolicyMember.create_from('user:OWNER@company.com') ] } expected_violations = set([ scanner_rules.RuleViolation( rule_index=1, rule_name='project blacklist', resource_id=self.project1.id, resource_type=self.project1.type, violation_type='ADDED', role=project_policy['bindings'][0]['role'], members=tuple(expected_outstanding_proj['roles/owner'])), ]) self.assertItemsEqual(expected_violations, actual_violations) if __name__ == '__main__': unittest.main()
""" Component that will help set the Microsoft face for verify processing. For more details about this component, please refer to the documentation at https://home-assistant.io/components/image_processing.microsoft_face_identify/ """ import asyncio import logging import voluptuous as vol from homeassistant.core import split_entity_id, callback from homeassistant.const import STATE_UNKNOWN from homeassistant.exceptions import HomeAssistantError from homeassistant.components.microsoft_face import DATA_MICROSOFT_FACE from homeassistant.components.image_processing import ( PLATFORM_SCHEMA, ImageProcessingEntity, CONF_CONFIDENCE, CONF_SOURCE, CONF_ENTITY_ID, CONF_NAME, ATTR_ENTITY_ID, ATTR_CONFIDENCE) import homeassistant.helpers.config_validation as cv from homeassistant.util.async import run_callback_threadsafe DEPENDENCIES = ['microsoft_face'] _LOGGER = logging.getLogger(__name__) EVENT_DETECT_FACE = 'image_processing.detect_face' ATTR_NAME = 'name' ATTR_TOTAL_FACES = 'total_faces' ATTR_AGE = 'age' ATTR_GENDER = 'gender' ATTR_MOTION = 'motion' ATTR_GLASSES = 'glasses' ATTR_FACES = 'faces' CONF_GROUP = 'group' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_GROUP): cv.slugify, }) @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): """Set up the Microsoft Face identify platform.""" api = hass.data[DATA_MICROSOFT_FACE] face_group = config[CONF_GROUP] confidence = config[CONF_CONFIDENCE] entities = [] for camera in config[CONF_SOURCE]: entities.append(MicrosoftFaceIdentifyEntity( camera[CONF_ENTITY_ID], api, face_group, confidence, camera.get(CONF_NAME) )) async_add_devices(entities) class ImageProcessingFaceEntity(ImageProcessingEntity): """Base entity class for face image processing.""" def __init__(self): """Initialize base face identify/verify entity.""" self.faces = [] self.total_faces = 0 @property def state(self): """Return the state of the entity.""" confidence = 0 state = STATE_UNKNOWN # No confidence support if not self.confidence: return self.total_faces # Search high confidence for face in self.faces: if ATTR_CONFIDENCE not in face: continue f_co = face[ATTR_CONFIDENCE] if f_co > confidence: confidence = f_co for attr in [ATTR_NAME, ATTR_MOTION]: if attr in face: state = face[attr] break return state @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" return 'face' @property def state_attributes(self): """Return device specific state attributes.""" attr = { ATTR_FACES: self.faces, ATTR_TOTAL_FACES: self.total_faces, } return attr def process_faces(self, faces, total): """Send event with detected faces and store data.""" run_callback_threadsafe( self.hass.loop, self.async_process_faces, faces, total).result() @callback def async_process_faces(self, faces, total): """Send event with detected faces and store data. known are a dict in follow format: [ { ATTR_CONFIDENCE: 80, ATTR_NAME: 'Name', ATTR_AGE: 12.0, ATTR_GENDER: 'man', ATTR_MOTION: 'smile', ATTR_GLASSES: 'sunglasses' }, ] This method must be run in the event loop. """ # Send events for face in faces: if ATTR_CONFIDENCE in face and self.confidence: if face[ATTR_CONFIDENCE] < self.confidence: continue face.update({ATTR_ENTITY_ID: self.entity_id}) self.hass.async_add_job( self.hass.bus.async_fire, EVENT_DETECT_FACE, face ) # Update entity store self.faces = faces self.total_faces = total class MicrosoftFaceIdentifyEntity(ImageProcessingFaceEntity): """Representation of the Microsoft Face API entity for identify.""" def __init__(self, camera_entity, api, face_group, confidence, name=None): """Initialize the Microsoft Face API.""" super().__init__() self._api = api self._camera = camera_entity self._confidence = confidence self._face_group = face_group if name: self._name = name else: self._name = "MicrosoftFace {0}".format( split_entity_id(camera_entity)[1]) @property def confidence(self): """Return minimum confidence for send events.""" return self._confidence @property def camera_entity(self): """Return camera entity id from process pictures.""" return self._camera @property def name(self): """Return the name of the entity.""" return self._name @asyncio.coroutine def async_process_image(self, image): """Process image. This method is a coroutine. """ detect = None try: face_data = yield from self._api.call_api( 'post', 'detect', image, binary=True) if face_data is None or len(face_data) < 1: return face_ids = [data['faceId'] for data in face_data] detect = yield from self._api.call_api( 'post', 'identify', {'faceIds': face_ids, 'personGroupId': self._face_group}) except HomeAssistantError as err: _LOGGER.error("Can't process image on Microsoft face: %s", err) return # Parse data knwon_faces = [] total = 0 for face in detect: total += 1 if not face['candidates']: continue data = face['candidates'][0] name = '' for s_name, s_id in self._api.store[self._face_group].items(): if data['personId'] == s_id: name = s_name break knwon_faces.append({ ATTR_NAME: name, ATTR_CONFIDENCE: data['confidence'] * 100, }) self.async_process_faces(knwon_faces, total)
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function import sys import warnings from functools import reduce from threading import RLock if sys.version >= '3': basestring = unicode = str xrange = range else: from itertools import izip as zip, imap as map from pyspark import since from pyspark.rdd import RDD, ignore_unicode_prefix from pyspark.sql.catalog import Catalog from pyspark.sql.conf import RuntimeConfig from pyspark.sql.dataframe import DataFrame from pyspark.sql.readwriter import DataFrameReader from pyspark.sql.streaming import DataStreamReader from pyspark.sql.types import Row, DataType, StringType, StructType, TimestampType, \ _make_type_verifier, _infer_schema, _has_nulltype, _merge_type, _create_converter, \ _parse_datatype_string from pyspark.sql.utils import install_exception_handler __all__ = ["SparkSession"] def _monkey_patch_RDD(sparkSession): def toDF(self, schema=None, sampleRatio=None): """ Converts current :class:`RDD` into a :class:`DataFrame` This is a shorthand for ``spark.createDataFrame(rdd, schema, sampleRatio)`` :param schema: a :class:`pyspark.sql.types.StructType` or list of names of columns :param samplingRatio: the sample ratio of rows used for inferring :return: a DataFrame >>> rdd.toDF().collect() [Row(name=u'Alice', age=1)] """ return sparkSession.createDataFrame(self, schema, sampleRatio) RDD.toDF = toDF class SparkSession(object): """The entry point to programming Spark with the Dataset and DataFrame API. A SparkSession can be used create :class:`DataFrame`, register :class:`DataFrame` as tables, execute SQL over tables, cache tables, and read parquet files. To create a SparkSession, use the following builder pattern: >>> spark = SparkSession.builder \\ ... .master("local") \\ ... .appName("Word Count") \\ ... .config("spark.some.config.option", "some-value") \\ ... .getOrCreate() .. autoattribute:: builder :annotation: """ class Builder(object): """Builder for :class:`SparkSession`. """ _lock = RLock() _options = {} @since(2.0) def config(self, key=None, value=None, conf=None): """Sets a config option. Options set using this method are automatically propagated to both :class:`SparkConf` and :class:`SparkSession`'s own configuration. For an existing SparkConf, use `conf` parameter. >>> from pyspark.conf import SparkConf >>> SparkSession.builder.config(conf=SparkConf()) <pyspark.sql.session... For a (key, value) pair, you can omit parameter names. >>> SparkSession.builder.config("spark.some.config.option", "some-value") <pyspark.sql.session... :param key: a key name string for configuration property :param value: a value for configuration property :param conf: an instance of :class:`SparkConf` """ with self._lock: if conf is None: self._options[key] = str(value) else: for (k, v) in conf.getAll(): self._options[k] = v return self @since(2.0) def master(self, master): """Sets the Spark master URL to connect to, such as "local" to run locally, "local[4]" to run locally with 4 cores, or "spark://master:7077" to run on a Spark standalone cluster. :param master: a url for spark master """ return self.config("spark.master", master) @since(2.0) def appName(self, name): """Sets a name for the application, which will be shown in the Spark web UI. If no application name is set, a randomly generated name will be used. :param name: an application name """ return self.config("spark.app.name", name) @since(2.0) def enableHiveSupport(self): """Enables Hive support, including connectivity to a persistent Hive metastore, support for Hive serdes, and Hive user-defined functions. """ return self.config("spark.sql.catalogImplementation", "hive") @since(2.0) def getOrCreate(self): """Gets an existing :class:`SparkSession` or, if there is no existing one, creates a new one based on the options set in this builder. This method first checks whether there is a valid global default SparkSession, and if yes, return that one. If no valid global default SparkSession exists, the method creates a new SparkSession and assigns the newly created SparkSession as the global default. >>> s1 = SparkSession.builder.config("k1", "v1").getOrCreate() >>> s1.conf.get("k1") == s1.sparkContext.getConf().get("k1") == "v1" True In case an existing SparkSession is returned, the config options specified in this builder will be applied to the existing SparkSession. >>> s2 = SparkSession.builder.config("k2", "v2").getOrCreate() >>> s1.conf.get("k1") == s2.conf.get("k1") True >>> s1.conf.get("k2") == s2.conf.get("k2") True """ with self._lock: from pyspark.context import SparkContext from pyspark.conf import SparkConf session = SparkSession._instantiatedSession if session is None or session._sc._jsc is None: sparkConf = SparkConf() for key, value in self._options.items(): sparkConf.set(key, value) sc = SparkContext.getOrCreate(sparkConf) # This SparkContext may be an existing one. for key, value in self._options.items(): # we need to propagate the confs # before we create the SparkSession. Otherwise, confs like # warehouse path and metastore url will not be set correctly ( # these confs cannot be changed once the SparkSession is created). sc._conf.set(key, value) session = SparkSession(sc) for key, value in self._options.items(): session._jsparkSession.sessionState().conf().setConfString(key, value) for key, value in self._options.items(): session.sparkContext._conf.set(key, value) return session builder = Builder() """A class attribute having a :class:`Builder` to construct :class:`SparkSession` instances""" _instantiatedSession = None @ignore_unicode_prefix def __init__(self, sparkContext, jsparkSession=None): """Creates a new SparkSession. >>> from datetime import datetime >>> spark = SparkSession(sc) >>> allTypes = sc.parallelize([Row(i=1, s="string", d=1.0, l=1, ... b=True, list=[1, 2, 3], dict={"s": 0}, row=Row(a=1), ... time=datetime(2014, 8, 1, 14, 1, 5))]) >>> df = allTypes.toDF() >>> df.createOrReplaceTempView("allTypes") >>> spark.sql('select i+1, d+1, not b, list[1], dict["s"], time, row.a ' ... 'from allTypes where b and i > 0').collect() [Row((i + CAST(1 AS BIGINT))=2, (d + CAST(1 AS DOUBLE))=2.0, (NOT b)=False, list[1]=2, \ dict[s]=0, time=datetime.datetime(2014, 8, 1, 14, 1, 5), a=1)] >>> df.rdd.map(lambda x: (x.i, x.s, x.d, x.l, x.b, x.time, x.row.a, x.list)).collect() [(1, u'string', 1.0, 1, True, datetime.datetime(2014, 8, 1, 14, 1, 5), 1, [1, 2, 3])] """ from pyspark.sql.context import SQLContext self._sc = sparkContext self._jsc = self._sc._jsc self._jvm = self._sc._jvm if jsparkSession is None: jsparkSession = self._jvm.SparkSession(self._jsc.sc()) self._jsparkSession = jsparkSession self._jwrapped = self._jsparkSession.sqlContext() self._wrapped = SQLContext(self._sc, self, self._jwrapped) _monkey_patch_RDD(self) install_exception_handler() # If we had an instantiated SparkSession attached with a SparkContext # which is stopped now, we need to renew the instantiated SparkSession. # Otherwise, we will use invalid SparkSession when we call Builder.getOrCreate. if SparkSession._instantiatedSession is None \ or SparkSession._instantiatedSession._sc._jsc is None: SparkSession._instantiatedSession = self def _repr_html_(self): return """ <div> <p><b>SparkSession - {catalogImplementation}</b></p> {sc_HTML} </div> """.format( catalogImplementation=self.conf.get("spark.sql.catalogImplementation"), sc_HTML=self.sparkContext._repr_html_() ) @since(2.0) def newSession(self): """ Returns a new SparkSession as new session, that has separate SQLConf, registered temporary views and UDFs, but shared SparkContext and table cache. """ return self.__class__(self._sc, self._jsparkSession.newSession()) @property @since(2.0) def sparkContext(self): """Returns the underlying :class:`SparkContext`.""" return self._sc @property @since(2.0) def version(self): """The version of Spark on which this application is running.""" return self._jsparkSession.version() @property @since(2.0) def conf(self): """Runtime configuration interface for Spark. This is the interface through which the user can get and set all Spark and Hadoop configurations that are relevant to Spark SQL. When getting the value of a config, this defaults to the value set in the underlying :class:`SparkContext`, if any. """ if not hasattr(self, "_conf"): self._conf = RuntimeConfig(self._jsparkSession.conf()) return self._conf @property @since(2.0) def catalog(self): """Interface through which the user may create, drop, alter or query underlying databases, tables, functions etc. :return: :class:`Catalog` """ if not hasattr(self, "_catalog"): self._catalog = Catalog(self) return self._catalog @property @since(2.0) def udf(self): """Returns a :class:`UDFRegistration` for UDF registration. :return: :class:`UDFRegistration` """ from pyspark.sql.context import UDFRegistration return UDFRegistration(self._wrapped) @since(2.0) def range(self, start, end=None, step=1, numPartitions=None): """ Create a :class:`DataFrame` with single :class:`pyspark.sql.types.LongType` column named ``id``, containing elements in a range from ``start`` to ``end`` (exclusive) with step value ``step``. :param start: the start value :param end: the end value (exclusive) :param step: the incremental step (default: 1) :param numPartitions: the number of partitions of the DataFrame :return: :class:`DataFrame` >>> spark.range(1, 7, 2).collect() [Row(id=1), Row(id=3), Row(id=5)] If only one argument is specified, it will be used as the end value. >>> spark.range(3).collect() [Row(id=0), Row(id=1), Row(id=2)] """ if numPartitions is None: numPartitions = self._sc.defaultParallelism if end is None: jdf = self._jsparkSession.range(0, int(start), int(step), int(numPartitions)) else: jdf = self._jsparkSession.range(int(start), int(end), int(step), int(numPartitions)) return DataFrame(jdf, self._wrapped) def _inferSchemaFromList(self, data): """ Infer schema from list of Row or tuple. :param data: list of Row or tuple :return: :class:`pyspark.sql.types.StructType` """ if not data: raise ValueError("can not infer schema from empty dataset") first = data[0] if type(first) is dict: warnings.warn("inferring schema from dict is deprecated," "please use pyspark.sql.Row instead") schema = reduce(_merge_type, map(_infer_schema, data)) if _has_nulltype(schema): raise ValueError("Some of types cannot be determined after inferring") return schema def _inferSchema(self, rdd, samplingRatio=None): """ Infer schema from an RDD of Row or tuple. :param rdd: an RDD of Row or tuple :param samplingRatio: sampling ratio, or no sampling (default) :return: :class:`pyspark.sql.types.StructType` """ first = rdd.first() if not first: raise ValueError("The first row in RDD is empty, " "can not infer schema") if type(first) is dict: warnings.warn("Using RDD of dict to inferSchema is deprecated. " "Use pyspark.sql.Row instead") if samplingRatio is None: schema = _infer_schema(first) if _has_nulltype(schema): for row in rdd.take(100)[1:]: schema = _merge_type(schema, _infer_schema(row)) if not _has_nulltype(schema): break else: raise ValueError("Some of types cannot be determined by the " "first 100 rows, please try again with sampling") else: if samplingRatio < 0.99: rdd = rdd.sample(False, float(samplingRatio)) schema = rdd.map(_infer_schema).reduce(_merge_type) return schema def _createFromRDD(self, rdd, schema, samplingRatio): """ Create an RDD for DataFrame from an existing RDD, returns the RDD and schema. """ if schema is None or isinstance(schema, (list, tuple)): struct = self._inferSchema(rdd, samplingRatio) converter = _create_converter(struct) rdd = rdd.map(converter) if isinstance(schema, (list, tuple)): for i, name in enumerate(schema): struct.fields[i].name = name struct.names[i] = name schema = struct elif not isinstance(schema, StructType): raise TypeError("schema should be StructType or list or None, but got: %s" % schema) # convert python objects to sql data rdd = rdd.map(schema.toInternal) return rdd, schema def _createFromLocal(self, data, schema): """ Create an RDD for DataFrame from a list or pandas.DataFrame, returns the RDD and schema. """ # make sure data could consumed multiple times if not isinstance(data, list): data = list(data) if schema is None or isinstance(schema, (list, tuple)): struct = self._inferSchemaFromList(data) converter = _create_converter(struct) data = map(converter, data) if isinstance(schema, (list, tuple)): for i, name in enumerate(schema): struct.fields[i].name = name struct.names[i] = name schema = struct elif not isinstance(schema, StructType): raise TypeError("schema should be StructType or list or None, but got: %s" % schema) # convert python objects to sql data data = [schema.toInternal(row) for row in data] return self._sc.parallelize(data), schema def _get_numpy_record_dtype(self, rec): """ Used when converting a pandas.DataFrame to Spark using to_records(), this will correct the dtypes of fields in a record so they can be properly loaded into Spark. :param rec: a numpy record to check field dtypes :return corrected dtype for a numpy.record or None if no correction needed """ import numpy as np cur_dtypes = rec.dtype col_names = cur_dtypes.names record_type_list = [] has_rec_fix = False for i in xrange(len(cur_dtypes)): curr_type = cur_dtypes[i] # If type is a datetime64 timestamp, convert to microseconds # NOTE: if dtype is datetime[ns] then np.record.tolist() will output values as longs, # conversion from [us] or lower will lead to py datetime objects, see SPARK-22417 if curr_type == np.dtype('datetime64[ns]'): curr_type = 'datetime64[us]' has_rec_fix = True record_type_list.append((str(col_names[i]), curr_type)) return np.dtype(record_type_list) if has_rec_fix else None def _convert_from_pandas(self, pdf, schema, timezone): """ Convert a pandas.DataFrame to list of records that can be used to make a DataFrame :return list of records """ if timezone is not None: from pyspark.sql.types import _check_series_convert_timestamps_tz_local copied = False if isinstance(schema, StructType): for field in schema: # TODO: handle nested timestamps, such as ArrayType(TimestampType())? if isinstance(field.dataType, TimestampType): s = _check_series_convert_timestamps_tz_local(pdf[field.name], timezone) if not copied and s is not pdf[field.name]: # Copy once if the series is modified to prevent the original Pandas # DataFrame from being updated pdf = pdf.copy() copied = True pdf[field.name] = s else: for column, series in pdf.iteritems(): s = _check_series_convert_timestamps_tz_local(pdf[column], timezone) if not copied and s is not pdf[column]: # Copy once if the series is modified to prevent the original Pandas # DataFrame from being updated pdf = pdf.copy() copied = True pdf[column] = s # Convert pandas.DataFrame to list of numpy records np_records = pdf.to_records(index=False) # Check if any columns need to be fixed for Spark to infer properly if len(np_records) > 0: record_dtype = self._get_numpy_record_dtype(np_records[0]) if record_dtype is not None: return [r.astype(record_dtype).tolist() for r in np_records] # Convert list of numpy records to python lists return [r.tolist() for r in np_records] def _create_from_pandas_with_arrow(self, pdf, schema, timezone): """ Create a DataFrame from a given pandas.DataFrame by slicing it into partitions, converting to Arrow data, then sending to the JVM to parallelize. If a schema is passed in, the data types will be used to coerce the data in Pandas to Arrow conversion. """ from pyspark.serializers import ArrowSerializer, _create_batch from pyspark.sql.types import from_arrow_schema, to_arrow_type, TimestampType from pyspark.sql.utils import require_minimum_pandas_version, \ require_minimum_pyarrow_version require_minimum_pandas_version() require_minimum_pyarrow_version() from pandas.api.types import is_datetime64_dtype, is_datetime64tz_dtype # Determine arrow types to coerce data when creating batches if isinstance(schema, StructType): arrow_types = [to_arrow_type(f.dataType) for f in schema.fields] elif isinstance(schema, DataType): raise ValueError("Single data type %s is not supported with Arrow" % str(schema)) else: # Any timestamps must be coerced to be compatible with Spark arrow_types = [to_arrow_type(TimestampType()) if is_datetime64_dtype(t) or is_datetime64tz_dtype(t) else None for t in pdf.dtypes] # Slice the DataFrame to be batched step = -(-len(pdf) // self.sparkContext.defaultParallelism) # round int up pdf_slices = (pdf[start:start + step] for start in xrange(0, len(pdf), step)) # Create Arrow record batches batches = [_create_batch([(c, t) for (_, c), t in zip(pdf_slice.iteritems(), arrow_types)], timezone) for pdf_slice in pdf_slices] # Create the Spark schema from the first Arrow batch (always at least 1 batch after slicing) if isinstance(schema, (list, tuple)): struct = from_arrow_schema(batches[0].schema) for i, name in enumerate(schema): struct.fields[i].name = name struct.names[i] = name schema = struct # Create the Spark DataFrame directly from the Arrow data and schema jrdd = self._sc._serialize_to_jvm(batches, len(batches), ArrowSerializer()) jdf = self._jvm.PythonSQLUtils.arrowPayloadToDataFrame( jrdd, schema.json(), self._wrapped._jsqlContext) df = DataFrame(jdf, self._wrapped) df._schema = schema return df @since(2.0) @ignore_unicode_prefix def createDataFrame(self, data, schema=None, samplingRatio=None, verifySchema=True): """ Creates a :class:`DataFrame` from an :class:`RDD`, a list or a :class:`pandas.DataFrame`. When ``schema`` is a list of column names, the type of each column will be inferred from ``data``. When ``schema`` is ``None``, it will try to infer the schema (column names and types) from ``data``, which should be an RDD of :class:`Row`, or :class:`namedtuple`, or :class:`dict`. When ``schema`` is :class:`pyspark.sql.types.DataType` or a datatype string, it must match the real data, or an exception will be thrown at runtime. If the given schema is not :class:`pyspark.sql.types.StructType`, it will be wrapped into a :class:`pyspark.sql.types.StructType` as its only field, and the field name will be "value", each record will also be wrapped into a tuple, which can be converted to row later. If schema inference is needed, ``samplingRatio`` is used to determined the ratio of rows used for schema inference. The first row will be used if ``samplingRatio`` is ``None``. :param data: an RDD of any kind of SQL data representation(e.g. row, tuple, int, boolean, etc.), or :class:`list`, or :class:`pandas.DataFrame`. :param schema: a :class:`pyspark.sql.types.DataType` or a datatype string or a list of column names, default is ``None``. The data type string format equals to :class:`pyspark.sql.types.DataType.simpleString`, except that top level struct type can omit the ``struct<>`` and atomic types use ``typeName()`` as their format, e.g. use ``byte`` instead of ``tinyint`` for :class:`pyspark.sql.types.ByteType`. We can also use ``int`` as a short name for ``IntegerType``. :param samplingRatio: the sample ratio of rows used for inferring :param verifySchema: verify data types of every row against schema. :return: :class:`DataFrame` .. versionchanged:: 2.1 Added verifySchema. >>> l = [('Alice', 1)] >>> spark.createDataFrame(l).collect() [Row(_1=u'Alice', _2=1)] >>> spark.createDataFrame(l, ['name', 'age']).collect() [Row(name=u'Alice', age=1)] >>> d = [{'name': 'Alice', 'age': 1}] >>> spark.createDataFrame(d).collect() [Row(age=1, name=u'Alice')] >>> rdd = sc.parallelize(l) >>> spark.createDataFrame(rdd).collect() [Row(_1=u'Alice', _2=1)] >>> df = spark.createDataFrame(rdd, ['name', 'age']) >>> df.collect() [Row(name=u'Alice', age=1)] >>> from pyspark.sql import Row >>> Person = Row('name', 'age') >>> person = rdd.map(lambda r: Person(*r)) >>> df2 = spark.createDataFrame(person) >>> df2.collect() [Row(name=u'Alice', age=1)] >>> from pyspark.sql.types import * >>> schema = StructType([ ... StructField("name", StringType(), True), ... StructField("age", IntegerType(), True)]) >>> df3 = spark.createDataFrame(rdd, schema) >>> df3.collect() [Row(name=u'Alice', age=1)] >>> spark.createDataFrame(df.toPandas()).collect() # doctest: +SKIP [Row(name=u'Alice', age=1)] >>> spark.createDataFrame(pandas.DataFrame([[1, 2]])).collect() # doctest: +SKIP [Row(0=1, 1=2)] >>> spark.createDataFrame(rdd, "a: string, b: int").collect() [Row(a=u'Alice', b=1)] >>> rdd = rdd.map(lambda row: row[1]) >>> spark.createDataFrame(rdd, "int").collect() [Row(value=1)] >>> spark.createDataFrame(rdd, "boolean").collect() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... Py4JJavaError: ... """ if isinstance(data, DataFrame): raise TypeError("data is already a DataFrame") if isinstance(schema, basestring): schema = _parse_datatype_string(schema) elif isinstance(schema, (list, tuple)): # Must re-encode any unicode strings to be consistent with StructField names schema = [x.encode('utf-8') if not isinstance(x, str) else x for x in schema] try: import pandas has_pandas = True except Exception: has_pandas = False if has_pandas and isinstance(data, pandas.DataFrame): if self.conf.get("spark.sql.execution.pandas.respectSessionTimeZone").lower() \ == "true": timezone = self.conf.get("spark.sql.session.timeZone") else: timezone = None # If no schema supplied by user then get the names of columns only if schema is None: schema = [x.encode('utf-8') if not isinstance(x, str) else x for x in data.columns] if self.conf.get("spark.sql.execution.arrow.enabled", "false").lower() == "true" \ and len(data) > 0: try: return self._create_from_pandas_with_arrow(data, schema, timezone) except Exception as e: warnings.warn("Arrow will not be used in createDataFrame: %s" % str(e)) # Fallback to create DataFrame without arrow if raise some exception data = self._convert_from_pandas(data, schema, timezone) if isinstance(schema, StructType): verify_func = _make_type_verifier(schema) if verifySchema else lambda _: True def prepare(obj): verify_func(obj) return obj elif isinstance(schema, DataType): dataType = schema schema = StructType().add("value", schema) verify_func = _make_type_verifier( dataType, name="field value") if verifySchema else lambda _: True def prepare(obj): verify_func(obj) return obj, else: prepare = lambda obj: obj if isinstance(data, RDD): rdd, schema = self._createFromRDD(data.map(prepare), schema, samplingRatio) else: rdd, schema = self._createFromLocal(map(prepare, data), schema) jrdd = self._jvm.SerDeUtil.toJavaArray(rdd._to_java_object_rdd()) jdf = self._jsparkSession.applySchemaToPythonRDD(jrdd.rdd(), schema.json()) df = DataFrame(jdf, self._wrapped) df._schema = schema return df @ignore_unicode_prefix @since(2.0) def sql(self, sqlQuery): """Returns a :class:`DataFrame` representing the result of the given query. :return: :class:`DataFrame` >>> df.createOrReplaceTempView("table1") >>> df2 = spark.sql("SELECT field1 AS f1, field2 as f2 from table1") >>> df2.collect() [Row(f1=1, f2=u'row1'), Row(f1=2, f2=u'row2'), Row(f1=3, f2=u'row3')] """ return DataFrame(self._jsparkSession.sql(sqlQuery), self._wrapped) @since(2.0) def table(self, tableName): """Returns the specified table as a :class:`DataFrame`. :return: :class:`DataFrame` >>> df.createOrReplaceTempView("table1") >>> df2 = spark.table("table1") >>> sorted(df.collect()) == sorted(df2.collect()) True """ return DataFrame(self._jsparkSession.table(tableName), self._wrapped) @property @since(2.0) def read(self): """ Returns a :class:`DataFrameReader` that can be used to read data in as a :class:`DataFrame`. :return: :class:`DataFrameReader` """ return DataFrameReader(self._wrapped) @property @since(2.0) def readStream(self): """ Returns a :class:`DataStreamReader` that can be used to read data streams as a streaming :class:`DataFrame`. .. note:: Evolving. :return: :class:`DataStreamReader` """ return DataStreamReader(self._wrapped) @property @since(2.0) def streams(self): """Returns a :class:`StreamingQueryManager` that allows managing all the :class:`StreamingQuery` StreamingQueries active on `this` context. .. note:: Evolving. :return: :class:`StreamingQueryManager` """ from pyspark.sql.streaming import StreamingQueryManager return StreamingQueryManager(self._jsparkSession.streams()) @since(2.0) def stop(self): """Stop the underlying :class:`SparkContext`. """ self._sc.stop() SparkSession._instantiatedSession = None @since(2.0) def __enter__(self): """ Enable 'with SparkSession.builder.(...).getOrCreate() as session: app' syntax. """ return self @since(2.0) def __exit__(self, exc_type, exc_val, exc_tb): """ Enable 'with SparkSession.builder.(...).getOrCreate() as session: app' syntax. Specifically stop the SparkSession on exit of the with block. """ self.stop() def _test(): import os import doctest from pyspark.context import SparkContext from pyspark.sql import Row import pyspark.sql.session os.chdir(os.environ["SPARK_HOME"]) globs = pyspark.sql.session.__dict__.copy() sc = SparkContext('local[4]', 'PythonTest') globs['sc'] = sc globs['spark'] = SparkSession(sc) globs['rdd'] = rdd = sc.parallelize( [Row(field1=1, field2="row1"), Row(field1=2, field2="row2"), Row(field1=3, field2="row3")]) globs['df'] = rdd.toDF() (failure_count, test_count) = doctest.testmod( pyspark.sql.session, globs=globs, optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE) globs['sc'].stop() if failure_count: exit(-1) if __name__ == "__main__": _test()
from formencode import validators, NoDefault, Invalid, Schema, NestedVariables, ForEach, All, Any from columns.lib import rfc3339 __all__ = [ 'Invalid', 'CreateArticle', 'UpdateArticle', 'CreatePage', 'UpdatePage', 'CreateUser', 'UpdateUser', 'CreateAccount', 'UpdateAccount', 'CreateComment', 'UpdateComment', 'CreateUpload', 'UpdateUpload', 'CreateTag', ] class DateTimeValidator(validators.FancyValidator): format = "" tzinfo = None messages = {'bad_format': 'Date/Time stamp must be in the format %(format)s',} def to_python(self, value, state): import datetime import pytz UTC = pytz.timezone('UTC') EST = pytz.timezone('US/Eastern') try: if isinstance(value, basestring): value = datetime.datetime.strptime(value,self.format) dt = EST.localize(value).astimezone(UTC).replace(tzinfo=None) except ValueError: raise Invalid(self.message("bad_format", state, format=self.format), value, state) return dt def from_python(self, value, state): return value.strftime(self.format) class UniqueUserName(validators.FancyValidator): messages = {'user_name_taken': 'The name %(name)s is unavailable',} def to_python(self, value, state): from columns.model import User, meta if meta.Session.query(User).filter(User.name == value).count() > 0: raise validators.Invalid(self.message("user_name_taken",state,name=value),value,state) return value class StringListValidator(validators.FancyValidator): messages = {'bad_string': 'Value %(value)s is not a valid string',} def to_python(self, value, state): try: return [unicode(x.strip()) for x in value.split(",") if x.strip() != ""] except (TypeError, ValueError, AttributeError): raise Invalid(self.message("bad_string", state, value=str(value)), value, state) def from_python(self, value, state): return unicode(", ".join(value)) class HTMLValidator(validators.UnicodeString): def to_python(self, value, state): try: from lxml import etree soup = etree.fromstring("<div>%s</div>"%value) return etree.tostring(soup, encoding=unicode)[5:-6] except: from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(value) return unicode(soup) class CreateArticle(Schema): allow_extra_fields = True title = validators.UnicodeString(max=255, strip=True, not_empty=True) page_id = validators.Int(if_empty=None) can_comment = validators.StringBool(if_missing=False) sticky = validators.StringBool(if_missing=False) published = DateTimeValidator(format=rfc3339.RFC3339_wo_Timezone, if_empty=None) content = HTMLValidator() tags = StringListValidator() class UpdateArticle(CreateArticle): allow_extra_fields = True filter_extra_fields = True class CreatePage(Schema): allow_extra_fields = True filter_extra_fields = True title = validators.UnicodeString(max=255, strip=True, not_empty=True) can_post = validators.StringBool(if_missing=False) content = HTMLValidator(if_empty=u'') template = validators.UnicodeString(if_empty=u'/blog/blank') visible = validators.StringBool(if_missing=False) in_main = validators.StringBool(if_missing=False) in_menu = validators.StringBool(if_missing=False) stream_comment_style = validators.UnicodeString(max=20, strip=True) story_comment_style = validators.UnicodeString(max=20, strip=True) class UpdatePage(CreatePage): allow_extra_fields = True filter_extra_fields = True class CreateUser(Schema): allow_extra_fields = True filter_extra_fields = True name = validators.UnicodeString(max=255, strip=True, not_empty=True) open_id = validators.UnicodeString(max=255, if_empty=None, strip=True) fb_id = validators.UnicodeString(max=255, if_empty=None, strip=True) twitter_id = validators.UnicodeString(max=255, if_empty=None, strip=True) profile = validators.URL(add_http=True, max=255, strip=True, if_empty=None) type = validators.Int() class UpdateUser(CreateUser): allow_extra_fields = True filter_extra_fields = True class CreateAccount(Schema): allow_extra_fields = True filter_extra_fields = True name = validators.UnicodeString(max=255, strip=True, not_empty=True) profile = validators.URL(add_http=True, max=255, strip=True, if_empty=None) class UpdateAccount(Schema): allow_extra_fields = True filter_extra_fields = True profile = validators.URL(add_http=True, max=255, strip=True, if_empty=None) class CreateTag(Schema): allow_extra_fields = True filter_extra_fields = True label = validators.UnicodeString(max=255, strip=True) class UpdateTag(CreateTag): allow_extra_fields = True filter_extra_fields = True class CreateComment(Schema): allow_extra_fields = True filter_extra_fields = True parent = validators.Int(if_missing=None, if_empty=None) title = validators.UnicodeString(max=255, if_empty='No Subject', strip=True) content = validators.UnicodeString() class UpdateComment(CreateComment): allow_extra_fields = True filter_extra_fields = True class CreateUpload(Schema): allow_extra_fields = True filter_extra_fields = True upload = validators.FieldStorageUploadConverter() title = validators.UnicodeString(max=255, strip=True) content = validators.UnicodeString(if_empty=None, if_missing=u'', strip=True) tags = StringListValidator(if_missing=[]) class UpdateUpload(Schema): allow_extra_fields = True filter_extra_fields = True title = validators.UnicodeString(max=255, strip=True) content = validators.UnicodeString(if_empty=None, if_missing=u'', strip=True) tags = StringListValidator(if_missing=[]) class CreateSetting(Schema): pre_validators = [NestedVariables()] allow_extra_fields = True filter_extra_fields = True module = validators.UnicodeString(max=255, strip=True) values = NestedVariables() class UpdateSetting(CreateSetting): pre_validators = [NestedVariables()] allow_extra_fields = True filter_extra_fields = True values = NestedVariables() class LoginForm(Schema): allow_extra_fields = True filter_extra_fields = True auth_type = validators.UnicodeString(max=255) auth_id = validators.UnicodeString(max=255, if_empty=None, if_missing=None) class UpdateProfile(Schema): allow_extra_fields = True filter_extra_fields = True profile = validators.URL(add_http=True, max=255, strip=True, if_empty=None) class SaveQuickUser(Schema): allow_extra_fields = True filter_extra_fields = True name = All(validators.UnicodeString(max=255,min=3,strip=True),UniqueUserName()) profile = validators.URL(add_http=True, max=255, strip=True, if_empty=None) class Delete(Schema): allow_extra_fields = True filter_extra_fields = True obj_type = validators.UnicodeString(max=255) id = validators.Int(max=255)
import logging import os.path from ibmsecurity.utilities.tools import files_same, get_random_temp_dir import shutil logger = logging.getLogger(__name__) def get_all(isamAppliance, kdb_id, check_mode=False, force=False): """ Retrieving signer certificate names and details in a certificate database """ return isamAppliance.invoke_get("Retrieving signer certificate names and details in a certificate database", "/isam/ssl_certificates/{0}/signer_cert".format(kdb_id)) def get(isamAppliance, kdb_id, cert_id, check_mode=False, force=False): """ Retrieving a signer certificate from a certificate database """ return isamAppliance.invoke_get("Retrieving a signer certificate from a certificate database", "/isam/ssl_certificates/{0}/signer_cert/{1}".format(kdb_id, cert_id)) def load(isamAppliance, kdb_id, label, server, port, check_remote=False, check_mode=False, force=False): """ Load a certificate from a server check_remote controls if ansible should check remote certificate by retrieving it or simply by checking for existence of the label in the kdb """ if check_remote: logger.debug("Compare remote certificate with the one on the appliance. Use check_remote=False to switch to simple label checking.") tmp_check = _check_load(isamAppliance, kdb_id, label, server, port) else: logger.debug("Check for existence of the label in the kdb. Use check_remote=True to switch to advanced remote certificate with appliance certificate checking.") tmp_check = _check(isamAppliance, kdb_id, label) if force is True or tmp_check is False: if check_mode is True: return isamAppliance.create_return_object(changed=True) else: return isamAppliance.invoke_post( "Load a certificate from a server", "/isam/ssl_certificates/{0}/signer_cert".format(kdb_id), { "operation": 'load', "label": label, "server": server, "port": port }) return isamAppliance.create_return_object() def _check_expired(notafter_epoch): """ Can be used to check for expired certs Returns True if expired, False otherwise """ import time epoch_time = int(time.time()) cert_epoch = int(notafter_epoch) return cert_epoch < epoch_time def _check_load(isamAppliance, kdb_id, label, server, port): """ Checks if certificate to be loaded on the Appliance exists and if so, whether it is different from the one on the remote host. If the certificate exists on the Appliance, but has a different label, we return True, so that load() takes no action. If the requested label matches an existing label on the appliance, but the certs are different, check to see if cert is expired. If so, replace cert. If not, do not replace. """ import ssl remote_cert_pem = ssl.get_server_certificate((server, port)) # Look for remote_cert_pem on in the signer certs on the appliance ret_obj = get_all(isamAppliance, kdb_id) for cert_data in ret_obj['data']: cert_id = cert_data['id'] cert_pem = get(isamAppliance, kdb_id, cert_id)['data']['contents'] if cert_id == label: # label exists on appliance already logger.debug("Comparing certificates: appliance[{0}] remote[{1}].".format(cert_pem,remote_cert_pem)) if cert_pem == remote_cert_pem: # certificate data is the same logger.debug("The certificate already exits on the appliance with the same label name and same content.") return True # both the labels and certificates match else: # Labels match, but the certs are different, so we need to update it. # However, you cannot load a cert with the same label name onto the appliance, since you get # CTGSK2021W A duplicate certificate already exists in the database. # We delete the cert from the appliance and return False to the load() function, # so that we can load the new one ret_obj = delete(isamAppliance, kdb_id, cert_id) logger.debug("Labels match, but the certs are different, so we need to update it.") return False else: if cert_pem == remote_cert_pem: # cert on the appliance, but with a different name logger.info( "The certifcate is already on the appliance, but it has a different label name. " "The existing label name is {label} and requested label name is {cert_id}".format( label=label, cert_id=cert_id)) return True return False def delete(isamAppliance, kdb_id, cert_id, check_mode=False, force=False): """ Deleting a signer certificate from a certificate database """ if force is True or _check(isamAppliance, kdb_id, cert_id) is True: if check_mode is True: return isamAppliance.create_return_object(changed=True) else: try: # Assume Python3 and import package from urllib.parse import quote except ImportError: # Now try to import Python2 package from urllib import quote # URL being encoded primarily to handle spaces and other special characers in them f_uri = "/isam/ssl_certificates/{0}/signer_cert/{1}".format(kdb_id, cert_id) full_uri = quote(f_uri) return isamAppliance.invoke_delete( "Deleting a signer certificate from a certificate database", full_uri) return isamAppliance.create_return_object() def export_cert(isamAppliance, kdb_id, cert_id, filename, check_mode=False, force=False): """ Exporting a signer certificate from a certificate database """ import os.path if force is True or _check(isamAppliance, kdb_id, cert_id) is True: if check_mode is False: # No point downloading a file if in check_mode return isamAppliance.invoke_get_file( "Export a certificate database", "/isam/ssl_certificates/{0}/signer_cert/{1}?export".format(kdb_id, cert_id), filename) return isamAppliance.create_return_object() def import_cert(isamAppliance, kdb_id, cert, label, check_mode=False, force=False): """ Importing a signer certificate into a certificate database """ if force is True or _check_import(isamAppliance, kdb_id, label, cert, check_mode=check_mode): if check_mode is True: return isamAppliance.create_return_object(changed=True) else: return isamAppliance.invoke_post_files( "Importing a signer certificate into a certificate database", "/isam/ssl_certificates/{0}/signer_cert".format(kdb_id), [ { 'file_formfield': 'cert', 'filename': cert, 'mimetype': 'application/octet-stream' } ], {'label': label}) return isamAppliance.create_return_object() def _check(isamAppliance, kdb_id, cert_id): """ Check if signer certificate already exists in certificate database """ ret_obj = get_all(isamAppliance, kdb_id) for certdb in ret_obj['data']: if certdb['id'] == cert_id: return True return False def _check_import(isamAppliance, kdb_id, cert_id, filename, check_mode=False): """ Checks if certificate on the Appliance exists and if so, whether it is different from the one stored in filename """ tmpdir = get_random_temp_dir() orig_filename = '%s.cer' % cert_id tmp_original_file = os.path.join(tmpdir, os.path.basename(orig_filename)) if _check(isamAppliance, kdb_id, cert_id): export_cert(isamAppliance, kdb_id, cert_id, tmp_original_file, check_mode=False, force=True) logger.debug("file already exists on appliance") if files_same(tmp_original_file, filename): logger.debug("files are the same, so we don't want to do anything") shutil.rmtree(tmpdir) return False else: logger.debug("files are different, so we delete existing file in preparation for import") delete(isamAppliance, kdb_id, cert_id, check_mode=check_mode, force=True) shutil.rmtree(tmpdir) return True else: logger.debug("file does not exist on appliance, so we'll want to import") shutil.rmtree(tmpdir) return True def compare(isamAppliance1, isamAppliance2, kdb_id): """ Compare signer certificates in certificate database between two appliances """ ret_obj1 = get_all(isamAppliance1, kdb_id) ret_obj2 = get_all(isamAppliance2, kdb_id) import ibmsecurity.utilities.tools return ibmsecurity.utilities.tools.json_compare(ret_obj1, ret_obj2, deleted_keys=[])
from __future__ import absolute_import from collections import defaultdict import math import os import os.path from blessings import Terminal term = Terminal() import gevent import gevent.pool import tabulate from . import RepoConfigParser from .git import git from .base_git import NoSuchRemote class GitRepository(object): def __init__(self, name, path, remote_name, remote_url, remote_branch): self.name = name self.path = path self.remote_name = remote_name self.remote_url = remote_url self.remote_branch = remote_branch def repository_exists(self): return os.path.exists( os.path.join(self.path, '.git') ) def update_remote(self, dry_run): try: url = git.get_remote_url(self.path, self.remote_name) except NoSuchRemote: if dry_run: print(term.red( 'Would add remote %s for %s.' % ( self.remote_name, self.path ) )) return False git.add_remote(self.path, self.remote_name, self.remote_url) url = self.remote_url if url.strip() != self.remote_url.strip(): if dry_run: print(term.red( 'Remote url for %s is incorrect, will update it.' % self.name )) return False git.set_remote_url(self.path, self.remote_name, self.remote_url) return True def fast_foward(self, dry_run): if not self.repository_exists(): return local_change_count = self.local_change_count() remote_change_count = self.remote_change_count() if remote_change_count: print(term.cyan('Attempting to fastforward %s.' % self.name)) if remote_change_count or local_change_count: print( 'Branch has %s more commits and %s less commits ' 'than %s/%s' % ( local_change_count, remote_change_count, self.remote_name, self.remote_branch ) ) on_branch = git.is_on_branch(self.path) if remote_change_count and not local_change_count and on_branch: if dry_run: print(term.red('Would attempt to fastforward %s.' % self.name)) return print(term.green("Fast forwarding repository...")) git.fast_forward(self.path, self.remote_name, self.remote_branch) elif remote_change_count and not on_branch: print(term.red( "Unable to fastforward. Checkout a branch first." )) elif remote_change_count: print(term.red( 'Not fastforwarding %s. Branch has %s local changes.' % (self.name, local_change_count) )) def clone_repository(self): print(term.green('Cloning repository %s ...' % self.name)) return git.clone(self.path, self.remote_url, self.remote_branch, remote_name=self.remote_name) def fetch(self, dry_run): print(term.cyan('Fetching repository %s ...' % self.name)) if self.repository_exists(): if not self.update_remote(dry_run): return False if not git.fetch_remote(self.path, self.remote_name): print(term.red("Unable to fetch %s in %s." % (self.remote_name, self.path))) return False return True else: return self.clone_repository() def local_change_count(self): local_change_count = git.count_different_commits( self.path, '%s/%s' % (self.remote_name, self.remote_branch), 'HEAD' ) return local_change_count def remote_change_count(self): remote_change_count = git.count_different_commits( self.path, 'HEAD', '%s/%s' % (self.remote_name, self.remote_branch) ) return remote_change_count def update_or_clone(self, dry_run): if self.repository_exists(): self.update_repository(dry_run) else: if dry_run: print(term.red( "Repo %s doesn't exist, will create it." % self.name )) return if not self.clone_repository(): print(term.red( "Unable to clone %s with remote %s." % ( self.path, self.remote_name ) )) def status(self): local_change_count = self.local_change_count() remote_change_count = self.remote_change_count() branch = git.get_current_branch(self.path) return { 'branch': branch, 'local_change_count': local_change_count, 'remote_change_count': remote_change_count, } def push(self): current_branch = git.get_proper_current_branch(self.path) git.push(self.path, self.remote_name, current_branch, current_branch) def start(self, branch): current_branch, branches = git.list_branches(self.path) if branch not in branches: git.start_new_branch( self.path, branch, self.remote_name, self.remote_branch ) else: print(term.red( "Branch %s already exists in %s." % (branch, self.name) )) def set_git_config(self, config): for field, value in config: if git.config_get(self.path, field) != value: git.config_set(self.path, field, value) class GitRepositoryHandler(object): def __init__(self, dry_run): self.dry_run = dry_run self.config = RepoConfigParser.JsonConfigParser() self.config.find_config_file(os.getcwd()) self.configure() def configure(self): config = self.config config.parse_file() remotes = config.remotes self.repositories = {} self.repo_groups = defaultdict(list) # Determine the default remote default_remote_name = None for name, settings in remotes.items(): if settings.get('default', False): default_remote_name = name break else: if len(remotes) == 1: default_remote_name = list(remotes.keys())[0] # Load the repositories for path, repo_details in config.repositories.items(): remote_name = repo_details.get('remote', default_remote_name) if not remote_name: raise ValueError( 'Repo %s has no remote set, and there is no' 'valid default remote!' % path ) if remote_name in config.remotes: remote = config.remotes[remote_name] remote_url = remote['url'] + repo_details['name'] remote_branch = repo_details.get('branch', remote['branch']) else: remote_url = remote_name remote_branch = repo_details.get('branch', 'master') remote_name = 'origin' repo_group = repo_details.get('group') repo = GitRepository( name=path, path=os.path.realpath( os.path.join(config.working_directory, path) ), remote_name=remote_name, remote_url=remote_url, remote_branch=remote_branch, ) self.repositories[path] = repo self.repo_groups[repo_group].append(repo) self.enabled_groups = {None} | config.enabled_groups self.git_config = config.git_config def _repository_iter(self): for group in self.enabled_groups: for repo in self.repo_groups[group]: yield repo def fetch_polygamy_repo(self): if not os.path.exists(os.path.join( self.config.config_dir, 'polygamy', '.git' )): return print('Updating polygamy repository...') try: git.pull(os.path.join( self.config.config_dir, 'polygamy' )) except: print(term.red('Unable to update polygamy repository.')) self.configure() def update_repositories(self): self.fetch() for repo in self._repository_iter(): repo.set_git_config(self.git_config) repo.fast_foward(self.dry_run) def fetch(self): pool = gevent.pool.Pool(size=6) for repo in self._repository_iter(): pool.apply_async(repo.fetch, [self.dry_run]) pool.join() def list(self, seperator, local_changes_only): repo_names = [] for repo in self._repository_iter(): change_count = repo.local_change_count() if not local_changes_only or (change_count and not math.isnan(change_count)): repo_names.append(repo.name) print(seperator.join(repo_names)) def status(self): statuses = [] for repo in sorted(self._repository_iter(), key=lambda r: r.name): status = repo.status() statuses.append([ repo.name, status['branch'], status['local_change_count'], status['remote_change_count'] ]) print(tabulate.tabulate( statuses, headers=['Repo', 'Branch', 'Local Changes', 'Remote Changes'], tablefmt='simple' )) def push(self, repositories): for repository in repositories: self.repositories[repository].push() def groups(self): for group in sorted(self.repo_groups.keys()): if group is None: continue enabled = u'\u2714' if group in self.enabled_groups else ' ' print('[%s] %s' % (enabled, group)) def enable_groups(self, groups): self.config.enabled_groups |= set(groups) self.config.save_preferences() def disable_groups(self, groups): self.config.enabled_groups -= set(groups) self.config.save_preferences() def start(self, branch_name, repositories): for repo in repositories: self.repositories[repo].start(branch_name) def add_repository(self, repository_url, path, group, branch): repo = { 'remote': repository_url, 'branch': branch if branch else 'master' } if group is not None: repo['group'] = group self.config.repositories[path] = repo self.config.save_config_file()
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Tests for Google Cloud Build Hook """ import unittest from typing import Optional from unittest import mock from mock import PropertyMock from airflow import AirflowException from airflow.providers.google.cloud.hooks.cloud_build import CloudBuildHook from tests.providers.google.cloud.utils.base_gcp_mock import ( GCP_PROJECT_ID_HOOK_UNIT_TEST, mock_base_gcp_hook_default_project_id, mock_base_gcp_hook_no_default_project_id, ) TEST_CREATE_BODY = { "source": {"storageSource": {"bucket": "cloud-build-examples", "object": "node-docker-example.tar.gz"}}, "steps": [ {"name": "gcr.io/cloud-builders/docker", "args": ["build", "-t", "gcr.io/$PROJECT_ID/my-image", "."]} ], "images": ["gcr.io/$PROJECT_ID/my-image"], } TEST_BUILD = {"name": "build-name", "metadata": {"build": {"id": "AAA"}}} TEST_WAITING_OPERATION = {"done": False, "response": "response"} TEST_DONE_OPERATION = {"done": True, "response": "response"} TEST_ERROR_OPERATION = {"done": True, "response": "response", "error": "error"} TEST_PROJECT_ID = "cloud-build-project-id" class TestCloudBuildHookWithPassedProjectId(unittest.TestCase): hook = None # type: Optional[CloudBuildHook] def setUp(self): with mock.patch( "airflow.providers.google.cloud.hooks.base.CloudBaseHook.__init__", new=mock_base_gcp_hook_default_project_id, ): self.hook = CloudBuildHook(gcp_conn_id="test") @mock.patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook._authorize") @mock.patch("airflow.providers.google.cloud.hooks.cloud_build.build") def test_cloud_build_client_creation(self, mock_build, mock_authorize): result = self.hook.get_conn() mock_build.assert_called_once_with( 'cloudbuild', 'v1', http=mock_authorize.return_value, cache_discovery=False ) self.assertEqual(mock_build.return_value, result) self.assertEqual(self.hook._conn, result) @mock.patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook.get_conn") def test_build_immediately_complete(self, get_conn_mock): service_mock = get_conn_mock.return_value service_mock.projects.return_value\ .builds.return_value\ .create.return_value\ .execute.return_value = TEST_BUILD service_mock.projects.return_value.\ builds.return_value.\ get.return_value.\ execute.return_value = TEST_BUILD service_mock.operations.return_value.\ get.return_value.\ execute.return_value = TEST_DONE_OPERATION result = self.hook.create_build(body={}, project_id=TEST_PROJECT_ID) service_mock.projects.return_value.builds.return_value.create.assert_called_once_with( body={}, projectId=TEST_PROJECT_ID ) self.assertEqual(result, TEST_BUILD) @mock.patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook.get_conn") @mock.patch("airflow.providers.google.cloud.hooks.cloud_build.time.sleep") def test_waiting_operation(self, _, get_conn_mock): service_mock = get_conn_mock.return_value service_mock.projects.return_value.builds.return_value.create.return_value.execute.return_value = ( TEST_BUILD ) service_mock.projects.return_value.builds.return_value.get.return_value.execute.return_value = ( TEST_BUILD ) execute_mock = mock.Mock( **{"side_effect": [TEST_WAITING_OPERATION, TEST_DONE_OPERATION, TEST_DONE_OPERATION]} ) service_mock.operations.return_value.get.return_value.execute = execute_mock result = self.hook.create_build(body={}, project_id=TEST_PROJECT_ID) self.assertEqual(result, TEST_BUILD) @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook.project_id', new_callable=PropertyMock, return_value=GCP_PROJECT_ID_HOOK_UNIT_TEST ) @mock.patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook.get_conn") @mock.patch("airflow.providers.google.cloud.hooks.cloud_build.time.sleep") def test_error_operation(self, _, get_conn_mock, mock_project_id): service_mock = get_conn_mock.return_value service_mock.projects.return_value.builds.return_value.create.return_value.execute.return_value = ( TEST_BUILD ) execute_mock = mock.Mock(**{"side_effect": [TEST_WAITING_OPERATION, TEST_ERROR_OPERATION]}) service_mock.operations.return_value.get.return_value.execute = execute_mock with self.assertRaisesRegex(AirflowException, "error"): self.hook.create_build(body={}) class TestGcpComputeHookWithDefaultProjectIdFromConnection(unittest.TestCase): hook = None # type: Optional[CloudBuildHook] def setUp(self): with mock.patch( "airflow.providers.google.cloud.hooks.base.CloudBaseHook.__init__", new=mock_base_gcp_hook_default_project_id, ): self.hook = CloudBuildHook(gcp_conn_id="test") @mock.patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook._authorize") @mock.patch("airflow.providers.google.cloud.hooks.cloud_build.build") def test_cloud_build_client_creation(self, mock_build, mock_authorize): result = self.hook.get_conn() mock_build.assert_called_once_with( 'cloudbuild', 'v1', http=mock_authorize.return_value, cache_discovery=False ) self.assertEqual(mock_build.return_value, result) self.assertEqual(self.hook._conn, result) @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook.project_id', new_callable=PropertyMock, return_value=GCP_PROJECT_ID_HOOK_UNIT_TEST ) @mock.patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook.get_conn") def test_build_immediately_complete(self, get_conn_mock, mock_project_id): service_mock = get_conn_mock.return_value service_mock.projects.return_value.builds.return_value.create.return_value.execute.return_value = ( TEST_BUILD ) service_mock.projects.return_value.builds.return_value.get.return_value.execute.return_value = ( TEST_BUILD ) service_mock.operations.return_value.get.return_value.execute.return_value = TEST_DONE_OPERATION result = self.hook.create_build(body={}) service_mock.projects.return_value.builds.return_value.create.assert_called_once_with( body={}, projectId='example-project' ) self.assertEqual(result, TEST_BUILD) @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook.project_id', new_callable=PropertyMock, return_value=GCP_PROJECT_ID_HOOK_UNIT_TEST ) @mock.patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook.get_conn") @mock.patch("airflow.providers.google.cloud.hooks.cloud_build.time.sleep") def test_waiting_operation(self, _, get_conn_mock, mock_project_id): service_mock = get_conn_mock.return_value service_mock.projects.return_value.builds.return_value.create.return_value.execute.return_value = ( TEST_BUILD ) service_mock.projects.return_value.builds.return_value.get.return_value.execute.return_value = ( TEST_BUILD ) execute_mock = mock.Mock( **{"side_effect": [TEST_WAITING_OPERATION, TEST_DONE_OPERATION, TEST_DONE_OPERATION]} ) service_mock.operations.return_value.get.return_value.execute = execute_mock result = self.hook.create_build(body={}) self.assertEqual(result, TEST_BUILD) @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook.project_id', new_callable=PropertyMock, return_value=GCP_PROJECT_ID_HOOK_UNIT_TEST ) @mock.patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook.get_conn") @mock.patch("airflow.providers.google.cloud.hooks.cloud_build.time.sleep") def test_error_operation(self, _, get_conn_mock, mock_project_id): service_mock = get_conn_mock.return_value service_mock.projects.return_value.builds.return_value.create.return_value.execute.return_value = ( TEST_BUILD ) execute_mock = mock.Mock(**{"side_effect": [TEST_WAITING_OPERATION, TEST_ERROR_OPERATION]}) service_mock.operations.return_value.get.return_value.execute = execute_mock with self.assertRaisesRegex(AirflowException, "error"): self.hook.create_build(body={}) class TestCloudBuildHookWithoutProjectId(unittest.TestCase): hook = None # type: Optional[CloudBuildHook] def setUp(self): with mock.patch( "airflow.providers.google.cloud.hooks.base.CloudBaseHook.__init__", new=mock_base_gcp_hook_no_default_project_id, ): self.hook = CloudBuildHook(gcp_conn_id="test") @mock.patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook._authorize") @mock.patch("airflow.providers.google.cloud.hooks.cloud_build.build") def test_cloud_build_client_creation(self, mock_build, mock_authorize): result = self.hook.get_conn() mock_build.assert_called_once_with( 'cloudbuild', 'v1', http=mock_authorize.return_value, cache_discovery=False ) self.assertEqual(mock_build.return_value, result) self.assertEqual(self.hook._conn, result) @mock.patch( 'airflow.providers.google.cloud.hooks.base.CloudBaseHook.project_id', new_callable=PropertyMock, return_value=None ) @mock.patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook.get_conn") def test_create_build(self, mock_get_conn, mock_project_id): with self.assertRaises(AirflowException) as e: self.hook.create_build(body={}) self.assertEqual( "The project id must be passed either as keyword project_id parameter or as project_id extra in " "GCP connection definition. Both are not set!", str(e.exception), )
import logging import ibmsecurity.utilities.tools try: basestring except NameError: basestring = (str, bytes) logger = logging.getLogger(__name__) # URI for this module uri = "/isam/authzserver" requires_model = "Appliance" docker_warning = ['API invoked requires model: Appliance, appliance is of deployment model: Docker.'] def get_all(isamAppliance, id, stanza_id, check_mode=False, force=False): """ Retrieving all configuration entries for a stanza - Authorization Server """ try: return isamAppliance.invoke_get( description="Retrieving all configuration entries for a stanza - Authorization Server", uri="{0}/{1}/configuration/stanza/{2}/v1".format(uri, id, stanza_id), requires_model=requires_model) except: # Return empty array - exception thrown if stanza has no entries or does not exist ret_obj = isamAppliance.create_return_object() ret_obj['data'] = {} return ret_obj def get(isamAppliance, id, stanza_id, entry_id, check_mode=False, force=False): """ Retrieving a specific configuration entry - Authorization Server """ return isamAppliance.invoke_get(description="Retrieving a specific configuration entry - Authorization Server", uri="{0}/{1}/configuration/stanza/{2}/entry_name/{3}/v1".format(uri, id, stanza_id, entry_id), requires_model=requires_model) def add(isamAppliance, id, stanza_id, entries, check_mode=False, force=False): """ Add configuration entry by stanza - Authorization Server """ if _isDocker(isamAppliance, id, stanza_id): return isamAppliance.create_return_object(warnings=docker_warning) if isinstance(entries, basestring): import ast entries = ast.literal_eval(entries) add_required = False if force is False: add_entries = [] for entry in entries: exists, update_required, value = _check(isamAppliance, id, stanza_id, entry[0], entry[1]) if exists is True: logger.debug( 'Entries exists {0}/{1}/{2}/{3}! Will be ignored.'.format(id, stanza_id, entry[0], entry[1])) else: add_entries.append(entry) add_required = True entries = add_entries if force is True or add_required is True: if check_mode is True: return isamAppliance.create_return_object(changed=True) else: return _add(isamAppliance, id, stanza_id, entries) return isamAppliance.create_return_object() def _add(isamAppliance, id, stanza_id, entries): return isamAppliance.invoke_post( description="Add configuration entry by stanza - Authorization Server", uri="{0}/{1}/configuration/stanza/{2}/entry_name/v1".format(uri, id, stanza_id), data={"entries": entries}, requires_model=requires_model) def _isDocker(isamAppliance, id, stanza_id): ret_obj = get_all(isamAppliance, id, stanza_id) warnings = ret_obj['warnings'] if warnings and 'Docker' in warnings[0]: return True else: return False def set(isamAppliance, id, stanza_id, entries, check_mode=False, force=False): """ Set a configuration entry or entries by stanza - Authorization Server Note: entries has to be [['key', 'value1'], ['key', 'value2]], cannot provide [['key', ['value1', 'value2']]] get() returns the second format - thus lots of logic to handle this discrepancy. Smart enough to update only that which is needed. """ if _isDocker(isamAppliance, id, stanza_id): return isamAppliance.create_return_object(warnings=docker_warning) if isinstance(entries, basestring): import ast entries = ast.literal_eval(entries) set_update = False set_entries = [] if force is False: for entry in _collapse_entries(entries): process_entry = False exists, update_required, cur_value = _check(isamAppliance, id, stanza_id, entry[0], entry[1]) if exists is False: set_update = True process_entry = True elif update_required is True: set_update = True process_entry = True for val in cur_value: # Force delete of existing values, new values will be added delete(isamAppliance, id, stanza_id, entry[0], val, check_mode, True) logger.info( 'Deleting entry, will be re-added: {0}/{1}/{2}/{3}'.format(id, stanza_id, entry[0], val)) if process_entry is True: if isinstance(entry[1], list): for v in entry[1]: set_entries.append([entry[0], v]) else: set_entries.append([entry[0], entry[1]]) if force is True or set_update is True: if check_mode is True: return isamAppliance.create_return_object(changed=True) else: return _add(isamAppliance, id, stanza_id, set_entries) return isamAppliance.create_return_object() def _collapse_entries(entries): """ Convert [['key', 'value1'], ['key', 'value2]] to [['key', ['value1', 'value2']]] Expect key values to be consecutive. Will maintain order as provided. """ if entries is None or len(entries) < 1: return [] else: cur_key = entries[0][0] cur_value = [] new_entry = [] for entry in entries: if entry[0] == cur_key: cur_value.append(entry[1]) else: new_entry.append([cur_key, cur_value]) # reset current key cur_key = entry[0] cur_value = [entry[1]] new_entry.append([cur_key, cur_value]) return new_entry def delete(isamAppliance, id, stanza_id, entry_id, value_id='', check_mode=False, force=False): """ Deleting a value from a configuration entry - Authorization Server """ if _isDocker(isamAppliance, id, stanza_id): return isamAppliance.create_return_object(warnings=docker_warning) exists = False if force is False: exists, update_required, value = _check(isamAppliance, id, stanza_id, entry_id, value_id) if force is True or exists is True: if check_mode is True: return isamAppliance.create_return_object(changed=True) else: # URL being encoded primarily to handle request-log-format that has "%" values in them f_uri = "{0}/{1}/configuration/stanza/{2}/entry_name/{3}/value/{4}/v1".format(uri, id, stanza_id, entry_id, value_id) # Replace % with %25 if it is not encoded already import re ruri = re.sub("%(?![0-9a-fA-F]{2})", "%25", f_uri) # URL encode import urllib.parse full_uri = urllib.parse.quote(ruri) return isamAppliance.invoke_delete( description="Deleting a value from a configuration entry - Authorization Server", uri=full_uri, requires_model=requires_model) return isamAppliance.create_return_object() def delete_all(isamAppliance, id, stanza_id, entry_id, check_mode=False, force=False): """ Deleting all values from a configuration entry - Authorization Server """ delete_required = False if force is False: try: ret_obj = get(isamAppliance, id, stanza_id, entry_id) warnings = ret_obj['warnings'] if warnings and 'Docker' in warnings[0]: return isamAppliance.create_return_object(warnings=ret_obj['warnings']) if ret_obj['data'] != {}: delete_required = True except: pass if force is True or delete_required is True: if check_mode is True: return isamAppliance.create_return_object(changed=True) else: f_uri = "{0}/{1}/configuration/stanza/{2}/entry_name/{3}/v1".format(uri, id, stanza_id, entry_id) return isamAppliance.invoke_delete( description="Deleting all values from a configuration entry - Authorization Server", uri=f_uri, requires_model=requires_model) return isamAppliance.create_return_object() def update(isamAppliance, id, stanza_id, entry_name_id, value_id, check_mode=False, force=False): """ Updating a configuration entry or entries by stanza - Authorization Server """ if _isDocker(isamAppliance, id, stanza_id): return isamAppliance.create_return_object(warnings=docker_warning) if force is False: exists, update_required, cur_value = _check(isamAppliance, id, stanza_id, entry_name_id, value_id) if force is True or update_required is True: if check_mode is True: return isamAppliance.create_return_object(changed=True) else: return isamAppliance.invoke_put( description="Updating a configuration entry or entries by stanza - Authorization Server", uri="{0}/{1}/configuration/stanza/{2}/entry_name/{3}/v1".format(uri, id, stanza_id, entry_name_id), data={ 'value': value_id }, requires_model=requires_model) return isamAppliance.create_return_object() def _check(isamAppliance, id, stanza_id, entry_id, value_id): """ Check if entry/value exists and if exists then if update is required """ try: ret_obj = get(isamAppliance, id, stanza_id, entry_id) exists = True update_required = False value = ret_obj['data'][entry_id] except: return False, True, None # Exception means entry / stanza not found logger.info("Entry found in acld:{0}, stanza:{1}, entryid:{2}, value:{3}".format(id, stanza_id, entry_id, value)) logger.debug("Existing Value(s): {0}".format(value)) logger.debug("Value to update : {0}".format(value_id)) if isinstance(value_id, list): if value != value_id: # Comparing list with no sorting... sequence of values is of importance logger.debug("Value arrays do not match!") update_required = True else: # assuming base string provided for value_id if len(value) == 1: if str(value_id) != str(value[0]): logger.debug("Single value do not match!") update_required = True exists = False # to satisfy delete call else: # base string will not match a zero length array or multiple values in it logger.debug("Current non-single value does not match provided single value!") update_required = True if value_id not in value: logger.debug("Current non-single value does not contain provided single value!") exists = False return exists, update_required, value def compare(isamAppliance1, isamAppliance2, id, stanza_id, id2=None): """ Compare stanza/entries in two appliances authorization server configuration """ if id2 is None or id2 == '': id2 = id ret_obj1 = get_all(isamAppliance1, id, stanza_id) ret_obj2 = get_all(isamAppliance2, id2, stanza_id) return ibmsecurity.utilities.tools.json_compare(ret_obj1, ret_obj2, deleted_keys=[])
"""Testing for Spectral Biclustering methods""" import numpy as np from scipy.sparse import csr_matrix, issparse from sklearn.model_selection import ParameterGrid from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import SkipTest from sklearn.base import BaseEstimator, BiclusterMixin from sklearn.cluster.bicluster import SpectralCoclustering from sklearn.cluster.bicluster import SpectralBiclustering from sklearn.cluster.bicluster import _scale_normalize from sklearn.cluster.bicluster import _bistochastic_normalize from sklearn.cluster.bicluster import _log_normalize from sklearn.metrics import (consensus_score, v_measure_score) from sklearn.datasets import make_biclusters, make_checkerboard class MockBiclustering(BaseEstimator, BiclusterMixin): # Mock object for testing get_submatrix. def __init__(self): pass def get_indices(self, i): # Overridden to reproduce old get_submatrix test. return (np.where([True, True, False, False, True])[0], np.where([False, False, True, True])[0]) def test_get_submatrix(): data = np.arange(20).reshape(5, 4) model = MockBiclustering() for X in (data, csr_matrix(data), data.tolist()): submatrix = model.get_submatrix(0, X) if issparse(submatrix): submatrix = submatrix.toarray() assert_array_equal(submatrix, [[2, 3], [6, 7], [18, 19]]) submatrix[:] = -1 if issparse(X): X = X.toarray() assert np.all(X != -1) def _test_shape_indices(model): # Test get_shape and get_indices on fitted model. for i in range(model.n_clusters): m, n = model.get_shape(i) i_ind, j_ind = model.get_indices(i) assert len(i_ind) == m assert len(j_ind) == n def test_spectral_coclustering(): # Test Dhillon's Spectral CoClustering on a simple problem. param_grid = {'svd_method': ['randomized', 'arpack'], 'n_svd_vecs': [None, 20], 'mini_batch': [False, True], 'init': ['k-means++'], 'n_init': [10], 'n_jobs': [1]} random_state = 0 S, rows, cols = make_biclusters((30, 30), 3, noise=0.5, random_state=random_state) S -= S.min() # needs to be nonnegative before making it sparse S = np.where(S < 1, 0, S) # threshold some values for mat in (S, csr_matrix(S)): for kwargs in ParameterGrid(param_grid): model = SpectralCoclustering(n_clusters=3, random_state=random_state, **kwargs) model.fit(mat) assert model.rows_.shape == (3, 30) assert_array_equal(model.rows_.sum(axis=0), np.ones(30)) assert_array_equal(model.columns_.sum(axis=0), np.ones(30)) assert consensus_score(model.biclusters_, (rows, cols)) == 1 _test_shape_indices(model) def test_spectral_biclustering(): # Test Kluger methods on a checkerboard dataset. S, rows, cols = make_checkerboard((30, 30), 3, noise=0.5, random_state=0) non_default_params = {'method': ['scale', 'log'], 'svd_method': ['arpack'], 'n_svd_vecs': [20], 'mini_batch': [True]} for mat in (S, csr_matrix(S)): for param_name, param_values in non_default_params.items(): for param_value in param_values: model = SpectralBiclustering( n_clusters=3, n_init=3, init='k-means++', random_state=0, ) model.set_params(**dict([(param_name, param_value)])) if issparse(mat) and model.get_params().get('method') == 'log': # cannot take log of sparse matrix assert_raises(ValueError, model.fit, mat) continue else: model.fit(mat) assert model.rows_.shape == (9, 30) assert model.columns_.shape == (9, 30) assert_array_equal(model.rows_.sum(axis=0), np.repeat(3, 30)) assert_array_equal(model.columns_.sum(axis=0), np.repeat(3, 30)) assert consensus_score(model.biclusters_, (rows, cols)) == 1 _test_shape_indices(model) def _do_scale_test(scaled): """Check that rows sum to one constant, and columns to another.""" row_sum = scaled.sum(axis=1) col_sum = scaled.sum(axis=0) if issparse(scaled): row_sum = np.asarray(row_sum).squeeze() col_sum = np.asarray(col_sum).squeeze() assert_array_almost_equal(row_sum, np.tile(row_sum.mean(), 100), decimal=1) assert_array_almost_equal(col_sum, np.tile(col_sum.mean(), 100), decimal=1) def _do_bistochastic_test(scaled): """Check that rows and columns sum to the same constant.""" _do_scale_test(scaled) assert_almost_equal(scaled.sum(axis=0).mean(), scaled.sum(axis=1).mean(), decimal=1) def test_scale_normalize(): generator = np.random.RandomState(0) X = generator.rand(100, 100) for mat in (X, csr_matrix(X)): scaled, _, _ = _scale_normalize(mat) _do_scale_test(scaled) if issparse(mat): assert issparse(scaled) def test_bistochastic_normalize(): generator = np.random.RandomState(0) X = generator.rand(100, 100) for mat in (X, csr_matrix(X)): scaled = _bistochastic_normalize(mat) _do_bistochastic_test(scaled) if issparse(mat): assert issparse(scaled) def test_log_normalize(): # adding any constant to a log-scaled matrix should make it # bistochastic generator = np.random.RandomState(0) mat = generator.rand(100, 100) scaled = _log_normalize(mat) + 1 _do_bistochastic_test(scaled) def test_fit_best_piecewise(): model = SpectralBiclustering(random_state=0) vectors = np.array([[0, 0, 0, 1, 1, 1], [2, 2, 2, 3, 3, 3], [0, 1, 2, 3, 4, 5]]) best = model._fit_best_piecewise(vectors, n_best=2, n_clusters=2) assert_array_equal(best, vectors[:2]) def test_project_and_cluster(): model = SpectralBiclustering(random_state=0) data = np.array([[1, 1, 1], [1, 1, 1], [3, 6, 3], [3, 6, 3]]) vectors = np.array([[1, 0], [0, 1], [0, 0]]) for mat in (data, csr_matrix(data)): labels = model._project_and_cluster(data, vectors, n_clusters=2) assert_almost_equal(v_measure_score(labels, [0, 0, 1, 1]), 1.0) def test_perfect_checkerboard(): # XXX test always skipped raise SkipTest("This test is failing on the buildbot, but cannot" " reproduce. Temporarily disabling it until it can be" " reproduced and fixed.") model = SpectralBiclustering(3, svd_method="arpack", random_state=0) S, rows, cols = make_checkerboard((30, 30), 3, noise=0, random_state=0) model.fit(S) assert consensus_score(model.biclusters_, (rows, cols)) == 1 S, rows, cols = make_checkerboard((40, 30), 3, noise=0, random_state=0) model.fit(S) assert consensus_score(model.biclusters_, (rows, cols)) == 1 S, rows, cols = make_checkerboard((30, 40), 3, noise=0, random_state=0) model.fit(S) assert consensus_score(model.biclusters_, (rows, cols)) == 1 def test_errors(): data = np.arange(25).reshape((5, 5)) model = SpectralBiclustering(n_clusters=(3, 3, 3)) assert_raises(ValueError, model.fit, data) model = SpectralBiclustering(n_clusters='abc') assert_raises(ValueError, model.fit, data) model = SpectralBiclustering(n_clusters=(3, 'abc')) assert_raises(ValueError, model.fit, data) model = SpectralBiclustering(method='unknown') assert_raises(ValueError, model.fit, data) model = SpectralBiclustering(svd_method='unknown') assert_raises(ValueError, model.fit, data) model = SpectralBiclustering(n_components=0) assert_raises(ValueError, model.fit, data) model = SpectralBiclustering(n_best=0) assert_raises(ValueError, model.fit, data) model = SpectralBiclustering(n_components=3, n_best=4) assert_raises(ValueError, model.fit, data) model = SpectralBiclustering() data = np.arange(27).reshape((3, 3, 3)) assert_raises(ValueError, model.fit, data)
# Copyright (c) 2010-2012 OpenStack, LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import hashlib import httplib import os import random import socket import StringIO import time import urllib import simplejson as json from nose import SkipTest from xml.dom import minidom class AuthenticationFailed(Exception): pass class RequestError(Exception): pass class ResponseError(Exception): def __init__(self, response): self.status = response.status self.reason = response.reason Exception.__init__(self) def __str__(self): return '%d: %s' % (self.status, self.reason) def __repr__(self): return '%d: %s' % (self.status, self.reason) def listing_empty(method): for i in xrange(0, 6): if len(method()) == 0: return True time.sleep(2 ** i) return False def listing_items(method): marker = None once = True items = [] while once or items: for i in items: yield i if once or marker: if marker: items = method(parms={'marker': marker}) else: items = method() if len(items) == 10000: marker = items[-1] else: marker = None once = False else: items = [] class Connection(object): def __init__(self, config): for key in 'auth_host auth_port auth_ssl username password'.split(): if not key in config: raise SkipTest self.auth_host = config['auth_host'] self.auth_port = int(config['auth_port']) self.auth_ssl = config['auth_ssl'] in ('on', 'true', 'yes', '1') self.auth_prefix = config.get('auth_prefix', '/') self.account = config.get('account') self.username = config['username'] self.password = config['password'] self.storage_host = None self.storage_port = None self.conn_class = None def get_account(self): return Account(self, self.account) def authenticate(self, clone_conn=None): if clone_conn: self.conn_class = clone_conn.conn_class self.storage_host = clone_conn.storage_host self.storage_url = clone_conn.storage_url self.storage_port = clone_conn.storage_port self.storage_token = clone_conn.storage_token return if self.account: auth_user = '%s:%s' % (self.account, self.username) else: auth_user = self.username headers = { 'x-auth-user': auth_user, 'x-auth-key': self.password, } path = '%sv1.0' % (self.auth_prefix) if self.auth_ssl: connection = httplib.HTTPSConnection(self.auth_host, port=self.auth_port) else: connection = httplib.HTTPConnection(self.auth_host, port=self.auth_port) #connection.set_debuglevel(3) connection.request('GET', path, '', headers) response = connection.getresponse() connection.close() if response.status == 401: raise AuthenticationFailed() if response.status not in (200, 204): raise ResponseError(response) for hdr in response.getheaders(): if hdr[0].lower() == "x-storage-url": storage_url = hdr[1] elif hdr[0].lower() == "x-storage-token": storage_token = hdr[1] if not (storage_url and storage_token): raise AuthenticationFailed() x = storage_url.split('/') if x[0] == 'http:': self.conn_class = httplib.HTTPConnection self.storage_port = 80 elif x[0] == 'https:': self.conn_class = httplib.HTTPSConnection self.storage_port = 443 else: raise ValueError('unexpected protocol %s' % (x[0])) self.storage_host = x[2].split(':')[0] if ':' in x[2]: self.storage_port = int(x[2].split(':')[1]) self.storage_url = '/%s/%s' % (x[3], x[4]) self.storage_token = storage_token self.http_connect() return self.storage_url, self.storage_token def http_connect(self): self.connection = self.conn_class(self.storage_host, port=self.storage_port) #self.connection.set_debuglevel(3) def make_path(self, path=[], cfg={}): if cfg.get('version_only_path'): return '/' + self.storage_url.split('/')[1] if path: quote = urllib.quote if cfg.get('no_quote') or cfg.get('no_path_quote'): quote = lambda x: x return '%s/%s' % (self.storage_url, '/'.join([quote(i) for i in path])) else: return self.storage_url def make_headers(self, hdrs, cfg={}): headers = {} if not cfg.get('no_auth_token'): headers['X-Auth-Token'] = self.storage_token if isinstance(hdrs, dict): headers.update(hdrs) return headers def make_request(self, method, path=[], data='', hdrs={}, parms={}, cfg={}): path = self.make_path(path, cfg=cfg) headers = self.make_headers(hdrs, cfg=cfg) if isinstance(parms, dict) and parms: quote = urllib.quote if cfg.get('no_quote') or cfg.get('no_parms_quote'): quote = lambda x: x query_args = ['%s=%s' % (quote(x), quote(str(y))) for (x, y) in parms.items()] path = '%s?%s' % (path, '&'.join(query_args)) if not cfg.get('no_content_length'): if cfg.get('set_content_length'): headers['Content-Length'] = cfg.get('set_content_length') else: headers['Content-Length'] = len(data) def try_request(): self.http_connect() self.connection.request(method, path, data, headers) return self.connection.getresponse() self.response = None try_count = 0 while try_count < 5: try_count += 1 try: self.response = try_request() except httplib.HTTPException: continue if self.response.status == 401: self.authenticate() continue elif self.response.status == 503: if try_count != 5: time.sleep(5) continue break if self.response: return self.response.status raise RequestError('Unable to complete http request') def put_start(self, path, hdrs={}, parms={}, cfg={}, chunked=False): self.http_connect() path = self.make_path(path, cfg) headers = self.make_headers(hdrs, cfg=cfg) if chunked: headers['Transfer-Encoding'] = 'chunked' headers.pop('Content-Length', None) if isinstance(parms, dict) and parms: quote = urllib.quote if cfg.get('no_quote') or cfg.get('no_parms_quote'): quote = lambda x: x query_args = ['%s=%s' % (quote(x), quote(str(y))) for (x, y) in parms.items()] path = '%s?%s' % (path, '&'.join(query_args)) query_args = ['%s=%s' % (urllib.quote(x), urllib.quote(str(y))) for (x, y) in parms.items()] path = '%s?%s' % (path, '&'.join(query_args)) self.connection = self.conn_class(self.storage_host, port=self.storage_port) #self.connection.set_debuglevel(3) self.connection.putrequest('PUT', path) for key, value in headers.iteritems(): self.connection.putheader(key, value) self.connection.endheaders() def put_data(self, data, chunked=False): if chunked: self.connection.send('%s\r\n%s\r\n' % (hex(len(data)), data)) else: self.connection.send(data) def put_end(self, chunked=False): if chunked: self.connection.send('0\r\n\r\n') self.response = self.connection.getresponse() self.connection.close() return self.response.status class Base: def __str__(self): return self.name def header_fields(self, fields): headers = dict(self.conn.response.getheaders()) ret = {} for field in fields: if not field[1] in headers: raise ValueError("%s was not found in response header" % (field[1])) try: ret[field[0]] = int(headers[field[1]]) except ValueError: ret[field[0]] = headers[field[1]] return ret class Account(Base): def __init__(self, conn, name): self.conn = conn self.name = str(name) def container(self, container_name): return Container(self.conn, self.name, container_name) def containers(self, hdrs={}, parms={}, cfg={}): format = parms.get('format', None) if format not in [None, 'json', 'xml']: raise RequestError('Invalid format: %s' % format) if format is None and 'format' in parms: del parms['format'] status = self.conn.make_request('GET', self.path, hdrs=hdrs, parms=parms, cfg=cfg) if status == 200: if format == 'json': conts = json.loads(self.conn.response.read()) for cont in conts: cont['name'] = cont['name'].encode('utf-8') return conts elif format == 'xml': conts = [] tree = minidom.parseString(self.conn.response.read()) for x in tree.getElementsByTagName('container'): cont = {} for key in ['name', 'count', 'bytes']: cont[key] = x.getElementsByTagName(key)[0].\ childNodes[0].nodeValue conts.append(cont) for cont in conts: cont['name'] = cont['name'].encode('utf-8') return conts else: lines = self.conn.response.read().split('\n') if lines and not lines[-1]: lines = lines[:-1] return lines elif status == 204: return [] raise ResponseError(self.conn.response) def delete_containers(self): for c in listing_items(self.containers): cont = self.container(c) if not cont.delete_recursive(): return False return listing_empty(self.containers) def info(self, hdrs={}, parms={}, cfg={}): if self.conn.make_request('HEAD', self.path, hdrs=hdrs, parms=parms, cfg=cfg) != 204: raise ResponseError(self.conn.response) fields = [['object_count', 'x-account-object-count'], ['container_count', 'x-account-container-count'], ['bytes_used', 'x-account-bytes-used']] return self.header_fields(fields) @property def path(self): return [] class Container(Base): def __init__(self, conn, account, name): self.conn = conn self.account = str(account) self.name = str(name) def create(self, hdrs={}, parms={}, cfg={}): return self.conn.make_request('PUT', self.path, hdrs=hdrs, parms=parms, cfg=cfg) in (201, 202) def delete(self, hdrs={}, parms={}): return self.conn.make_request('DELETE', self.path, hdrs=hdrs, parms=parms) == 204 def delete_files(self): for f in listing_items(self.files): file = self.file(f) if not file.delete(): return False return listing_empty(self.files) def delete_recursive(self): return self.delete_files() and self.delete() def file(self, file_name): return File(self.conn, self.account, self.name, file_name) def files(self, hdrs={}, parms={}, cfg={}): format = parms.get('format', None) if format not in [None, 'json', 'xml']: raise RequestError('Invalid format: %s' % format) if format is None and 'format' in parms: del parms['format'] status = self.conn.make_request('GET', self.path, hdrs=hdrs, parms=parms, cfg=cfg) if status == 200: if format == 'json': files = json.loads(self.conn.response.read()) for file in files: file['name'] = file['name'].encode('utf-8') file['content_type'] = file['content_type'].encode('utf-8') return files elif format == 'xml': files = [] tree = minidom.parseString(self.conn.response.read()) for x in tree.getElementsByTagName('object'): file = {} for key in ['name', 'hash', 'bytes', 'content_type', 'last_modified']: file[key] = x.getElementsByTagName(key)[0].\ childNodes[0].nodeValue files.append(file) for file in files: file['name'] = file['name'].encode('utf-8') file['content_type'] = file['content_type'].encode('utf-8') return files else: content = self.conn.response.read() if content: lines = content.split('\n') if lines and not lines[-1]: lines = lines[:-1] return lines else: return [] elif status == 204: return [] raise ResponseError(self.conn.response) def info(self, hdrs={}, parms={}, cfg={}): status = self.conn.make_request('HEAD', self.path, hdrs=hdrs, parms=parms, cfg=cfg) if self.conn.response.status == 204: fields = [['bytes_used', 'x-container-bytes-used'], ['object_count', 'x-container-object-count']] return self.header_fields(fields) raise ResponseError(self.conn.response) @property def path(self): return [self.name] class File(Base): def __init__(self, conn, account, container, name): self.conn = conn self.account = str(account) self.container = str(container) self.name = str(name) self.chunked_write_in_progress = False self.content_type = None self.size = None self.metadata = {} def make_headers(self, cfg={}): headers = {} if not cfg.get('no_content_length'): if cfg.get('set_content_length'): headers['Content-Length'] = cfg.get('set_content_length') elif self.size: headers['Content-Length'] = self.size else: headers['Content-Length'] = 0 if cfg.get('no_content_type'): pass elif self.content_type: headers['Content-Type'] = self.content_type else: headers['Content-Type'] = 'application/octet-stream' for key in self.metadata: headers['X-Object-Meta-' + key] = self.metadata[key] return headers @classmethod def compute_md5sum(cls, data): block_size = 4096 if isinstance(data, str): data = StringIO.StringIO(data) checksum = hashlib.md5() buff = data.read(block_size) while buff: checksum.update(buff) buff = data.read(block_size) data.seek(0) return checksum.hexdigest() def copy(self, dest_cont, dest_file, hdrs={}, parms={}, cfg={}): if 'destination' in cfg: headers = {'Destination': cfg['destination']} elif cfg.get('no_destination'): headers = {} else: headers = {'Destination': '%s/%s' % (dest_cont, dest_file)} headers.update(hdrs) if 'Destination' in headers: headers['Destination'] = urllib.quote(headers['Destination']) return self.conn.make_request('COPY', self.path, hdrs=headers, parms=parms) == 201 def delete(self, hdrs={}, parms={}): if self.conn.make_request('DELETE', self.path, hdrs=hdrs, parms=parms) != 204: raise ResponseError(self.conn.response) return True def info(self, hdrs={}, parms={}, cfg={}): if self.conn.make_request('HEAD', self.path, hdrs=hdrs, parms=parms, cfg=cfg) != 200: raise ResponseError(self.conn.response) fields = [['content_length', 'content-length'], ['content_type', 'content-type'], ['last_modified', 'last-modified'], ['etag', 'etag']] header_fields = self.header_fields(fields) header_fields['etag'] = header_fields['etag'].strip('"') return header_fields def initialize(self, hdrs={}, parms={}): if not self.name: return False status = self.conn.make_request('HEAD', self.path, hdrs=hdrs, parms=parms) if status == 404: return False elif (status < 200) or (status > 299): raise ResponseError(self.conn.response) for hdr in self.conn.response.getheaders(): if hdr[0].lower() == 'content-type': self.content_type = hdr[1] if hdr[0].lower().startswith('x-object-meta-'): self.metadata[hdr[0][14:]] = hdr[1] if hdr[0].lower() == 'etag': self.etag = hdr[1].strip('"') if hdr[0].lower() == 'content-length': self.size = int(hdr[1]) if hdr[0].lower() == 'last-modified': self.last_modified = hdr[1] return True def load_from_filename(self, filename, callback=None): fobj = open(filename, 'rb') self.write(fobj, callback=callback) fobj.close() @property def path(self): return [self.container, self.name] @classmethod def random_data(cls, size=None): if size is None: size = random.randint(1, 32768) fd = open('/dev/urandom', 'r') data = fd.read(size) fd.close() return data def read(self, size=-1, offset=0, hdrs=None, buffer=None, callback=None, cfg={}): if size > 0: range = 'bytes=%d-%d' % (offset, (offset + size) - 1) if hdrs: hdrs['Range'] = range else: hdrs = {'Range': range} status = self.conn.make_request('GET', self.path, hdrs=hdrs, cfg=cfg) if(status < 200) or (status > 299): raise ResponseError(self.conn.response) for hdr in self.conn.response.getheaders(): if hdr[0].lower() == 'content-type': self.content_type = hdr[1] if hasattr(buffer, 'write'): scratch = self.conn.response.read(8192) transferred = 0 while len(scratch) > 0: buffer.write(scratch) transferred += len(scratch) if callable(callback): callback(transferred, self.size) scratch = self.conn.response.read(8192) return None else: return self.conn.response.read() def read_md5(self): status = self.conn.make_request('GET', self.path) if(status < 200) or (status > 299): raise ResponseError(self.conn.response) checksum = hashlib.md5() scratch = self.conn.response.read(8192) while len(scratch) > 0: checksum.update(scratch) scratch = self.conn.response.read(8192) return checksum.hexdigest() def save_to_filename(self, filename, callback=None): try: fobj = open(filename, 'wb') self.read(buffer=fobj, callback=callback) finally: fobj.close() def sync_metadata(self, metadata={}, cfg={}): self.metadata.update(metadata) if self.metadata: headers = self.make_headers(cfg=cfg) if not cfg.get('no_content_length'): if cfg.get('set_content_length'): headers['Content-Length'] = \ cfg.get('set_content_length') else: headers['Content-Length'] = 0 self.conn.make_request('POST', self.path, hdrs=headers, cfg=cfg) if self.conn.response.status not in (201, 202): raise ResponseError(self.conn.response) return True def chunked_write(self, data=None, hdrs={}, parms={}, cfg={}): if data is not None and self.chunked_write_in_progress: self.conn.put_data(data, True) elif data is not None: self.chunked_write_in_progress = True headers = self.make_headers(cfg=cfg) headers.update(hdrs) self.conn.put_start(self.path, hdrs=headers, parms=parms, cfg=cfg, chunked=True) self.conn.put_data(data, True) elif self.chunked_write_in_progress: self.chunked_write_in_progress = False return self.conn.put_end(True) == 201 else: raise RuntimeError def write(self, data='', hdrs={}, parms={}, callback=None, cfg={}): block_size = 2 ** 20 if isinstance(data, file): try: data.flush() data.seek(0) except IOError: pass self.size = int(os.fstat(data.fileno())[6]) else: data = StringIO.StringIO(data) self.size = data.len headers = self.make_headers(cfg=cfg) headers.update(hdrs) self.conn.put_start(self.path, hdrs=headers, parms=parms, cfg=cfg) transfered = 0 buff = data.read(block_size) try: while len(buff) > 0: self.conn.put_data(buff) buff = data.read(block_size) transfered += len(buff) if callable(callback): callback(transfered, self.size) self.conn.put_end() except socket.timeout, err: raise err if (self.conn.response.status < 200) or \ (self.conn.response.status > 299): raise ResponseError(self.conn.response) self.md5 = self.compute_md5sum(data) return True def write_random(self, size=None, hdrs={}, parms={}, cfg={}): data = self.random_data(size) if not self.write(data, hdrs=hdrs, parms=parms, cfg=cfg): raise ResponseError(self.conn.response) self.md5 = self.compute_md5sum(StringIO.StringIO(data)) return data
# Gum sound editor (https://github.com/stackp/Gum) # Copyright 2009 (C) Pierre Duquesne <stackp@online.fr> # Licensed under the Revised BSD License. from gum.lib.event import Signal try: from gum import fast except ImportError: HAVE_FAST = False print "Warning: 'fast' module not found. You won't have fast display!" else: HAVE_FAST = True def frame2cell(frame, density): return frame / float(density) def cell2frame(cell, density): return cell * density def _overview(data, start, width, density): numchan = data.ndim if numchan == 1: channels = [data] else: channels = data.transpose() o = [] for chan in channels: values = _condense(chan, start, width, density) o.append(values) return o def _condense(data, start, width, density): """Returns a list of (min, max) tuples. A density slices the data in "cells", each cell containing several frames. This function returns the min and max of each visible cell. """ res = [] start = int(start) width = int(width) for i in range(start, start + width): a = int(round(cell2frame(i, density))) b = int(round(cell2frame(i + 1, density))) d = data[a:b] if len(d) == 0: break mini = d.min() maxi = d.max() res.append((mini, maxi)) return res if HAVE_FAST: _condense = fast._condense def intersection((a, b), (x, y)): if b <= x or a >= y: return None else: start = max(a, x) end = min(b, y) return start, end class OverviewCache(object): def set_data(self, data): self._data = data # _cache is a tuple (start_index, width, density, values) self._cache = None, None, None, None def get(self, start, width, density): start = int(start) done = False c_start, c_width, c_density, _ = self._cache # Same as last call if (c_start, c_width, c_density) == (start, width, density): done = True # There is an intersection if not done and c_density == density: inter = intersection((start, start + width), (c_start, c_start + c_width)) if inter != None: head, tail = [], [] a, b = inter if start < a: head = _overview(self._data, start, a - start, density) if b < start + width: tail = _overview(self._data, b, start + width - b, density) i, j = [int(x - c_start) for x in inter] body = zip(*self._cache[3])[i:j] ov = zip(*head) + body + zip(*tail) ov = zip(*ov) ov = [list(t) for t in ov] self._cache = (start, width, density, ov) done = True # Compute entirely if not done: ov = _overview(self._data, start, width, density) self._cache = (start, width, density, ov) return self._cache[3] class Graph(object): """Scale the sound visualization. When audio is drawn on the screen, several frames are condensed in one column of pixels. This object computes what to display, according to zooming and position in the sound. """ def __init__(self, sound): self.changed = Signal() self._overview = OverviewCache() self._width = 100. self.set_sound(sound) def get_density(self): return self._density def set_density(self, value): mini = 1 maxi = max(mini, self.numframes() / float(self._width)) self._density = self._gauge(value, mini, maxi) density = property(get_density, set_density) def set_sound(self, sound): self._sound = sound self._view_start = 0 # is a cell self.density = self.numframes() / float(self._width) self._sound.changed.connect(self.on_sound_changed) self.on_sound_changed() def on_sound_changed(self): self._overview.set_data(self._sound.frames) self.update() def set_width(self, width): start, end = self.view() self._width = width self.density = (end - start) / float(width) self.move_to(start) def update(self): self._adjust_view() self.changed() def numframes(self): return len(self._sound.frames) def view(self): """ Return start and end frames; end is exclusive. """ start = cell2frame(self._view_start, self.density) end = start + cell2frame(self._width, self.density) n = self.numframes() if end > n: end = n return (start, end) def set_view(self, start, end): self.density = (end - start) / float(self._width) self.move_to(start) def move_to(self, frame): "Moves the view start and keep the view length" self._view_start = frame2cell(frame, self.density) self.update() def center_on(self, frame): self.move_to(frame - (self._width - 1) * self.density * 0.5) def frmtopxl(self, f): "Converts a frame index to a pixel index." return int(frame2cell(f, self.density) - self._view_start) def pxltofrm(self, p): "Converts a pixel index to a frame index." f = cell2frame(self._view_start + p, self.density) return int(round(self._gauge(f, 0, self.numframes()))) def _gauge(self, value, mini, maxi): "Calibrate value between mini and maxi." if value < mini: value = mini if value > maxi: value = maxi return value def _zoom(self, factor): """Expand or shrink view according to factor. 0 < factor < 1 zoom in factor = 1 unchanged 1 < factor < +Inf zoom out The zoom factor is relative to the current zoom, ie.:: self._zoom(x, n) self._zoom(x, m) is equivalent to:: self._zoom(x, n * m) """ self.density *= factor def middle(self): start, end = self.view() return start + (end - 1 - start) * 0.5 def zoom_in(self): "Make view twice smaller, centering on the middle of the view." mid = self.middle() self._zoom(0.5) self.center_on(mid) def zoom_out(self): "Make view twice larger, centering on the middle of the view." mid = self.middle() self._zoom(2) self.center_on(mid) def zoom_out_full(self): "Fit everything in the view." self.set_view(0, self.numframes()) def is_zoomed_out_full(self): start, end = self.view() return start == 0 and end == self.numframes() def zoom_on(self, pixel, factor): point = self.pxltofrm(pixel) self._zoom(factor) self.move_to(point - pixel * self.density) def zoom_in_on(self, pixel): self.zoom_on(pixel, 0.8) def zoom_out_on(self, pixel): self.zoom_on(pixel, 1.2) def _scroll(self, factor): """Shift the view. A negative factor shifts the view to the left, a positive one to the right. The absolute value of the factor determines the length of the shift, relative to the view length. For example: 0.1 is 10%, 0.5 is one half, 1.0 is 100%. """ l = self._width * factor self._view_start += l self.update() def scroll_left(self): self._scroll(-0.1) def scroll_right(self): self._scroll(0.1) def channels(self): "Return the graph values." o = self._overview.get(self._view_start, self._width, self.density) return o def _adjust_view(self): numcells = frame2cell(self.numframes(), self.density) if self._view_start + self._width > numcells: self._view_start = numcells - self._width if self._view_start < 0: self._view_start = 0 # Test functions DTYPE = 'float64' def test_overview(): import numpy l = 1000000 b = numpy.array(range(l), DTYPE) assert len(_condense(b, 0, l, l/10)) == 10 assert len(_condense(b, 0, l, l/100)) == 100 def test_middle(): from gum.lib.mock import Mock, Fake import numpy sound = Mock({"numchan": 1}) sound.changed = Fake() sound.frames = [] g = Graph(sound) for nframes, mid in [(4, 1.5), (9, 4), (10, 4.5)]: sound.frames = numpy.array(range(nframes)) g.set_sound(sound) assert g.middle() == mid def test_intersection(): assert intersection((1, 4), (2, 3)) == (2, 3) assert intersection((2, 3), (1, 4)) == (2, 3) assert intersection((1, 7), (5, 9)) == (5, 7) assert intersection((5, 9), (1, 7)) == (5, 7) assert intersection((1, 4), (5, 9)) == None assert intersection((5, 9), (1, 4)) == None def test_Graph(): from gum.lib.mock import Mock, Fake import numpy sound = Mock({"numchan": 1}) sound.changed = Fake() sound.frames = numpy.array(range(1000), DTYPE) c = Graph(sound) c.set_width(200) o = c.channels() class Foo: def foo(self): print "Changed." f = Foo() c = Graph(sound) c.changed.connect(f.foo) c.set_width(200) o = c.channels() # stereo import numpy sound = Mock({"numchan": 2}) sound.changed = Fake() data = numpy.array([[1, 1], [2, 2], [3, 3]], DTYPE) sound.frames = data c = Graph(sound) o = c.channels() assert(len(o)) == 2 def test_zoom(): from gum.lib.mock import Mock, Fake import numpy sound = Mock({"numchan": 1}) data = numpy.array([1, 2, 3, 4], DTYPE) sound.frames = data sound.changed = Fake() g = Graph(sound) g.set_width(4) g._zoom(1) g.center_on(1.5) o = g.channels() assert o == [[(1, 1), (2, 2), (3, 3), (4, 4)]] g._zoom(factor=1) g.center_on(0) o = g.channels() assert o == [[(1, 1), (2, 2), (3, 3), (4, 4)]] g._zoom(1) g.center_on(6) o = g.channels() assert o == [[(1, 1), (2, 2), (3, 3), (4, 4)]] g._zoom(factor=0.5) g.center_on(1.5) g.set_width(4) o = g.channels() assert o == [[(1, 1), (2, 2), (3, 3), (4, 4)]] g.set_width(2) g._zoom(0.5) g.center_on(0) o = g.channels() assert o == [[(1, 1), (2, 2)]] g.set_width(4) g._zoom(0.25) g.center_on(0) o = g.channels() assert o == [[(1, 1), (2, 2), (3, 3), (4, 4)]] g.set_width(4) g._zoom(4) g.center_on(4) o = g.channels() assert o == [[(1, 1), (2, 2), (3, 3), (4, 4)]], o g.set_width(100) data = numpy.array(range(3241)) sound.frames = data g.zoom_out_full() g._zoom(factor=0.5) g._zoom(factor=0.5) start, end = g.view() g.zoom_out_full() g._zoom(factor=0.5 * 0.5) assert (start, end) == g.view() def test_zoom_in(): import numpy from gum.lib.mock import Mock, Fake sound = Mock({"numchan": 1}) sound.changed = Fake() data = numpy.array([1, 2, 3, 4], DTYPE) sound.frames = data g = Graph(sound) g.set_width(2) g.zoom_in() o = g.channels() assert o == [[(2, 2), (3, 3)]] g.zoom_out() g.set_width(4) o = g.channels() assert o == [[(1, 1), (2, 2), (3, 3), (4, 4)]] def test_zoom_in_on(): import numpy from gum.lib.mock import Mock, Fake sound = Mock({"numchan": 1}) sound.changed = Fake() data = numpy.array([1, 2, 3, 4], DTYPE) sound.frames = data g = Graph(sound) g.set_width(2) g.zoom_in_on(0) assert g.channels() == [[(1, 2), (3, 3)]] g.zoom_out() g.zoom_in_on(1) assert g.channels() == [[(1, 2), (3, 3)]] g.zoom_out() g.zoom_in_on(2) assert g.channels() == [[(1, 2), (3, 3)]] def test_scroll(): import numpy from gum.lib.mock import Mock, Fake sound = Mock({}) data = numpy.array([1, 2, 3, 4]) sound.frames = data sound.changed = Fake() g = Graph(sound) g.set_width(4) g.scroll_right() length = g.numframes() start, end = g.view() assert length == 4 assert start == 0 assert end == 4 def test_density(): from gum.models import Sound import gum g = Graph(Sound(gum.basedir + "/data/test/test1.wav")) g.set_width(700) g.zoom_in() g.channels() g.zoom_in() g.channels() g.zoom_in() d = g.density pos = [26744.9875, 18793.775, 15902.425, 13011.075, 10119.725, 7228.375, 4337.025, 1445.675, 0.0, 2891.35, 5782.7, 8674.05, 11565.4, 14456.75, 17348.1, 20239.45] for x in pos: g.move_to(x) assert d == g.density def test_channels(): import numpy from gum.lib.mock import Mock, Fake sound = Mock({"numchan": 1}) sound.changed = Fake() sound.frames = numpy.array(range(1000000), DTYPE) g = Graph(sound) for w in [1, 10, 11, 12, 13, 14, 15, 29, 54, 12.0, 347, 231., 1030]: g.set_width(w) c = g.channels() assert len(c[0]) == w, \ "expected: %d, got: %d, density: %f, last value: %s " % \ (w, len(c[0]), g.density, str(c[0][-1])) def test_OverviewCache(): import numpy cache = OverviewCache() cache.set_data(numpy.array([1, 2, 3, 4], DTYPE)) o = cache.get(start=0, width=4, density=1) assert o == [[(1, 1), (2, 2), (3, 3), (4, 4)]] o2 = cache.get(start=0, width=4, density=1) assert o2 == o assert o2 is o cache.set_data(numpy.array([1, 2, 3, 4], DTYPE)) o3 = cache.get(start=0, width=4, density=1) assert o3 == o assert o3 is not o cache.set_data(numpy.array(range(1000), DTYPE)) o1 = cache.get(start=0, width=10, density=10) o2 = cache.get(start=4, width=10, density=10) o3 = cache.get(start=0, width=10, density=10) o4 = cache.get(start=4, width=10, density=10) assert o1 == o3 assert o2 == o4 assert o1[0][4:] == o2[0][:6], str(o1[0][4:]) + str(o2[0][:6]) if __name__ == "__main__": test_overview() test_Graph() test_intersection() test_channels() test_middle() test_zoom() test_zoom_in() test_scroll() test_zoom_in_on() test_OverviewCache() test_density()
#!/usr/bin/env python """ Copyright (c) 2021 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import itertools import logging import os import random import cocotb_test.simulator import pytest import cocotb from cocotb.clock import Clock from cocotb.triggers import RisingEdge from cocotb.regression import TestFactory from cocotbext.axi import AxiStreamBus, AxiStreamFrame, AxiStreamSource, AxiStreamSink class TB(object): def __init__(self, dut): self.dut = dut self.log = logging.getLogger("cocotb.tb") self.log.setLevel(logging.DEBUG) cocotb.start_soon(Clock(dut.clk, 10, units="ns").start()) self.source = AxiStreamSource(AxiStreamBus.from_prefix(dut, "s_axis"), dut.clk, dut.rst) self.sink = AxiStreamSink(AxiStreamBus.from_prefix(dut, "m_axis"), dut.clk, dut.rst) def set_idle_generator(self, generator=None): if generator: self.source.set_pause_generator(generator()) def set_backpressure_generator(self, generator=None): if generator: self.sink.set_pause_generator(generator()) async def reset(self): self.dut.rst.setimmediatevalue(0) await RisingEdge(self.dut.clk) await RisingEdge(self.dut.clk) self.dut.rst.value = 1 await RisingEdge(self.dut.clk) await RisingEdge(self.dut.clk) self.dut.rst.value = 0 await RisingEdge(self.dut.clk) await RisingEdge(self.dut.clk) async def run_test(dut, payload_lengths=None, payload_data=None, idle_inserter=None, backpressure_inserter=None): tb = TB(dut) id_count = 2**len(tb.source.bus.tid) cur_id = 1 await tb.reset() tb.set_idle_generator(idle_inserter) tb.set_backpressure_generator(backpressure_inserter) test_frames = [] for test_data in [payload_data(x) for x in payload_lengths()]: test_frame = AxiStreamFrame(test_data) test_frame.tid = cur_id test_frame.tdest = cur_id test_frames.append(test_frame) await tb.source.send(test_frame) cur_id = (cur_id + 1) % id_count for test_frame in test_frames: rx_frame = await tb.sink.recv() assert rx_frame.tdata == test_frame.tdata assert rx_frame.tid == test_frame.tid assert rx_frame.tdest == test_frame.tdest assert not rx_frame.tuser assert tb.sink.empty() await RisingEdge(dut.clk) await RisingEdge(dut.clk) async def run_test_tuser_assert(dut): tb = TB(dut) await tb.reset() test_data = bytearray(itertools.islice(itertools.cycle(range(256)), 32)) test_frame = AxiStreamFrame(test_data, tuser=1) await tb.source.send(test_frame) if int(os.getenv("PARAM_DROP_BAD_FRAME")): for k in range(64): await RisingEdge(dut.clk) else: rx_frame = await tb.sink.recv() assert rx_frame.tdata == test_data assert rx_frame.tuser assert tb.sink.empty() await RisingEdge(dut.clk) await RisingEdge(dut.clk) async def run_test_init_sink_pause(dut): tb = TB(dut) await tb.reset() tb.sink.pause = True test_data = bytearray(itertools.islice(itertools.cycle(range(256)), 32)) test_frame = AxiStreamFrame(test_data) await tb.source.send(test_frame) for k in range(64): await RisingEdge(dut.clk) tb.sink.pause = False rx_frame = await tb.sink.recv() assert rx_frame.tdata == test_data assert not rx_frame.tuser assert tb.sink.empty() await RisingEdge(dut.clk) await RisingEdge(dut.clk) async def run_test_init_sink_pause_reset(dut): tb = TB(dut) await tb.reset() tb.sink.pause = True test_data = bytearray(itertools.islice(itertools.cycle(range(256)), 32)) test_frame = AxiStreamFrame(test_data) await tb.source.send(test_frame) for k in range(64): await RisingEdge(dut.clk) await tb.reset() tb.sink.pause = False for k in range(64): await RisingEdge(dut.clk) assert tb.sink.empty() await RisingEdge(dut.clk) await RisingEdge(dut.clk) async def run_test_overflow(dut): tb = TB(dut) await tb.reset() tb.sink.pause = True test_data = bytearray(itertools.islice(itertools.cycle(range(256)), 2048)) test_frame = AxiStreamFrame(test_data) await tb.source.send(test_frame) for k in range(2048): await RisingEdge(dut.clk) tb.sink.pause = False if int(os.getenv("PARAM_DROP_OVERSIZE_FRAME")): for k in range(2048): await RisingEdge(dut.clk) else: rx_frame = await tb.sink.recv() assert rx_frame.tdata == test_data assert not rx_frame.tuser assert tb.sink.empty() await RisingEdge(dut.clk) await RisingEdge(dut.clk) async def run_stress_test(dut, idle_inserter=None, backpressure_inserter=None): tb = TB(dut) byte_lanes = max(tb.source.byte_lanes, tb.sink.byte_lanes) id_count = 2**len(tb.source.bus.tid) cur_id = 1 await tb.reset() tb.set_idle_generator(idle_inserter) tb.set_backpressure_generator(backpressure_inserter) test_frames = [] for k in range(128): length = random.randint(1, byte_lanes*16) test_data = bytearray(itertools.islice(itertools.cycle(range(256)), length)) test_frame = AxiStreamFrame(test_data) test_frame.tid = cur_id test_frame.tdest = cur_id test_frames.append(test_frame) await tb.source.send(test_frame) cur_id = (cur_id + 1) % id_count for test_frame in test_frames: rx_frame = await tb.sink.recv() assert rx_frame.tdata == test_frame.tdata assert rx_frame.tid == test_frame.tid assert rx_frame.tdest == test_frame.tdest assert not rx_frame.tuser assert tb.sink.empty() await RisingEdge(dut.clk) await RisingEdge(dut.clk) def cycle_pause(): return itertools.cycle([1, 1, 1, 0]) def size_list(): data_width = max(len(cocotb.top.m_axis_tdata), len(cocotb.top.s_axis_tdata)) byte_width = data_width // 8 return list(range(1, byte_width*4+1))+[512]+[1]*64 def incrementing_payload(length): return bytearray(itertools.islice(itertools.cycle(range(256)), length)) if cocotb.SIM_NAME: factory = TestFactory(run_test) factory.add_option("payload_lengths", [size_list]) factory.add_option("payload_data", [incrementing_payload]) factory.add_option("idle_inserter", [None, cycle_pause]) factory.add_option("backpressure_inserter", [None, cycle_pause]) factory.generate_tests() for test in [ run_test_tuser_assert, run_test_init_sink_pause, run_test_init_sink_pause_reset, run_test_overflow ]: factory = TestFactory(test) factory.generate_tests() factory = TestFactory(run_stress_test) factory.add_option("idle_inserter", [None, cycle_pause]) factory.add_option("backpressure_inserter", [None, cycle_pause]) factory.generate_tests() # cocotb-test tests_dir = os.path.dirname(__file__) rtl_dir = os.path.abspath(os.path.join(tests_dir, '..', '..', 'rtl')) @pytest.mark.parametrize(("frame_fifo", "drop_oversize_frame", "drop_bad_frame", "drop_when_full"), [(0, 0, 0, 0), (1, 0, 0, 0), (1, 1, 0, 0), (1, 1, 1, 0)]) @pytest.mark.parametrize("m_data_width", [8, 16, 32]) @pytest.mark.parametrize("s_data_width", [8, 16, 32]) def test_axis_fifo_adapter(request, s_data_width, m_data_width, frame_fifo, drop_oversize_frame, drop_bad_frame, drop_when_full): dut = "axis_fifo_adapter" module = os.path.splitext(os.path.basename(__file__))[0] toplevel = dut verilog_sources = [ os.path.join(rtl_dir, f"{dut}.v"), os.path.join(rtl_dir, "axis_fifo.v"), os.path.join(rtl_dir, "axis_adapter.v"), ] parameters = {} parameters['DEPTH'] = 1024 parameters['S_DATA_WIDTH'] = s_data_width parameters['S_KEEP_ENABLE'] = int(parameters['S_DATA_WIDTH'] > 8) parameters['S_KEEP_WIDTH'] = parameters['S_DATA_WIDTH'] // 8 parameters['M_DATA_WIDTH'] = m_data_width parameters['M_KEEP_ENABLE'] = int(parameters['M_DATA_WIDTH'] > 8) parameters['M_KEEP_WIDTH'] = parameters['M_DATA_WIDTH'] // 8 parameters['ID_ENABLE'] = 1 parameters['ID_WIDTH'] = 8 parameters['DEST_ENABLE'] = 1 parameters['DEST_WIDTH'] = 8 parameters['USER_ENABLE'] = 1 parameters['USER_WIDTH'] = 1 parameters['FRAME_FIFO'] = frame_fifo parameters['USER_BAD_FRAME_VALUE'] = 1 parameters['USER_BAD_FRAME_MASK'] = 1 parameters['DROP_OVERSIZE_FRAME'] = drop_oversize_frame parameters['DROP_BAD_FRAME'] = drop_bad_frame parameters['DROP_WHEN_FULL'] = drop_when_full extra_env = {f'PARAM_{k}': str(v) for k, v in parameters.items()} sim_build = os.path.join(tests_dir, "sim_build", request.node.name.replace('[', '-').replace(']', '')) cocotb_test.simulator.run( python_search=[tests_dir], verilog_sources=verilog_sources, toplevel=toplevel, module=module, parameters=parameters, sim_build=sim_build, extra_env=extra_env, )
# The following YAML grammar is LL(1) and is parsed by a recursive descent # parser. # # stream ::= STREAM-START implicit_document? explicit_document* STREAM-END # implicit_document ::= block_node DOCUMENT-END* # explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* # block_node_or_indentless_sequence ::= # ALIAS # | properties (block_content | indentless_block_sequence)? # | block_content # | indentless_block_sequence # block_node ::= ALIAS # | properties block_content? # | block_content # flow_node ::= ALIAS # | properties flow_content? # | flow_content # properties ::= TAG ANCHOR? | ANCHOR TAG? # block_content ::= block_collection | flow_collection | SCALAR # flow_content ::= flow_collection | SCALAR # block_collection ::= block_sequence | block_mapping # flow_collection ::= flow_sequence | flow_mapping # block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END # indentless_sequence ::= (BLOCK-ENTRY block_node?)+ # block_mapping ::= BLOCK-MAPPING_START # ((KEY block_node_or_indentless_sequence?)? # (VALUE block_node_or_indentless_sequence?)?)* # BLOCK-END # flow_sequence ::= FLOW-SEQUENCE-START # (flow_sequence_entry FLOW-ENTRY)* # flow_sequence_entry? # FLOW-SEQUENCE-END # flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? # flow_mapping ::= FLOW-MAPPING-START # (flow_mapping_entry FLOW-ENTRY)* # flow_mapping_entry? # FLOW-MAPPING-END # flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? # # FIRST sets: # # stream: { STREAM-START } # explicit_document: { DIRECTIVE DOCUMENT-START } # implicit_document: FIRST(block_node) # block_node: { ALIAS TAG ANCHOR SCALAR BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START } # flow_node: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START } # block_content: { BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START SCALAR } # flow_content: { FLOW-SEQUENCE-START FLOW-MAPPING-START SCALAR } # block_collection: { BLOCK-SEQUENCE-START BLOCK-MAPPING-START } # flow_collection: { FLOW-SEQUENCE-START FLOW-MAPPING-START } # block_sequence: { BLOCK-SEQUENCE-START } # block_mapping: { BLOCK-MAPPING-START } # block_node_or_indentless_sequence: { ALIAS ANCHOR TAG SCALAR BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START BLOCK-ENTRY } # indentless_sequence: { ENTRY } # flow_collection: { FLOW-SEQUENCE-START FLOW-MAPPING-START } # flow_sequence: { FLOW-SEQUENCE-START } # flow_mapping: { FLOW-MAPPING-START } # flow_sequence_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY } # flow_mapping_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY } __all__ = ['Parser', 'ParserError'] from error import MarkedYAMLError from tokens import * from events import * from scanner import * class ParserError(MarkedYAMLError): pass class Parser(object): # Since writing a recursive-descendant parser is a straightforward task, we # do not give many comments here. # Note that we use Python generators. If you rewrite the parser in another # language, you may replace all 'yield'-s with event handler calls. DEFAULT_TAGS = { u'!': u'!', u'!!': u'tag:yaml.org,2002:', } def __init__(self): self.current_event = None self.yaml_version = None self.tag_handles = {} self.states = [] self.marks = [] self.state = self.parse_stream_start def check_event(self, *choices): # Check the type of the next event. if self.current_event is None: if self.state: self.current_event = self.state() if self.current_event is not None: if not choices: return True for choice in choices: if isinstance(self.current_event, choice): return True return False def peek_event(self): # Get the next event. if self.current_event is None: if self.state: self.current_event = self.state() return self.current_event def get_event(self): # Get the next event and proceed further. if self.current_event is None: if self.state: self.current_event = self.state() value = self.current_event self.current_event = None return value # stream ::= STREAM-START implicit_document? explicit_document* STREAM-END # implicit_document ::= block_node DOCUMENT-END* # explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* def parse_stream_start(self): # Parse the stream start. token = self.get_token() event = StreamStartEvent(token.start_mark, token.end_mark, encoding=token.encoding) # Prepare the next state. self.state = self.parse_implicit_document_start return event def parse_implicit_document_start(self): # Parse an implicit document. if not self.check_token(DirectiveToken, DocumentStartToken, StreamEndToken): self.tag_handles = self.DEFAULT_TAGS token = self.peek_token() start_mark = end_mark = token.start_mark event = DocumentStartEvent(start_mark, end_mark, explicit=False) # Prepare the next state. self.states.append(self.parse_document_end) self.state = self.parse_block_node return event else: return self.parse_document_start() def parse_document_start(self): # Parse an explicit document. if not self.check_token(StreamEndToken): token = self.peek_token() start_mark = token.start_mark version, tags = self.process_directives() if not self.check_token(DocumentStartToken): raise ParserError(None, None, "expected '<document start>', but found %r" % self.peek_token().id, self.peek_token().start_mark) token = self.get_token() end_mark = token.end_mark event = DocumentStartEvent(start_mark, end_mark, explicit=True, version=version, tags=tags) self.states.append(self.parse_document_end) self.state = self.parse_document_content else: # Parse the end of the stream. token = self.get_token() event = StreamEndEvent(token.start_mark, token.end_mark) assert not self.states assert not self.marks self.state = None return event def parse_document_end(self): # Parse the document end. token = self.peek_token() start_mark = end_mark = token.start_mark explicit = False while self.check_token(DocumentEndToken): token = self.get_token() end_mark = token.end_mark explicit = True event = DocumentEndEvent(start_mark, end_mark, explicit=explicit) # Prepare the next state. self.state = self.parse_document_start return event def parse_document_content(self): if self.check_token(DirectiveToken, DocumentStartToken, DocumentEndToken, StreamEndToken): event = self.process_empty_scalar(self.peek_token().start_mark) self.state = self.states.pop() return event else: return self.parse_block_node() def process_directives(self): self.yaml_version = None self.tag_handles = {} while self.check_token(DirectiveToken): token = self.get_token() if token.name == u'YAML': if self.yaml_version is not None: raise ParserError(None, None, "found duplicate YAML directive", token.start_mark) major, minor = token.value if major != 1: raise ParserError(None, None, "found incompatible YAML document (version 1.* is required)", token.start_mark) self.yaml_version = token.value elif token.name == u'TAG': handle, prefix = token.value if handle in self.tag_handles: raise ParserError(None, None, "duplicate tag handle %r" % handle.encode('utf-8'), token.start_mark) self.tag_handles[handle] = prefix if self.tag_handles: value = self.yaml_version, self.tag_handles.copy() else: value = self.yaml_version, None for key in self.DEFAULT_TAGS: if key not in self.tag_handles: self.tag_handles[key] = self.DEFAULT_TAGS[key] return value # block_node_or_indentless_sequence ::= ALIAS # | properties (block_content | indentless_block_sequence)? # | block_content # | indentless_block_sequence # block_node ::= ALIAS # | properties block_content? # | block_content # flow_node ::= ALIAS # | properties flow_content? # | flow_content # properties ::= TAG ANCHOR? | ANCHOR TAG? # block_content ::= block_collection | flow_collection | SCALAR # flow_content ::= flow_collection | SCALAR # block_collection ::= block_sequence | block_mapping # flow_collection ::= flow_sequence | flow_mapping def parse_block_node(self): return self.parse_node(block=True) def parse_flow_node(self): return self.parse_node() def parse_block_node_or_indentless_sequence(self): return self.parse_node(block=True, indentless_sequence=True) def parse_node(self, block=False, indentless_sequence=False): if self.check_token(AliasToken): token = self.get_token() event = AliasEvent(token.value, token.start_mark, token.end_mark) self.state = self.states.pop() else: anchor = None tag = None start_mark = end_mark = tag_mark = None if self.check_token(AnchorToken): token = self.get_token() start_mark = token.start_mark end_mark = token.end_mark anchor = token.value if self.check_token(TagToken): token = self.get_token() tag_mark = token.start_mark end_mark = token.end_mark tag = token.value elif self.check_token(TagToken): token = self.get_token() start_mark = tag_mark = token.start_mark end_mark = token.end_mark tag = token.value if self.check_token(AnchorToken): token = self.get_token() end_mark = token.end_mark anchor = token.value if tag is not None and tag != u'!': handle, suffix = tag if handle is not None: if handle not in self.tag_handles: raise ParserError("while parsing a node", start_mark, "found undefined tag handle %r" % handle.encode('utf-8'), tag_mark) tag = self.tag_handles[handle]+suffix else: tag = suffix #if tag == u'!': # raise ParserError("while parsing a node", start_mark, # "found non-specific tag '!'", tag_mark, # "Please check 'http://pyyaml.org/wiki/YAMLNonSpecificTag' and share your opinion.") if start_mark is None: start_mark = end_mark = self.peek_token().start_mark event = None implicit = (tag is None or tag == u'!') if indentless_sequence and self.check_token(BlockEntryToken): end_mark = self.peek_token().end_mark event = SequenceStartEvent(anchor, tag, implicit, start_mark, end_mark) self.state = self.parse_indentless_sequence_entry else: if self.check_token(ScalarToken): token = self.get_token() end_mark = token.end_mark if (token.plain and tag is None) or tag == u'!': implicit = (True, False) elif tag is None: implicit = (False, True) else: implicit = (False, False) event = ScalarEvent(anchor, tag, implicit, token.value, start_mark, end_mark, style=token.style) self.state = self.states.pop() elif self.check_token(FlowSequenceStartToken): end_mark = self.peek_token().end_mark event = SequenceStartEvent(anchor, tag, implicit, start_mark, end_mark, flow_style=True) self.state = self.parse_flow_sequence_first_entry elif self.check_token(FlowMappingStartToken): end_mark = self.peek_token().end_mark event = MappingStartEvent(anchor, tag, implicit, start_mark, end_mark, flow_style=True) self.state = self.parse_flow_mapping_first_key elif block and self.check_token(BlockSequenceStartToken): end_mark = self.peek_token().start_mark event = SequenceStartEvent(anchor, tag, implicit, start_mark, end_mark, flow_style=False) self.state = self.parse_block_sequence_first_entry elif block and self.check_token(BlockMappingStartToken): end_mark = self.peek_token().start_mark event = MappingStartEvent(anchor, tag, implicit, start_mark, end_mark, flow_style=False) self.state = self.parse_block_mapping_first_key elif anchor is not None or tag is not None: # Empty scalars are allowed even if a tag or an anchor is # specified. event = ScalarEvent(anchor, tag, (implicit, False), u'', start_mark, end_mark) self.state = self.states.pop() else: if block: node = 'block' else: node = 'flow' token = self.peek_token() raise ParserError("while parsing a %s node" % node, start_mark, "expected the node content, but found %r" % token.id, token.start_mark) return event # block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END def parse_block_sequence_first_entry(self): token = self.get_token() self.marks.append(token.start_mark) return self.parse_block_sequence_entry() def parse_block_sequence_entry(self): if self.check_token(BlockEntryToken): token = self.get_token() if not self.check_token(BlockEntryToken, BlockEndToken): self.states.append(self.parse_block_sequence_entry) return self.parse_block_node() else: self.state = self.parse_block_sequence_entry return self.process_empty_scalar(token.end_mark) if not self.check_token(BlockEndToken): token = self.peek_token() raise ParserError("while parsing a block collection", self.marks[-1], "expected <block end>, but found %r" % token.id, token.start_mark) token = self.get_token() event = SequenceEndEvent(token.start_mark, token.end_mark) self.state = self.states.pop() self.marks.pop() return event # indentless_sequence ::= (BLOCK-ENTRY block_node?)+ def parse_indentless_sequence_entry(self): if self.check_token(BlockEntryToken): token = self.get_token() if not self.check_token(BlockEntryToken, KeyToken, ValueToken, BlockEndToken): self.states.append(self.parse_indentless_sequence_entry) return self.parse_block_node() else: self.state = self.parse_indentless_sequence_entry return self.process_empty_scalar(token.end_mark) token = self.peek_token() event = SequenceEndEvent(token.start_mark, token.start_mark) self.state = self.states.pop() return event # block_mapping ::= BLOCK-MAPPING_START # ((KEY block_node_or_indentless_sequence?)? # (VALUE block_node_or_indentless_sequence?)?)* # BLOCK-END def parse_block_mapping_first_key(self): token = self.get_token() self.marks.append(token.start_mark) return self.parse_block_mapping_key() def parse_block_mapping_key(self): if self.check_token(KeyToken): token = self.get_token() if not self.check_token(KeyToken, ValueToken, BlockEndToken): self.states.append(self.parse_block_mapping_value) return self.parse_block_node_or_indentless_sequence() else: self.state = self.parse_block_mapping_value return self.process_empty_scalar(token.end_mark) if not self.check_token(BlockEndToken): token = self.peek_token() raise ParserError("while parsing a block mapping", self.marks[-1], "expected <block end>, but found %r" % token.id, token.start_mark) token = self.get_token() event = MappingEndEvent(token.start_mark, token.end_mark) self.state = self.states.pop() self.marks.pop() return event def parse_block_mapping_value(self): if self.check_token(ValueToken): token = self.get_token() if not self.check_token(KeyToken, ValueToken, BlockEndToken): self.states.append(self.parse_block_mapping_key) return self.parse_block_node_or_indentless_sequence() else: self.state = self.parse_block_mapping_key return self.process_empty_scalar(token.end_mark) else: self.state = self.parse_block_mapping_key token = self.peek_token() return self.process_empty_scalar(token.start_mark) # flow_sequence ::= FLOW-SEQUENCE-START # (flow_sequence_entry FLOW-ENTRY)* # flow_sequence_entry? # FLOW-SEQUENCE-END # flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? # # Note that while production rules for both flow_sequence_entry and # flow_mapping_entry are equal, their interpretations are different. # For `flow_sequence_entry`, the part `KEY flow_node? (VALUE flow_node?)?` # generate an inline mapping (set syntax). def parse_flow_sequence_first_entry(self): token = self.get_token() self.marks.append(token.start_mark) return self.parse_flow_sequence_entry(first=True) def parse_flow_sequence_entry(self, first=False): if not self.check_token(FlowSequenceEndToken): if not first: if self.check_token(FlowEntryToken): self.get_token() else: token = self.peek_token() raise ParserError("while parsing a flow sequence", self.marks[-1], "expected ',' or ']', but got %r" % token.id, token.start_mark) if self.check_token(KeyToken): token = self.peek_token() event = MappingStartEvent(None, None, True, token.start_mark, token.end_mark, flow_style=True) self.state = self.parse_flow_sequence_entry_mapping_key return event elif not self.check_token(FlowSequenceEndToken): self.states.append(self.parse_flow_sequence_entry) return self.parse_flow_node() token = self.get_token() event = SequenceEndEvent(token.start_mark, token.end_mark) self.state = self.states.pop() self.marks.pop() return event def parse_flow_sequence_entry_mapping_key(self): token = self.get_token() if not self.check_token(ValueToken, FlowEntryToken, FlowSequenceEndToken): self.states.append(self.parse_flow_sequence_entry_mapping_value) return self.parse_flow_node() else: self.state = self.parse_flow_sequence_entry_mapping_value return self.process_empty_scalar(token.end_mark) def parse_flow_sequence_entry_mapping_value(self): if self.check_token(ValueToken): token = self.get_token() if not self.check_token(FlowEntryToken, FlowSequenceEndToken): self.states.append(self.parse_flow_sequence_entry_mapping_end) return self.parse_flow_node() else: self.state = self.parse_flow_sequence_entry_mapping_end return self.process_empty_scalar(token.end_mark) else: self.state = self.parse_flow_sequence_entry_mapping_end token = self.peek_token() return self.process_empty_scalar(token.start_mark) def parse_flow_sequence_entry_mapping_end(self): self.state = self.parse_flow_sequence_entry token = self.peek_token() return MappingEndEvent(token.start_mark, token.start_mark) # flow_mapping ::= FLOW-MAPPING-START # (flow_mapping_entry FLOW-ENTRY)* # flow_mapping_entry? # FLOW-MAPPING-END # flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? def parse_flow_mapping_first_key(self): token = self.get_token() self.marks.append(token.start_mark) return self.parse_flow_mapping_key(first=True) def parse_flow_mapping_key(self, first=False): if not self.check_token(FlowMappingEndToken): if not first: if self.check_token(FlowEntryToken): self.get_token() else: token = self.peek_token() raise ParserError("while parsing a flow mapping", self.marks[-1], "expected ',' or '}', but got %r" % token.id, token.start_mark) if self.check_token(KeyToken): token = self.get_token() if not self.check_token(ValueToken, FlowEntryToken, FlowMappingEndToken): self.states.append(self.parse_flow_mapping_value) return self.parse_flow_node() else: self.state = self.parse_flow_mapping_value return self.process_empty_scalar(token.end_mark) elif not self.check_token(FlowMappingEndToken): self.states.append(self.parse_flow_mapping_empty_value) return self.parse_flow_node() token = self.get_token() event = MappingEndEvent(token.start_mark, token.end_mark) self.state = self.states.pop() self.marks.pop() return event def parse_flow_mapping_value(self): if self.check_token(ValueToken): token = self.get_token() if not self.check_token(FlowEntryToken, FlowMappingEndToken): self.states.append(self.parse_flow_mapping_key) return self.parse_flow_node() else: self.state = self.parse_flow_mapping_key return self.process_empty_scalar(token.end_mark) else: self.state = self.parse_flow_mapping_key token = self.peek_token() return self.process_empty_scalar(token.start_mark) def parse_flow_mapping_empty_value(self): self.state = self.parse_flow_mapping_key return self.process_empty_scalar(self.peek_token().start_mark) def process_empty_scalar(self, mark): return ScalarEvent(None, None, (True, False), u'', mark, mark)
# Copyright 2014 Rackspace # # 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 octavia_lib.common import constants as lib_consts ############################################################################## # Constants common to the provider drivers moved to # octavia_lib.common.constants # These are deprecated, to be removed in the 'U' release ############################################################################## # 'loadbalancers' LOADBALANCERS = lib_consts.LOADBALANCERS # 'listeners' LISTENERS = lib_consts.LISTENERS # 'pools' POOLS = lib_consts.POOLS # HEALTHMONITORS = 'healthmonitors' HEALTHMONITORS = lib_consts.HEALTHMONITORS # 'members' MEMBERS = lib_consts.MEMBERS # 'l7policies' L7POLICIES = lib_consts.L7POLICIES # 'l7rules' L7RULES = lib_consts.L7RULES # 'PING' HEALTH_MONITOR_PING = lib_consts.HEALTH_MONITOR_PING # 'TCP' HEALTH_MONITOR_TCP = lib_consts.HEALTH_MONITOR_TCP # 'HTTP' HEALTH_MONITOR_HTTP = lib_consts.HEALTH_MONITOR_HTTP # 'HTTPS' HEALTH_MONITOR_HTTPS = lib_consts.HEALTH_MONITOR_HTTPS # 'TLS-HELLO' HEALTH_MONITOR_TLS_HELLO = lib_consts.HEALTH_MONITOR_TLS_HELLO # 'UDP-CONNECT' HEALTH_MONITOR_UDP_CONNECT = lib_consts.HEALTH_MONITOR_UDP_CONNECT SUPPORTED_HEALTH_MONITOR_TYPES = lib_consts.SUPPORTED_HEALTH_MONITOR_TYPES # 'GET' HEALTH_MONITOR_HTTP_METHOD_GET = lib_consts.HEALTH_MONITOR_HTTP_METHOD_GET # 'HEAD' HEALTH_MONITOR_HTTP_METHOD_HEAD = lib_consts.HEALTH_MONITOR_HTTP_METHOD_HEAD # 'POST' HEALTH_MONITOR_HTTP_METHOD_POST = lib_consts.HEALTH_MONITOR_HTTP_METHOD_POST # 'PUT' HEALTH_MONITOR_HTTP_METHOD_PUT = lib_consts.HEALTH_MONITOR_HTTP_METHOD_PUT # 'DELETE' HEALTH_MONITOR_HTTP_METHOD_DELETE = ( lib_consts.HEALTH_MONITOR_HTTP_METHOD_DELETE) # 'TRACE' HEALTH_MONITOR_HTTP_METHOD_TRACE = lib_consts.HEALTH_MONITOR_HTTP_METHOD_TRACE # 'OPTIONS' HEALTH_MONITOR_HTTP_METHOD_OPTIONS = ( lib_consts.HEALTH_MONITOR_HTTP_METHOD_OPTIONS) # 'CONNECT' HEALTH_MONITOR_HTTP_METHOD_CONNECT = ( lib_consts.HEALTH_MONITOR_HTTP_METHOD_CONNECT) # 'PATCH' HEALTH_MONITOR_HTTP_METHOD_PATCH = lib_consts.HEALTH_MONITOR_HTTP_METHOD_PATCH SUPPORTED_HEALTH_MONITOR_HTTP_METHODS = ( lib_consts.SUPPORTED_HEALTH_MONITOR_HTTP_METHODS) # 'REJECT' L7POLICY_ACTION_REJECT = lib_consts.L7POLICY_ACTION_REJECT # 'REDIRECT_TO_URL' L7POLICY_ACTION_REDIRECT_TO_URL = lib_consts.L7POLICY_ACTION_REDIRECT_TO_URL # 'REDIRECT_TO_POOL' L7POLICY_ACTION_REDIRECT_TO_POOL = lib_consts.L7POLICY_ACTION_REDIRECT_TO_POOL # 'REDIRECT_PREFIX' L7POLICY_ACTION_REDIRECT_PREFIX = lib_consts.L7POLICY_ACTION_REDIRECT_PREFIX SUPPORTED_L7POLICY_ACTIONS = lib_consts.SUPPORTED_L7POLICY_ACTIONS # 'REGEX' L7RULE_COMPARE_TYPE_REGEX = lib_consts.L7RULE_COMPARE_TYPE_REGEX # 'STARTS_WITH' L7RULE_COMPARE_TYPE_STARTS_WITH = lib_consts.L7RULE_COMPARE_TYPE_STARTS_WITH # 'ENDS_WITH' L7RULE_COMPARE_TYPE_ENDS_WITH = lib_consts.L7RULE_COMPARE_TYPE_ENDS_WITH # 'CONTAINS' L7RULE_COMPARE_TYPE_CONTAINS = lib_consts.L7RULE_COMPARE_TYPE_CONTAINS # 'EQUAL_TO' L7RULE_COMPARE_TYPE_EQUAL_TO = lib_consts.L7RULE_COMPARE_TYPE_EQUAL_TO SUPPORTED_L7RULE_COMPARE_TYPES = lib_consts.SUPPORTED_L7RULE_COMPARE_TYPES # 'HOST_NAME' L7RULE_TYPE_HOST_NAME = lib_consts.L7RULE_TYPE_HOST_NAME # 'PATH' L7RULE_TYPE_PATH = lib_consts.L7RULE_TYPE_PATH # 'FILE_TYPE' L7RULE_TYPE_FILE_TYPE = lib_consts.L7RULE_TYPE_FILE_TYPE # 'HEADER' L7RULE_TYPE_HEADER = lib_consts.L7RULE_TYPE_HEADER # 'COOKIE' L7RULE_TYPE_COOKIE = lib_consts.L7RULE_TYPE_COOKIE # 'SSL_CONN_HAS_CERT' L7RULE_TYPE_SSL_CONN_HAS_CERT = lib_consts.L7RULE_TYPE_SSL_CONN_HAS_CERT # 'SSL_VERIFY_RESULT' L7RULE_TYPE_SSL_VERIFY_RESULT = lib_consts.L7RULE_TYPE_SSL_VERIFY_RESULT # 'SSL_DN_FIELD' L7RULE_TYPE_SSL_DN_FIELD = lib_consts.L7RULE_TYPE_SSL_DN_FIELD SUPPORTED_L7RULE_TYPES = lib_consts.SUPPORTED_L7RULE_TYPES # 'ROUND_ROBIN' LB_ALGORITHM_ROUND_ROBIN = lib_consts.LB_ALGORITHM_ROUND_ROBIN # 'LEAST_CONNECTIONS' LB_ALGORITHM_LEAST_CONNECTIONS = lib_consts.LB_ALGORITHM_LEAST_CONNECTIONS # 'SOURCE_IP' LB_ALGORITHM_SOURCE_IP = lib_consts.LB_ALGORITHM_SOURCE_IP SUPPORTED_LB_ALGORITHMS = lib_consts.SUPPORTED_LB_ALGORITHMS # 'operating_status' OPERATING_STATUS = lib_consts.OPERATING_STATUS # 'ONLINE' ONLINE = lib_consts.ONLINE # 'OFFLINE' OFFLINE = lib_consts.OFFLINE # 'DEGRADED' DEGRADED = lib_consts.DEGRADED # 'ERROR' ERROR = lib_consts.ERROR # 'DRAINING' DRAINING = lib_consts.DRAINING # 'NO_MONITOR' NO_MONITOR = lib_consts.NO_MONITOR # 'operating_status' SUPPORTED_OPERATING_STATUSES = lib_consts.SUPPORTED_OPERATING_STATUSES # 'TCP' PROTOCOL_TCP = lib_consts.PROTOCOL_TCP # 'UDP' PROTOCOL_UDP = lib_consts.PROTOCOL_UDP # 'HTTP' PROTOCOL_HTTP = lib_consts.PROTOCOL_HTTP # 'HTTPS' PROTOCOL_HTTPS = lib_consts.PROTOCOL_HTTPS # 'TERMINATED_HTTPS' PROTOCOL_TERMINATED_HTTPS = lib_consts.PROTOCOL_TERMINATED_HTTPS # 'PROXY' PROTOCOL_PROXY = lib_consts.PROTOCOL_PROXY SUPPORTED_PROTOCOLS = lib_consts.SUPPORTED_PROTOCOLS # 'PROMETHEUS' PROTOCOL_PROMETHEUS = lib_consts.PROTOCOL_PROMETHEUS # 'provisioning_status' PROVISIONING_STATUS = lib_consts.PROVISIONING_STATUS # Amphora has been allocated to a load balancer 'ALLOCATED' AMPHORA_ALLOCATED = lib_consts.AMPHORA_ALLOCATED # Amphora is being built 'BOOTING' AMPHORA_BOOTING = lib_consts.AMPHORA_BOOTING # Amphora is ready to be allocated to a load balancer 'READY' AMPHORA_READY = lib_consts.AMPHORA_READY # 'ACTIVE' ACTIVE = lib_consts.ACTIVE # 'PENDING_DELETE' PENDING_DELETE = lib_consts.PENDING_DELETE # 'PENDING_UPDATE' PENDING_UPDATE = lib_consts.PENDING_UPDATE # 'PENDING_CREATE' PENDING_CREATE = lib_consts.PENDING_CREATE # 'DELETED' DELETED = lib_consts.DELETED SUPPORTED_PROVISIONING_STATUSES = lib_consts.SUPPORTED_PROVISIONING_STATUSES # 'SOURCE_IP' SESSION_PERSISTENCE_SOURCE_IP = lib_consts.SESSION_PERSISTENCE_SOURCE_IP # 'HTTP_COOKIE' SESSION_PERSISTENCE_HTTP_COOKIE = lib_consts.SESSION_PERSISTENCE_HTTP_COOKIE # 'APP_COOKIE' SESSION_PERSISTENCE_APP_COOKIE = lib_consts.SESSION_PERSISTENCE_APP_COOKIE SUPPORTED_SP_TYPES = lib_consts.SUPPORTED_SP_TYPES # List of HTTP headers which are supported for insertion SUPPORTED_HTTP_HEADERS = lib_consts.SUPPORTED_HTTP_HEADERS # List of SSL headers for client certificate SUPPORTED_SSL_HEADERS = lib_consts.SUPPORTED_SSL_HEADERS ############################################################################### HEALTH_MONITOR_DEFAULT_EXPECTED_CODES = '200' HEALTH_MONITOR_HTTP_DEFAULT_METHOD = lib_consts.HEALTH_MONITOR_HTTP_METHOD_GET HEALTH_MONITOR_DEFAULT_URL_PATH = '/' TYPE = 'type' URL_PATH = 'url_path' HTTP_METHOD = 'http_method' HTTP_VERSION = 'http_version' EXPECTED_CODES = 'expected_codes' DELAY = 'delay' TIMEOUT = 'timeout' MAX_RETRIES = 'max_retries' MAX_RETRIES_DOWN = 'max_retries_down' RISE_THRESHOLD = 'rise_threshold' DOMAIN_NAME = 'domain_name' UPDATE_STATS = 'UPDATE_STATS' UPDATE_HEALTH = 'UPDATE_HEALTH' VALID_LISTENER_POOL_PROTOCOL_MAP = { PROTOCOL_TCP: [PROTOCOL_HTTP, PROTOCOL_HTTPS, PROTOCOL_PROXY, lib_consts.PROTOCOL_PROXYV2, PROTOCOL_TCP], PROTOCOL_HTTP: [PROTOCOL_HTTP, PROTOCOL_PROXY, lib_consts.PROTOCOL_PROXYV2], PROTOCOL_HTTPS: [PROTOCOL_HTTPS, PROTOCOL_PROXY, lib_consts.PROTOCOL_PROXYV2, PROTOCOL_TCP], PROTOCOL_TERMINATED_HTTPS: [PROTOCOL_HTTP, PROTOCOL_PROXY, lib_consts.PROTOCOL_PROXYV2], PROTOCOL_UDP: [PROTOCOL_UDP], lib_consts.PROTOCOL_SCTP: [lib_consts.PROTOCOL_SCTP], lib_consts.PROTOCOL_PROMETHEUS: []} # API Integer Ranges MIN_PORT_NUMBER = 1 MAX_PORT_NUMBER = 65535 DEFAULT_CONNECTION_LIMIT = -1 MIN_CONNECTION_LIMIT = -1 DEFAULT_WEIGHT = 1 MIN_WEIGHT = 0 MAX_WEIGHT = 256 DEFAULT_MAX_RETRIES_DOWN = 3 MIN_HM_RETRIES = 1 MAX_HM_RETRIES = 10 # 24 days: days d h m ms MAX_TIMEOUT = 24 * 24 * 60 * 60 * 1000 MIN_TIMEOUT = 0 DEFAULT_TIMEOUT_CLIENT_DATA = 50000 DEFAULT_TIMEOUT_MEMBER_CONNECT = 5000 DEFAULT_TIMEOUT_MEMBER_DATA = 50000 DEFAULT_TIMEOUT_TCP_INSPECT = 0 MUTABLE_STATUSES = (lib_consts.ACTIVE,) DELETABLE_STATUSES = (lib_consts.ACTIVE, lib_consts.ERROR) FAILOVERABLE_STATUSES = (lib_consts.ACTIVE, lib_consts.ERROR) # Note: The database Amphora table has a foreign key constraint against # the provisioning_status table SUPPORTED_AMPHORA_STATUSES = ( lib_consts.AMPHORA_ALLOCATED, lib_consts.AMPHORA_BOOTING, lib_consts.ERROR, lib_consts.AMPHORA_READY, lib_consts.DELETED, lib_consts.PENDING_CREATE, lib_consts.PENDING_DELETE) AMPHORA_VM = 'VM' SUPPORTED_AMPHORA_TYPES = (AMPHORA_VM,) DISTINGUISHED_NAME_FIELD_REGEX = lib_consts.DISTINGUISHED_NAME_FIELD_REGEX # For redirect, only codes 301, 302, 303, 307 and 308 are # supported. SUPPORTED_L7POLICY_REDIRECT_HTTP_CODES = [301, 302, 303, 307, 308] SUPPORTED_HTTP_VERSIONS = [1.0, 1.1] MIN_POLICY_POSITION = 1 # Largest a 32-bit integer can be, which is a limitation # here if you're using MySQL, as most probably are. This just needs # to be larger than any existing rule position numbers which will # definitely be the case with 2147483647 MAX_POLICY_POSITION = 2147483647 # Testing showed haproxy config failed to parse after more than # 53 rules per policy MAX_L7RULES_PER_L7POLICY = 50 # See RFCs 2616, 2965, 6265, 7230: Should match characters valid in a # http header or cookie name. HTTP_HEADER_NAME_REGEX = r'\A[a-zA-Z0-9!#$%&\'*+-.^_`|~]+\Z' # See RFCs 2616, 2965, 6265: Should match characters valid in a cookie value. HTTP_COOKIE_VALUE_REGEX = r'\A[a-zA-Z0-9!#$%&\'()*+-./:<=>?@[\]^_`{|}~]+\Z' # See RFC 7230: Should match characters valid in a header value. HTTP_HEADER_VALUE_REGEX = (r'\A[a-zA-Z0-9' r'!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~\\]+\Z') # Also in RFC 7230: Should match characters valid in a header value # when quoted with double quotes. HTTP_QUOTED_HEADER_VALUE_REGEX = (r'\A"[a-zA-Z0-9 \t' r'!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~\\]*"\Z') DOMAIN_NAME_REGEX = ( r'^(?=.{1,253}\.?$)(?:(?!-|[^.]+_)[A-Za-z0-9-_]{1,63}(?<!-)(?:\.|$))+$') # TaskFlow SUPPORTED_TASKFLOW_ENGINE_TYPES = ['serial', 'parallel'] # Task/Flow constants ACTIVE_CONNECTIONS = 'active_connections' ADD_NICS = 'add_nics' ADDED_PORTS = 'added_ports' ADMIN_STATE_UP = 'admin_state_up' ALLOWED_ADDRESS_PAIRS = 'allowed_address_pairs' AMP_DATA = 'amp_data' AMP_VRRP_INT = 'amp_vrrp_int' AMPHORA = 'amphora' AMPHORA_DICT = 'amphora_dict' AMPHORA_ID = 'amphora_id' AMPHORA_INDEX = 'amphora_index' AMPHORA_NETWORK_CONFIG = 'amphora_network_config' AMPHORAE = 'amphorae' AMPHORAE_NETWORK_CONFIG = 'amphorae_network_config' AMPS_DATA = 'amps_data' ANTI_AFFINITY = 'anti-affinity' ATTEMPT_NUMBER = 'attempt_number' BASE_PORT = 'base_port' BYTES_IN = 'bytes_in' BYTES_OUT = 'bytes_out' CACHED_ZONE = 'cached_zone' CA_TLS_CERTIFICATE_ID = 'ca_tls_certificate_id' CIDR = 'cidr' CLIENT_CA_TLS_CERTIFICATE_ID = 'client_ca_tls_certificate_id' CLIENT_CRL_CONTAINER_ID = 'client_crl_container_id' COMPUTE_ID = 'compute_id' COMPUTE_OBJ = 'compute_obj' COMPUTE_ZONE = 'compute_zone' CONN_MAX_RETRIES = 'conn_max_retries' CONN_RETRY_INTERVAL = 'conn_retry_interval' CREATED_AT = 'created_at' CRL_CONTAINER_ID = 'crl_container_id' DEFAULT_TLS_CONTAINER_DATA = 'default_tls_container_data' DELETE_NICS = 'delete_nics' DELTA = 'delta' DELTAS = 'deltas' DESCRIPTION = 'description' DEVICE_OWNER = 'device_owner' ENABLED = 'enabled' FAILED_AMP_VRRP_PORT_ID = 'failed_amp_vrrp_port_id' FAILED_AMPHORA = 'failed_amphora' FAILOVER_AMPHORA = 'failover_amphora' FAILOVER_AMPHORA_ID = 'failover_amphora_id' FIELDS = 'fields' FIXED_IPS = 'fixed_ips' FLAVOR_ID = 'flavor_id' HA_IP = 'ha_ip' HA_PORT_ID = 'ha_port_id' HEALTH_MON = 'health_mon' HEALTH_MONITOR = 'health_monitor' HEALTH_MONITOR_ID = 'health_monitor_id' HEALTHMONITOR_ID = 'healthmonitor_id' HEALTH_MONITOR_UPDATES = 'health_monitor_updates' ID = 'id' IMAGE_ID = 'image_id' IP_ADDRESS = 'ip_address' IPV6_ICMP = 'ipv6-icmp' LB_NETWORK_IP = 'lb_network_ip' L7POLICY = 'l7policy' L7POLICY_ID = 'l7policy_id' L7POLICY_UPDATES = 'l7policy_updates' L7RULE = 'l7rule' L7RULE_ID = 'l7rule_id' L7RULE_UPDATES = 'l7rule_updates' LISTENER = 'listener' LISTENER_ID = 'listener_id' LISTENER_UPDATES = 'listener_updates' LOADBALANCER = 'loadbalancer' LOADBALANCER_ID = 'loadbalancer_id' LOAD_BALANCER_ID = 'load_balancer_id' LOAD_BALANCER_UPDATES = 'load_balancer_updates' MANAGEMENT_NETWORK = 'management_network' MEMBER = 'member' MEMBER_ID = 'member_id' MEMBER_PORTS = 'member_ports' MEMBER_UPDATES = 'member_updates' MESSAGE = 'message' NAME = 'name' NETWORK = 'network' NETWORK_ID = 'network_id' NICS = 'nics' OBJECT = 'object' ORIGINAL_HEALTH_MONITOR = 'original_health_monitor' ORIGINAL_L7POLICY = 'original_l7policy' ORIGINAL_L7RULE = 'original_l7rule' ORIGINAL_LISTENER = 'original_listener' ORIGINAL_LOADBALANCER = 'original_load_balancer' ORIGINAL_MEMBER = 'original_member' ORIGINAL_POOL = 'original_pool' PASSIVE_FAILURE = 'passive_failure' PEER_PORT = 'peer_port' POOL = 'pool' POOL_CHILD_COUNT = 'pool_child_count' POOL_ID = 'pool_id' POOL_UPDATES = 'pool_updates' PORT = 'port' PORT_ID = 'port_id' PORTS = 'ports' PROJECT_ID = 'project_id' PROVIDER = 'provider' PROVIDER_NAME = 'provider_name' QOS_POLICY_ID = 'qos_policy_id' REDIRECT_POOL = 'redirect_pool' REQ_CONN_TIMEOUT = 'req_conn_timeout' REQ_READ_TIMEOUT = 'req_read_timeout' REQUEST_ERRORS = 'request_errors' ROLE = 'role' SECURITY_GROUPS = 'security_groups' SECURITY_GROUP_RULES = 'security_group_rules' SERVER_GROUP_ID = 'server_group_id' SERVER_PEM = 'server_pem' SNI_CONTAINER_DATA = 'sni_container_data' SNI_CONTAINERS = 'sni_containers' SOFT_ANTI_AFFINITY = 'soft-anti-affinity' STATUS = 'status' STATUS_CODE = 'status_code' SUBNET = 'subnet' SUBNET_ID = 'subnet_id' TAGS = 'tags' TENANT_ID = 'tenant_id' TIMEOUT_DICT = 'timeout_dict' TLS_CERTIFICATE_ID = 'tls_certificate_id' TLS_CONTAINER_ID = 'tls_container_id' TOPOLOGY = 'topology' TOTAL_CONNECTIONS = 'total_connections' UPDATED_AT = 'updated_at' UPDATE_DICT = 'update_dict' VALID_VIP_NETWORKS = 'valid_vip_networks' VIP = 'vip' VIP_ADDRESS = 'vip_address' VIP_NETWORK = 'vip_network' VIP_PORT_ID = 'vip_port_id' VIP_QOS_POLICY_ID = 'vip_qos_policy_id' VIP_SG_ID = 'vip_sg_id' VIP_SUBNET = 'vip_subnet' VIP_SUBNET_ID = 'vip_subnet_id' VRRP_ID = 'vrrp_id' VRRP_IP = 'vrrp_ip' VRRP_GROUP = 'vrrp_group' VRRP_PORT = 'vrrp_port' VRRP_PORT_ID = 'vrrp_port_id' VRRP_PRIORITY = 'vrrp_priority' # Taskflow flow and task names CERT_ROTATE_AMPHORA_FLOW = 'octavia-cert-rotate-amphora-flow' CREATE_AMPHORA_FLOW = 'octavia-create-amphora-flow' CREATE_AMPHORA_RETRY_SUBFLOW = 'octavia-create-amphora-retry-subflow' CREATE_AMPHORA_FOR_LB_FLOW = 'octavia-create-amp-for-lb-flow' CREATE_HEALTH_MONITOR_FLOW = 'octavia-create-health-monitor-flow' CREATE_LISTENER_FLOW = 'octavia-create-listener_flow' PRE_CREATE_LOADBALANCER_FLOW = 'octavia-pre-create-loadbalancer-flow' CREATE_SERVER_GROUP_FLOW = 'octavia-create-server-group-flow' UPDATE_LB_SERVERGROUPID_FLOW = 'octavia-update-lb-server-group-id-flow' CREATE_LISTENERS_FLOW = 'octavia-create-all-listeners-flow' CREATE_LOADBALANCER_FLOW = 'octavia-create-loadbalancer-flow' CREATE_LOADBALANCER_GRAPH_FLOW = 'octavia-create-loadbalancer-graph-flow' CREATE_MEMBER_FLOW = 'octavia-create-member-flow' CREATE_POOL_FLOW = 'octavia-create-pool-flow' CREATE_L7POLICY_FLOW = 'octavia-create-l7policy-flow' CREATE_L7RULE_FLOW = 'octavia-create-l7rule-flow' DELETE_AMPHORA_FLOW = 'octavia-delete-amphora-flow' DELETE_EXTRA_AMPHORAE_FLOW = 'octavia-delete-extra-amphorae-flow' DELETE_HEALTH_MONITOR_FLOW = 'octavia-delete-health-monitor-flow' DELETE_LISTENER_FLOW = 'octavia-delete-listener_flow' DELETE_LOADBALANCER_FLOW = 'octavia-delete-loadbalancer-flow' DELETE_MEMBER_FLOW = 'octavia-delete-member-flow' DELETE_POOL_FLOW = 'octavia-delete-pool-flow' DELETE_L7POLICY_FLOW = 'octavia-delete-l7policy-flow' DELETE_L7RULE_FLOW = 'octavia-delete-l7policy-flow' FAILOVER_AMPHORA_FLOW = 'octavia-failover-amphora-flow' FAILOVER_LOADBALANCER_FLOW = 'octavia-failover-loadbalancer-flow' FINALIZE_AMPHORA_FLOW = 'octavia-finalize-amphora-flow' LOADBALANCER_NETWORKING_SUBFLOW = 'octavia-new-loadbalancer-net-subflow' UPDATE_HEALTH_MONITOR_FLOW = 'octavia-update-health-monitor-flow' UPDATE_LISTENER_FLOW = 'octavia-update-listener-flow' UPDATE_LOADBALANCER_FLOW = 'octavia-update-loadbalancer-flow' UPDATE_MEMBER_FLOW = 'octavia-update-member-flow' UPDATE_POOL_FLOW = 'octavia-update-pool-flow' UPDATE_L7POLICY_FLOW = 'octavia-update-l7policy-flow' UPDATE_L7RULE_FLOW = 'octavia-update-l7rule-flow' UPDATE_AMPS_SUBFLOW = 'octavia-update-amps-subflow' UPDATE_AMPHORA_CONFIG_FLOW = 'octavia-update-amp-config-flow' POST_MAP_AMP_TO_LB_SUBFLOW = 'octavia-post-map-amp-to-lb-subflow' CREATE_AMP_FOR_LB_SUBFLOW = 'octavia-create-amp-for-lb-subflow' CREATE_AMP_FOR_FAILOVER_SUBFLOW = 'octavia-create-amp-for-failover-subflow' AMP_PLUG_NET_SUBFLOW = 'octavia-plug-net-subflow' GET_AMPHORA_FOR_LB_SUBFLOW = 'octavia-get-amphora-for-lb-subflow' POST_LB_AMP_ASSOCIATION_SUBFLOW = ( 'octavia-post-loadbalancer-amp_association-subflow') AMPHORA_LISTENER_START_SUBFLOW = 'amphora-listener-start-subflow' AMPHORA_LISTENER_RELOAD_SUBFLOW = 'amphora-listener-start-subflow' MAP_LOADBALANCER_TO_AMPHORA = 'octavia-mapload-balancer-to-amphora' RELOAD_AMPHORA = 'octavia-reload-amphora' CREATE_AMPHORA_INDB = 'octavia-create-amphora-indb' GENERATE_SERVER_PEM = 'octavia-generate-serverpem' UPDATE_CERT_EXPIRATION = 'octavia-update-cert-expiration' CERT_COMPUTE_CREATE = 'octavia-cert-compute-create' COMPUTE_CREATE = 'octavia-compute-create' UPDATE_AMPHORA_COMPUTEID = 'octavia-update-amphora-computeid' MARK_AMPHORA_BOOTING_INDB = 'octavia-mark-amphora-booting-indb' WAIT_FOR_AMPHORA = 'octavia-wait_for_amphora' COMPUTE_WAIT = 'octavia-compute-wait' UPDATE_AMPHORA_INFO = 'octavia-update-amphora-info' AMPHORA_FINALIZE = 'octavia-amphora-finalize' MARK_AMPHORA_ALLOCATED_INDB = 'octavia-mark-amphora-allocated-indb' MARK_AMPHORA_READY_INDB = 'octavia-mark-amphora-ready-indb' MARK_LB_ACTIVE_INDB = 'octavia-mark-lb-active-indb' MARK_AMP_MASTER_INDB = 'octavia-mark-amp-master-indb' MARK_AMP_BACKUP_INDB = 'octavia-mark-amp-backup-indb' MARK_AMP_STANDALONE_INDB = 'octavia-mark-amp-standalone-indb' GET_VRRP_SUBFLOW = 'octavia-get-vrrp-subflow' AMP_VRRP_UPDATE = 'octavia-amphora-vrrp-update' AMP_VRRP_START = 'octavia-amphora-vrrp-start' AMP_VRRP_STOP = 'octavia-amphora-vrrp-stop' AMP_UPDATE_VRRP_INTF = 'octavia-amphora-update-vrrp-intf' CREATE_VRRP_GROUP_FOR_LB = 'octavia-create-vrrp-group-for-lb' CREATE_VRRP_SECURITY_RULES = 'octavia-create-vrrp-security-rules' AMP_COMPUTE_CONNECTIVITY_WAIT = 'octavia-amp-compute-connectivity-wait' AMP_LISTENER_UPDATE = 'octavia-amp-listeners-update' AMP_LISTENER_START = 'octavia-amp-listeners-start' PLUG_VIP_AMPHORA = 'octavia-amp-plug-vip' APPLY_QOS_AMP = 'octavia-amp-apply-qos' UPDATE_AMPHORA_VIP_DATA = 'ocatvia-amp-update-vip-data' GET_AMP_NETWORK_CONFIG = 'octavia-amp-get-network-config' AMP_POST_VIP_PLUG = 'octavia-amp-post-vip-plug' GENERATE_SERVER_PEM_TASK = 'GenerateServerPEMTask' AMPHORA_CONFIG_UPDATE_TASK = 'AmphoraConfigUpdateTask' FIRST_AMP_NETWORK_CONFIGS = 'first-amp-network-configs' FIRST_AMP_VRRP_INTERFACE = 'first-amp-vrrp_interface' # Batch Member Update constants UNORDERED_MEMBER_UPDATES_FLOW = 'octavia-unordered-member-updates-flow' UNORDERED_MEMBER_ACTIVE_FLOW = 'octavia-unordered-member-active-flow' UPDATE_ATTRIBUTES_FLOW = 'octavia-update-attributes-flow' DELETE_MODEL_OBJECT_FLOW = 'octavia-delete-model-object-flow' BATCH_UPDATE_MEMBERS_FLOW = 'octavia-batch-update-members-flow' MEMBER_TO_ERROR_ON_REVERT_FLOW = 'octavia-member-to-error-on-revert-flow' DECREMENT_MEMBER_QUOTA_FLOW = 'octavia-decrement-member-quota-flow' MARK_MEMBER_ACTIVE_INDB = 'octavia-mark-member-active-indb' UPDATE_MEMBER_INDB = 'octavia-update-member-indb' DELETE_MEMBER_INDB = 'octavia-delete-member-indb' # Task Names ADMIN_DOWN_PORT = 'admin-down-port' AMPHORA_POST_VIP_PLUG = 'amphora-post-vip-plug' AMPHORA_RELOAD_LISTENER = 'amphora-reload-listener' AMPHORA_TO_ERROR_ON_REVERT = 'amphora-to-error-on-revert' AMPHORAE_POST_NETWORK_PLUG = 'amphorae-post-network-plug' ATTACH_PORT = 'attach-port' CALCULATE_AMPHORA_DELTA = 'calculate-amphora-delta' CREATE_VIP_BASE_PORT = 'create-vip-base-port' DELETE_AMPHORA = 'delete-amphora' DELETE_PORT = 'delete-port' DISABLE_AMP_HEALTH_MONITORING = 'disable-amphora-health-monitoring' GET_AMPHORA_NETWORK_CONFIGS_BY_ID = 'get-amphora-network-configs-by-id' GET_AMPHORAE_FROM_LB = 'get-amphorae-from-lb' HANDLE_NETWORK_DELTA = 'handle-network-delta' MARK_AMPHORA_DELETED = 'mark-amphora-deleted' MARK_AMPHORA_PENDING_DELETE = 'mark-amphora-pending-delete' MARK_AMPHORA_HEALTH_BUSY = 'mark-amphora-health-busy' RELOAD_AMP_AFTER_PLUG_VIP = 'reload-amp-after-plug-vip' RELOAD_LB_AFTER_AMP_ASSOC = 'reload-lb-after-amp-assoc' RELOAD_LB_AFTER_AMP_ASSOC_FULL_GRAPH = 'reload-lb-after-amp-assoc-full-graph' RELOAD_LB_AFTER_PLUG_VIP = 'reload-lb-after-plug-vip' RELOAD_LB_BEFOR_ALLOCATE_VIP = 'reload-lb-before-allocate-vip' UPDATE_AMP_FAILOVER_DETAILS = 'update-amp-failover-details' NOVA_1 = '1.1' NOVA_21 = '2.1' NOVA_3 = '3' NOVA_VERSIONS = (NOVA_1, NOVA_21, NOVA_3) # Auth sections SERVICE_AUTH = 'service_auth' RPC_NAMESPACE_CONTROLLER_AGENT = 'controller' # Build Type Priority LB_CREATE_FAILOVER_PRIORITY = 20 LB_CREATE_NORMAL_PRIORITY = 40 LB_CREATE_ADMIN_FAILOVER_PRIORITY = 80 BUILD_TYPE_PRIORITY = 'build_type_priority' # Active standalone roles and topology TOPOLOGY_SINGLE = 'SINGLE' TOPOLOGY_ACTIVE_STANDBY = 'ACTIVE_STANDBY' ROLE_MASTER = 'MASTER' ROLE_BACKUP = 'BACKUP' ROLE_STANDALONE = 'STANDALONE' SUPPORTED_LB_TOPOLOGIES = (TOPOLOGY_ACTIVE_STANDBY, TOPOLOGY_SINGLE) SUPPORTED_AMPHORA_ROLES = (ROLE_BACKUP, ROLE_MASTER, ROLE_STANDALONE) TOPOLOGY_STATUS_OK = 'OK' ROLE_MASTER_PRIORITY = 100 ROLE_BACKUP_PRIORITY = 90 VRRP_AUTH_DEFAULT = 'PASS' VRRP_AUTH_AH = 'AH' SUPPORTED_VRRP_AUTH = (VRRP_AUTH_DEFAULT, VRRP_AUTH_AH) KEEPALIVED_CMD = '/usr/sbin/keepalived ' # The DEFAULT_VRRP_ID value needs to be variable for multi tenant support # per amphora in the future DEFAULT_VRRP_ID = 1 VRRP_PROTOCOL_NUM = 112 AUTH_HEADER_PROTOCOL_NUMBER = 51 TEMPLATES = '/templates' AGENT_API_TEMPLATES = '/templates' LOGGING_TEMPLATES = '/templates' AGENT_CONF_TEMPLATE = 'amphora_agent_conf.template' LOGGING_CONF_TEMPLATE = '10-rsyslog.conf.template' USER_DATA_CONFIG_DRIVE_TEMPLATE = 'user_data_config_drive.template' OPEN = 'OPEN' FULL = 'FULL' # OPEN = HAProxy listener status nbconn < maxconn # FULL = HAProxy listener status not nbconn < maxconn HAPROXY_LISTENER_STATUSES = (OPEN, FULL) UP = 'UP' DOWN = 'DOWN' # UP = HAProxy backend has working or no servers # DOWN = HAProxy backend has no working servers HAPROXY_BACKEND_STATUSES = (UP, DOWN) DRAIN = 'DRAIN' MAINT = 'MAINT' NO_CHECK = 'no check' # DRAIN = member is weight 0 and is in draining mode # MAINT = member is downed for maintenance? not sure when this happens # NO_CHECK = no health monitor is enabled HAPROXY_MEMBER_STATUSES = (UP, DOWN, DRAIN, MAINT, NO_CHECK) # Default number of concurrent connections in a HAProxy listener. HAPROXY_DEFAULT_MAXCONN = 50000 # Current maximum number of conccurent connections in HAProxy. # This is limited by the systemd "LimitNOFILE" and # the sysctl fs.file-max fs.nr_open settings in the image HAPROXY_MAX_MAXCONN = 1000000 RESTARTING = 'RESTARTING' # Quota Constants QUOTA_UNLIMITED = -1 MIN_QUOTA = QUOTA_UNLIMITED MAX_QUOTA = 2000000000 API_VERSION = '0.5' HAPROXY_BASE_PEER_PORT = 1025 KEEPALIVED_JINJA2_UPSTART = 'keepalived.upstart.j2' KEEPALIVED_JINJA2_SYSTEMD = 'keepalived.systemd.j2' KEEPALIVED_JINJA2_SYSVINIT = 'keepalived.sysvinit.j2' CHECK_SCRIPT_CONF = 'keepalived_check_script.conf.j2' KEEPALIVED_CHECK_SCRIPT = 'keepalived_lvs_check_script.sh.j2' PLUGGED_INTERFACES = '/var/lib/octavia/plugged_interfaces' HAPROXY_USER_GROUP_CFG = '/var/lib/octavia/haproxy-default-user-group.conf' AMPHORA_NAMESPACE = 'amphora-haproxy' FLOW_DOC_TITLES = {'AmphoraFlows': 'Amphora Flows', 'LoadBalancerFlows': 'Load Balancer Flows', 'ListenerFlows': 'Listener Flows', 'PoolFlows': 'Pool Flows', 'MemberFlows': 'Member Flows', 'HealthMonitorFlows': 'Health Monitor Flows', 'L7PolicyFlows': 'Layer 7 Policy Flows', 'L7RuleFlows': 'Layer 7 Rule Flows'} NETNS_PRIMARY_INTERFACE = 'eth1' SYSCTL_CMD = '/sbin/sysctl' AMP_ACTION_START = 'start' AMP_ACTION_STOP = 'stop' AMP_ACTION_RELOAD = 'reload' AMP_ACTION_RESTART = 'restart' GLANCE_IMAGE_ACTIVE = 'active' INIT_SYSTEMD = 'systemd' INIT_UPSTART = 'upstart' INIT_SYSVINIT = 'sysvinit' INIT_UNKOWN = 'unknown' VALID_INIT_SYSTEMS = (INIT_SYSTEMD, INIT_SYSVINIT, INIT_UPSTART) INIT_PATH = '/sbin/init' SYSTEMD_DIR = '/usr/lib/systemd/system' SYSVINIT_DIR = '/etc/init.d' UPSTART_DIR = '/etc/init' INIT_PROC_COMM_PATH = '/proc/1/comm' KEEPALIVED_SYSTEMD = 'octavia-keepalived.service' KEEPALIVED_SYSVINIT = 'octavia-keepalived' KEEPALIVED_UPSTART = 'octavia-keepalived.conf' KEEPALIVED_SYSTEMD_PREFIX = 'octavia-keepalivedlvs-%s.service' KEEPALIVED_SYSVINIT_PREFIX = 'octavia-keepalivedlvs-%s' KEEPALIVED_UPSTART_PREFIX = 'octavia-keepalivedlvs-%s.conf' # Authentication KEYSTONE = 'keystone' NOAUTH = 'noauth' TESTING = 'testing' # Amphora distro-specific data UBUNTU = 'ubuntu' CENTOS = 'centos' # Pagination, sorting, filtering values APPLICATION_JSON = 'application/json' PAGINATION_HELPER = 'pagination_helper' ASC = 'asc' DESC = 'desc' ALLOWED_SORT_DIR = (ASC, DESC) DEFAULT_SORT_DIR = ASC DEFAULT_SORT_KEYS = ['created_at', 'id'] DEFAULT_PAGE_SIZE = 1000 # RBAC LOADBALANCER_API = 'os_load-balancer_api' RULE_API_ADMIN = 'rule:load-balancer:admin' RULE_API_READ = 'rule:load-balancer:read' RULE_API_READ_GLOBAL = 'rule:load-balancer:read-global' RULE_API_WRITE = 'rule:load-balancer:write' RULE_API_READ_QUOTA = 'rule:load-balancer:read-quota' RULE_API_READ_QUOTA_GLOBAL = 'rule:load-balancer:read-quota-global' RULE_API_WRITE_QUOTA = 'rule:load-balancer:write-quota' RBAC_LOADBALANCER = '{}:loadbalancer:'.format(LOADBALANCER_API) RBAC_LISTENER = '{}:listener:'.format(LOADBALANCER_API) RBAC_POOL = '{}:pool:'.format(LOADBALANCER_API) RBAC_MEMBER = '{}:member:'.format(LOADBALANCER_API) RBAC_HEALTHMONITOR = '{}:healthmonitor:'.format(LOADBALANCER_API) RBAC_L7POLICY = '{}:l7policy:'.format(LOADBALANCER_API) RBAC_L7RULE = '{}:l7rule:'.format(LOADBALANCER_API) RBAC_QUOTA = '{}:quota:'.format(LOADBALANCER_API) RBAC_AMPHORA = '{}:amphora:'.format(LOADBALANCER_API) RBAC_PROVIDER = '{}:provider:'.format(LOADBALANCER_API) RBAC_PROVIDER_FLAVOR = '{}:provider-flavor:'.format(LOADBALANCER_API) RBAC_PROVIDER_AVAILABILITY_ZONE = '{}:provider-availability-zone:'.format( LOADBALANCER_API) RBAC_FLAVOR = '{}:flavor:'.format(LOADBALANCER_API) RBAC_FLAVOR_PROFILE = '{}:flavor-profile:'.format(LOADBALANCER_API) RBAC_AVAILABILITY_ZONE = '{}:availability-zone:'.format(LOADBALANCER_API) RBAC_AVAILABILITY_ZONE_PROFILE = '{}:availability-zone-profile:'.format( LOADBALANCER_API) RBAC_POST = 'post' RBAC_PUT = 'put' RBAC_PUT_CONFIG = 'put_config' RBAC_PUT_FAILOVER = 'put_failover' RBAC_DELETE = 'delete' RBAC_GET_ONE = 'get_one' RBAC_GET_ALL = 'get_all' RBAC_GET_ALL_GLOBAL = 'get_all-global' RBAC_GET_DEFAULTS = 'get_defaults' RBAC_GET_STATS = 'get_stats' RBAC_GET_STATUS = 'get_status' RBAC_SCOPE_PROJECT = 'project' RBAC_SCOPE_SYSTEM = 'system' RBAC_ROLES_DEPRECATED_REASON = ( 'The Octavia API now requires the OpenStack default roles and scoped ' 'tokens. ' 'See https://docs.openstack.org/octavia/latest/configuration/policy.html ' 'and https://docs.openstack.org/keystone/latest/contributor/' 'services.html#reusable-default-roles for more information.') # PROVIDERS OCTAVIA = 'octavia' AMPHORAV2 = 'amphorav2' AMPHORAV1 = 'amphorav1' # systemctl commands DISABLE = 'disable' ENABLE = 'enable' # systemd amphora netns service prefix AMP_NETNS_SVC_PREFIX = 'amphora-netns' # Amphora Feature Compatibility HTTP_REUSE = 'has_http_reuse' POOL_ALPN = 'has_pool_alpn' # TODO(johnsom) convert these to octavia_lib constants # once octavia is transitioned to use octavia_lib FLAVOR = 'flavor' FLAVOR_DATA = 'flavor_data' AVAILABILITY_ZONE = 'availability_zone' AVAILABILITY_ZONE_DATA = 'availability_zone_data' # Flavor metadata LOADBALANCER_TOPOLOGY = 'loadbalancer_topology' COMPUTE_FLAVOR = 'compute_flavor' AMP_IMAGE_TAG = 'amp_image_tag' # TODO(johnsom) move to octavia_lib # client certification authorization option CLIENT_AUTH_NONE = 'NONE' CLIENT_AUTH_OPTIONAL = 'OPTIONAL' CLIENT_AUTH_MANDATORY = 'MANDATORY' SUPPORTED_CLIENT_AUTH_MODES = [CLIENT_AUTH_NONE, CLIENT_AUTH_OPTIONAL, CLIENT_AUTH_MANDATORY] TOPIC_AMPHORA_V2 = 'octavia_provisioning_v2' HAPROXY_HTTP_PROTOCOLS = [lib_consts.PROTOCOL_HTTP, lib_consts.PROTOCOL_TERMINATED_HTTPS] LVS_PROTOCOLS = [PROTOCOL_UDP, lib_consts.PROTOCOL_SCTP] HAPROXY_BACKEND = 'HAPROXY' LVS_BACKEND = 'LVS' # Map each supported protocol to its L4 protocol L4_PROTOCOL_MAP = { PROTOCOL_TCP: PROTOCOL_TCP, PROTOCOL_HTTP: PROTOCOL_TCP, PROTOCOL_HTTPS: PROTOCOL_TCP, PROTOCOL_TERMINATED_HTTPS: PROTOCOL_TCP, PROTOCOL_PROXY: PROTOCOL_TCP, lib_consts.PROTOCOL_PROXYV2: PROTOCOL_TCP, PROTOCOL_UDP: PROTOCOL_UDP, lib_consts.PROTOCOL_SCTP: lib_consts.PROTOCOL_SCTP, lib_consts.PROTOCOL_PROMETHEUS: lib_consts.PROTOCOL_TCP, } # Image drivers SUPPORTED_IMAGE_DRIVERS = ['image_noop_driver', 'image_glance_driver'] # Volume drivers VOLUME_NOOP_DRIVER = 'volume_noop_driver' SUPPORTED_VOLUME_DRIVERS = [VOLUME_NOOP_DRIVER, 'volume_cinder_driver'] # Cinder volume driver constants CINDER_STATUS_AVAILABLE = 'available' CINDER_STATUS_ERROR = 'error' CINDER_ACTION_CREATE_VOLUME = 'create volume' # The nil UUID (used in octavia for deleted references) - RFC 4122 NIL_UUID = '00000000-0000-0000-0000-000000000000' # OpenSSL cipher strings CIPHERS_OWASP_SUITE_B = ('TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:' 'TLS_AES_128_GCM_SHA256:DHE-RSA-AES256-GCM-SHA384:' 'DHE-RSA-AES128-GCM-SHA256:' 'ECDHE-RSA-AES256-GCM-SHA384:' 'ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-SHA256:' 'DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:' 'ECDHE-RSA-AES128-SHA256') TLS_VERSIONS_OWASP_SUITE_B = [lib_consts.TLS_VERSION_1_2, lib_consts.TLS_VERSION_1_3] # All supported TLS versions in ascending order (oldest to newest) TLS_ALL_VERSIONS = [ lib_consts.SSL_VERSION_3, lib_consts.TLS_VERSION_1, lib_consts.TLS_VERSION_1_1, lib_consts.TLS_VERSION_1_2, lib_consts.TLS_VERSION_1_3 ] VIP_SECURITY_GROUP_PREFIX = 'lb-' AMP_BASE_PORT_PREFIX = 'octavia-lb-vrrp-' OCTAVIA_OWNED = 'octavia_owned' # Sadly in the LBaaS v2 API, header insertions are on the listener objects # but they should be on the pool. Dealing with it until v3. LISTENER_PROTOCOLS_SUPPORTING_HEADER_INSERTION = [PROTOCOL_HTTP, PROTOCOL_TERMINATED_HTTPS] SUPPORTED_ALPN_PROTOCOLS = [lib_consts.ALPN_PROTOCOL_HTTP_2, lib_consts.ALPN_PROTOCOL_HTTP_1_1, lib_consts.ALPN_PROTOCOL_HTTP_1_0] AMPHORA_SUPPORTED_ALPN_PROTOCOLS = [lib_consts.ALPN_PROTOCOL_HTTP_2, lib_consts.ALPN_PROTOCOL_HTTP_1_1, lib_consts.ALPN_PROTOCOL_HTTP_1_0] # Amphora interface fields MTU = 'mtu' ADDRESSES = 'addresses' ROUTES = 'routes' RULES = 'rules' SCRIPTS = 'scripts' # pyroute2 fields STATE = 'state' FAMILY = 'family' ADDRESS = 'address' PREFIXLEN = 'prefixlen' DHCP = 'dhcp' IPV6AUTO = 'ipv6auto' DST = 'dst' PREFSRC = 'prefsrc' GATEWAY = 'gateway' FLAGS = 'flags' ONLINK = 'onlink' TABLE = 'table' SCOPE = 'scope' SRC = 'src' SRC_LEN = 'src_len' IFACE_UP = 'up' IFACE_DOWN = 'down' COMMAND = 'command' # Amphora network directory AMP_NET_DIR_TEMPLATE = '/etc/octavia/interfaces/'
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 Cloudscaling Group, 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. """ The MatchMaker classes should except a Topic or Fanout exchange key and return keys for direct exchanges, per (approximate) AMQP parlance. """ import contextlib import eventlet from oslo.config import cfg from trove.openstack.common.gettextutils import _ # noqa from trove.openstack.common import log as logging matchmaker_opts = [ cfg.IntOpt('matchmaker_heartbeat_freq', default=300, help='Heartbeat frequency'), cfg.IntOpt('matchmaker_heartbeat_ttl', default=600, help='Heartbeat time-to-live.'), ] CONF = cfg.CONF CONF.register_opts(matchmaker_opts) LOG = logging.getLogger(__name__) contextmanager = contextlib.contextmanager class MatchMakerException(Exception): """Signified a match could not be found.""" message = _("Match not found by MatchMaker.") class Exchange(object): """Implements lookups. Subclass this to support hashtables, dns, etc. """ def __init__(self): pass def run(self, key): raise NotImplementedError() class Binding(object): """A binding on which to perform a lookup.""" def __init__(self): pass def test(self, key): raise NotImplementedError() class MatchMakerBase(object): """Match Maker Base Class. Build off HeartbeatMatchMakerBase if building a heartbeat-capable MatchMaker. """ def __init__(self): # Array of tuples. Index [2] toggles negation, [3] is last-if-true self.bindings = [] self.no_heartbeat_msg = _('Matchmaker does not implement ' 'registration or heartbeat.') def register(self, key, host): """Register a host on a backend. Heartbeats, if applicable, may keepalive registration. """ pass def ack_alive(self, key, host): """Acknowledge that a key.host is alive. Used internally for updating heartbeats, but may also be used publically to acknowledge a system is alive (i.e. rpc message successfully sent to host) """ pass def is_alive(self, topic, host): """Checks if a host is alive.""" pass def expire(self, topic, host): """Explicitly expire a host's registration.""" pass def send_heartbeats(self): """Send all heartbeats. Use start_heartbeat to spawn a heartbeat greenthread, which loops this method. """ pass def unregister(self, key, host): """Unregister a topic.""" pass def start_heartbeat(self): """Spawn heartbeat greenthread.""" pass def stop_heartbeat(self): """Destroys the heartbeat greenthread.""" pass def add_binding(self, binding, rule, last=True): self.bindings.append((binding, rule, False, last)) #NOTE(ewindisch): kept the following method in case we implement the # underlying support. #def add_negate_binding(self, binding, rule, last=True): # self.bindings.append((binding, rule, True, last)) def queues(self, key): workers = [] # bit is for negate bindings - if we choose to implement it. # last stops processing rules if this matches. for (binding, exchange, bit, last) in self.bindings: if binding.test(key): workers.extend(exchange.run(key)) # Support last. if last: return workers return workers class HeartbeatMatchMakerBase(MatchMakerBase): """Base for a heart-beat capable MatchMaker. Provides common methods for registering, unregistering, and maintaining heartbeats. """ def __init__(self): self.hosts = set() self._heart = None self.host_topic = {} super(HeartbeatMatchMakerBase, self).__init__() def send_heartbeats(self): """Send all heartbeats. Use start_heartbeat to spawn a heartbeat greenthread, which loops this method. """ for key, host in self.host_topic: self.ack_alive(key, host) def ack_alive(self, key, host): """Acknowledge that a host.topic is alive. Used internally for updating heartbeats, but may also be used publically to acknowledge a system is alive (i.e. rpc message successfully sent to host) """ raise NotImplementedError("Must implement ack_alive") def backend_register(self, key, host): """Implements registration logic. Called by register(self,key,host) """ raise NotImplementedError("Must implement backend_register") def backend_unregister(self, key, key_host): """Implements de-registration logic. Called by unregister(self,key,host) """ raise NotImplementedError("Must implement backend_unregister") def register(self, key, host): """Register a host on a backend. Heartbeats, if applicable, may keepalive registration. """ self.hosts.add(host) self.host_topic[(key, host)] = host key_host = '.'.join((key, host)) self.backend_register(key, key_host) self.ack_alive(key, host) def unregister(self, key, host): """Unregister a topic.""" if (key, host) in self.host_topic: del self.host_topic[(key, host)] self.hosts.discard(host) self.backend_unregister(key, '.'.join((key, host))) LOG.info(_("Matchmaker unregistered: %(key)s, %(host)s"), {'key': key, 'host': host}) def start_heartbeat(self): """Implementation of MatchMakerBase.start_heartbeat. Launches greenthread looping send_heartbeats(), yielding for CONF.matchmaker_heartbeat_freq seconds between iterations. """ if not self.hosts: raise MatchMakerException( _("Register before starting heartbeat.")) def do_heartbeat(): while True: self.send_heartbeats() eventlet.sleep(CONF.matchmaker_heartbeat_freq) self._heart = eventlet.spawn(do_heartbeat) def stop_heartbeat(self): """Destroys the heartbeat greenthread.""" if self._heart: self._heart.kill() class DirectBinding(Binding): """Specifies a host in the key via a '.' character. Although dots are used in the key, the behavior here is that it maps directly to a host, thus direct. """ def test(self, key): return '.' in key class TopicBinding(Binding): """Where a 'bare' key without dots. AMQP generally considers topic exchanges to be those *with* dots, but we deviate here in terminology as the behavior here matches that of a topic exchange (whereas where there are dots, behavior matches that of a direct exchange. """ def test(self, key): return '.' not in key class FanoutBinding(Binding): """Match on fanout keys, where key starts with 'fanout.' string.""" def test(self, key): return key.startswith('fanout~') class StubExchange(Exchange): """Exchange that does nothing.""" def run(self, key): return [(key, None)] class LocalhostExchange(Exchange): """Exchange where all direct topics are local.""" def __init__(self, host='localhost'): self.host = host super(Exchange, self).__init__() def run(self, key): return [('.'.join((key.split('.')[0], self.host)), self.host)] class DirectExchange(Exchange): """Exchange where all topic keys are split, sending to second half. i.e. "compute.host" sends a message to "compute.host" running on "host" """ def __init__(self): super(Exchange, self).__init__() def run(self, key): e = key.split('.', 1)[1] return [(key, e)] class MatchMakerLocalhost(MatchMakerBase): """Match Maker where all bare topics resolve to localhost. Useful for testing. """ def __init__(self, host='localhost'): super(MatchMakerLocalhost, self).__init__() self.add_binding(FanoutBinding(), LocalhostExchange(host)) self.add_binding(DirectBinding(), DirectExchange()) self.add_binding(TopicBinding(), LocalhostExchange(host)) class MatchMakerStub(MatchMakerBase): """Match Maker where topics are untouched. Useful for testing, or for AMQP/brokered queues. Will not work where knowledge of hosts is known (i.e. zeromq) """ def __init__(self): super(MatchMakerStub, self).__init__() self.add_binding(FanoutBinding(), StubExchange()) self.add_binding(DirectBinding(), StubExchange()) self.add_binding(TopicBinding(), StubExchange())
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Common graph operations for execution """ from copy import deepcopy from glob import glob import os import getpass import shutil from socket import gethostname import sys from time import strftime, sleep, time from traceback import format_exception, format_exc from warnings import warn import numpy as np import scipy.sparse as ssp from ..utils import (nx, dfs_preorder, topological_sort) from ..engine import (MapNode, str2bool) from nipype.utils.filemanip import savepkl, loadpkl from ... import logging logger = logging.getLogger('workflow') iflogger = logging.getLogger('interface') def report_crash(node, traceback=None, hostname=None): """Writes crash related information to a file """ name = node._id if node.result and hasattr(node.result, 'runtime') and \ node.result.runtime: if isinstance(node.result.runtime, list): host = node.result.runtime[0].hostname else: host = node.result.runtime.hostname else: if hostname: host = hostname else: host = gethostname() message = ['Node %s failed to run on host %s.' % (name, host)] logger.error(message) if not traceback: exc_type, exc_value, exc_traceback = sys.exc_info() traceback = format_exception(exc_type, exc_value, exc_traceback) timeofcrash = strftime('%Y%m%d-%H%M%S') login_name = getpass.getuser() crashfile = 'crash-%s-%s-%s.pklz' % (timeofcrash, login_name, name) crashdir = node.config['execution']['crashdump_dir'] if crashdir is None: crashdir = os.getcwd() if not os.path.exists(crashdir): os.makedirs(crashdir) crashfile = os.path.join(crashdir, crashfile) logger.info('Saving crash info to %s' % crashfile) logger.info(''.join(traceback)) savepkl(crashfile, dict(node=node, traceback=traceback)) #np.savez(crashfile, node=node, traceback=traceback) return crashfile def report_nodes_not_run(notrun): """List nodes that crashed with crashfile info Optionally displays dependent nodes that weren't executed as a result of the crash. """ if notrun: logger.info("***********************************") for info in notrun: logger.error("could not run node: %s" % '.'.join((info['node']._hierarchy, info['node']._id))) logger.info("crashfile: %s" % info['crashfile']) logger.debug("The following dependent nodes were not run") for subnode in info['dependents']: logger.debug(subnode._id) logger.info("***********************************") raise RuntimeError(('Workflow did not execute cleanly. ' 'Check log for details')) def create_pyscript(node, updatehash=False, store_exception=True): # pickle node timestamp = strftime('%Y%m%d_%H%M%S') if node._hierarchy: suffix = '%s_%s_%s' % (timestamp, node._hierarchy, node._id) batch_dir = os.path.join(node.base_dir, node._hierarchy.split('.')[0], 'batch') else: suffix = '%s_%s' % (timestamp, node._id) batch_dir = os.path.join(node.base_dir, 'batch') if not os.path.exists(batch_dir): os.makedirs(batch_dir) pkl_file = os.path.join(batch_dir, 'node_%s.pklz' % suffix) savepkl(pkl_file, dict(node=node, updatehash=updatehash)) mpl_backend = node.config["execution"]["matplotlib_backend"] # create python script to load and trap exception cmdstr = """import os import sys can_import_matplotlib = True #Silently allow matplotlib to be ignored try: import matplotlib matplotlib.use('%s') except ImportError: can_import_matplotlib = False pass from nipype import config, logging from nipype.utils.filemanip import loadpkl, savepkl from socket import gethostname from traceback import format_exception info = None pklfile = '%s' batchdir = '%s' from nipype.utils.filemanip import loadpkl, savepkl try: if not sys.version_info < (2, 7): from collections import OrderedDict config_dict=%s config.update_config(config_dict) ## Only configure matplotlib if it was successfully imported, matplotlib is an optional component to nipype if can_import_matplotlib: config.update_matplotlib() logging.update_logging(config) traceback=None cwd = os.getcwd() info = loadpkl(pklfile) result = info['node'].run(updatehash=info['updatehash']) except Exception, e: etype, eval, etr = sys.exc_info() traceback = format_exception(etype,eval,etr) if info is None or not os.path.exists(info['node'].output_dir()): result = None resultsfile = os.path.join(batchdir, 'crashdump_%s.pklz') else: result = info['node'].result resultsfile = os.path.join(info['node'].output_dir(), 'result_%%s.pklz'%%info['node'].name) """ if store_exception: cmdstr += """ savepkl(resultsfile, dict(result=result, hostname=gethostname(), traceback=traceback)) """ else: cmdstr += """ if info is None: savepkl(resultsfile, dict(result=result, hostname=gethostname(), traceback=traceback)) else: from nipype.pipeline.plugins.base import report_crash report_crash(info['node'], traceback, gethostname()) raise Exception(e) """ cmdstr = cmdstr % (mpl_backend, pkl_file, batch_dir, node.config, suffix) pyscript = os.path.join(batch_dir, 'pyscript_%s.py' % suffix) fp = open(pyscript, 'wt') fp.writelines(cmdstr) fp.close() return pyscript class PluginBase(object): """Base class for plugins""" def __init__(self, plugin_args=None): if plugin_args and 'status_callback' in plugin_args: self._status_callback = plugin_args['status_callback'] else: self._status_callback = None return def run(self, graph, config, updatehash=False): raise NotImplementedError class DistributedPluginBase(PluginBase): """Execute workflow with a distribution engine """ def __init__(self, plugin_args=None): """Initialize runtime attributes to none procs: list (N) of underlying interface elements to be processed proc_done: a boolean vector (N) signifying whether a process has been executed proc_pending: a boolean vector (N) signifying whether a process is currently running. Note: A process is finished only when both proc_done==True and proc_pending==False depidx: a boolean matrix (NxN) storing the dependency structure accross processes. Process dependencies are derived from each column. """ super(DistributedPluginBase, self).__init__(plugin_args=plugin_args) self.procs = None self.depidx = None self.refidx = None self.mapnodes = None self.mapnodesubids = None self.proc_done = None self.proc_pending = None self.max_jobs = np.inf if plugin_args and 'max_jobs' in plugin_args: self.max_jobs = plugin_args['max_jobs'] def run(self, graph, config, updatehash=False): """Executes a pre-defined pipeline using distributed approaches """ logger.info("Running in parallel.") self._config = config # Generate appropriate structures for worker-manager model self._generate_dependency_list(graph) self.pending_tasks = [] self.readytorun = [] self.mapnodes = [] self.mapnodesubids = {} # setup polling - TODO: change to threaded model notrun = [] while np.any(self.proc_done == False) | \ np.any(self.proc_pending == True): toappend = [] # trigger callbacks for any pending results while self.pending_tasks: taskid, jobid = self.pending_tasks.pop() try: result = self._get_result(taskid) if result: if result['traceback']: notrun.append(self._clean_queue(jobid, graph, result=result)) else: self._task_finished_cb(jobid) self._remove_node_dirs() self._clear_task(taskid) else: toappend.insert(0, (taskid, jobid)) except Exception: result = {'result': None, 'traceback': format_exc()} notrun.append(self._clean_queue(jobid, graph, result=result)) if toappend: self.pending_tasks.extend(toappend) num_jobs = len(self.pending_tasks) logger.debug('Number of pending tasks: %d' % num_jobs) if num_jobs < self.max_jobs: self._send_procs_to_workers(updatehash=updatehash, graph=graph) else: logger.debug('Not submitting') sleep(float(self._config['execution']['poll_sleep_duration'])) self._remove_node_dirs() report_nodes_not_run(notrun) def _get_result(self, taskid): raise NotImplementedError def _submit_job(self, node, updatehash=False): raise NotImplementedError def _report_crash(self, node, result=None): raise NotImplementedError def _clear_task(self, taskid): raise NotImplementedError def _clean_queue(self, jobid, graph, result=None): if str2bool(self._config['execution']['stop_on_first_crash']): raise RuntimeError("".join(result['traceback'])) crashfile = self._report_crash(self.procs[jobid], result=result) if self._status_callback: self._status_callback(self.procs[jobid], 'exception') if jobid in self.mapnodesubids: # remove current jobid self.proc_pending[jobid] = False self.proc_done[jobid] = True # remove parent mapnode jobid = self.mapnodesubids[jobid] self.proc_pending[jobid] = False self.proc_done[jobid] = True # remove dependencies from queue return self._remove_node_deps(jobid, crashfile, graph) def _submit_mapnode(self, jobid): if jobid in self.mapnodes: return True self.mapnodes.append(jobid) mapnodesubids = self.procs[jobid].get_subnodes() numnodes = len(mapnodesubids) logger.info('Adding %d jobs for mapnode %s' % (numnodes, self.procs[jobid]._id)) for i in range(numnodes): self.mapnodesubids[self.depidx.shape[0] + i] = jobid self.procs.extend(mapnodesubids) self.depidx = ssp.vstack((self.depidx, ssp.lil_matrix(np.zeros( (numnodes, self.depidx.shape[1])))), 'lil') self.depidx = ssp.hstack((self.depidx, ssp.lil_matrix( np.zeros((self.depidx.shape[0], numnodes)))), 'lil') self.depidx[-numnodes:, jobid] = 1 self.proc_done = np.concatenate((self.proc_done, np.zeros(numnodes, dtype=bool))) self.proc_pending = np.concatenate((self.proc_pending, np.zeros(numnodes, dtype=bool))) return False def _send_procs_to_workers(self, updatehash=False, graph=None): """ Sends jobs to workers """ while np.any(self.proc_done == False): num_jobs = len(self.pending_tasks) if np.isinf(self.max_jobs): slots = None else: slots = max(0, self.max_jobs - num_jobs) logger.debug('Slots available: %s' % slots) if (num_jobs >= self.max_jobs) or (slots == 0): break # Check to see if a job is available jobids = np.flatnonzero((self.proc_done == False) & (self.depidx.sum(axis=0) == 0).__array__()) if len(jobids) > 0: # send all available jobs logger.info('Submitting %d jobs' % len(jobids[:slots])) for jobid in jobids[:slots]: if isinstance(self.procs[jobid], MapNode): try: num_subnodes = self.procs[jobid].num_subnodes() except Exception: self._clean_queue(jobid, graph) self.proc_pending[jobid] = False continue if num_subnodes > 1: submit = self._submit_mapnode(jobid) if not submit: continue # change job status in appropriate queues self.proc_done[jobid] = True self.proc_pending[jobid] = True # Send job to task manager and add to pending tasks logger.info('Executing: %s ID: %d' % (self.procs[jobid]._id, jobid)) if self._status_callback: self._status_callback(self.procs[jobid], 'start') continue_with_submission = True if str2bool(self.procs[jobid].config['execution'] ['local_hash_check']): logger.debug('checking hash locally') try: hash_exists, _, _, _ = self.procs[ jobid].hash_exists() logger.debug('Hash exists %s' % str(hash_exists)) if (hash_exists and (self.procs[jobid].overwrite == False or (self.procs[jobid].overwrite == None and not self.procs[jobid]._interface.always_run) ) ): continue_with_submission = False self._task_finished_cb(jobid) self._remove_node_dirs() except Exception: self._clean_queue(jobid, graph) self.proc_pending[jobid] = False continue_with_submission = False logger.debug('Finished checking hash %s' % str(continue_with_submission)) if continue_with_submission: if self.procs[jobid].run_without_submitting: logger.debug('Running node %s on master thread' % self.procs[jobid]) try: self.procs[jobid].run() except Exception: self._clean_queue(jobid, graph) self._task_finished_cb(jobid) self._remove_node_dirs() else: tid = self._submit_job(deepcopy(self.procs[jobid]), updatehash=updatehash) if tid is None: self.proc_done[jobid] = False self.proc_pending[jobid] = False else: self.pending_tasks.insert(0, (tid, jobid)) else: break def _task_finished_cb(self, jobid): """ Extract outputs and assign to inputs of dependent tasks This is called when a job is completed. """ logger.info('[Job finished] jobname: %s jobid: %d' % (self.procs[jobid]._id, jobid)) if self._status_callback: self._status_callback(self.procs[jobid], 'end') # Update job and worker queues self.proc_pending[jobid] = False # update the job dependency structure rowview = self.depidx.getrowview(jobid) rowview[rowview.nonzero()] = 0 if jobid not in self.mapnodesubids: self.refidx[self.refidx[:, jobid].nonzero()[0], jobid] = 0 def _generate_dependency_list(self, graph): """ Generates a dependency list for a list of graphs. """ self.procs, _ = topological_sort(graph) try: self.depidx = nx.to_scipy_sparse_matrix(graph, nodelist=self.procs, format='lil') except: self.depidx = nx.to_scipy_sparse_matrix(graph, nodelist=self.procs) self.refidx = deepcopy(self.depidx) self.refidx.astype = np.int self.proc_done = np.zeros(len(self.procs), dtype=bool) self.proc_pending = np.zeros(len(self.procs), dtype=bool) def _remove_node_deps(self, jobid, crashfile, graph): subnodes = [s for s in dfs_preorder(graph, self.procs[jobid])] for node in subnodes: idx = self.procs.index(node) self.proc_done[idx] = True self.proc_pending[idx] = False return dict(node=self.procs[jobid], dependents=subnodes, crashfile=crashfile) def _remove_node_dirs(self): """Removes directories whose outputs have already been used up """ if str2bool(self._config['execution']['remove_node_directories']): for idx in np.nonzero( (self.refidx.sum(axis=1) == 0).__array__())[0]: if idx in self.mapnodesubids: continue if self.proc_done[idx] and (not self.proc_pending[idx]): self.refidx[idx, idx] = -1 outdir = self.procs[idx]._output_directory() logger.info(('[node dependencies finished] ' 'removing node: %s from directory %s') % (self.procs[idx]._id, outdir)) shutil.rmtree(outdir) class SGELikeBatchManagerBase(DistributedPluginBase): """Execute workflow with SGE/OGE/PBS like batch system """ def __init__(self, template, plugin_args=None): super(SGELikeBatchManagerBase, self).__init__(plugin_args=plugin_args) self._template = template self._qsub_args = None if plugin_args: if 'template' in plugin_args: self._template = plugin_args['template'] if os.path.isfile(self._template): self._template = open(self._template).read() if 'qsub_args' in plugin_args: self._qsub_args = plugin_args['qsub_args'] self._pending = {} def _is_pending(self, taskid): """Check if a task is pending in the batch system """ raise NotImplementedError def _submit_batchtask(self, scriptfile, node): """Submit a task to the batch system """ raise NotImplementedError def _get_result(self, taskid): if taskid not in self._pending: raise Exception('Task %d not found' % taskid) if self._is_pending(taskid): return None node_dir = self._pending[taskid] # MIT HACK # on the pbs system at mit the parent node directory needs to be # accessed before internal directories become available. there # is a disconnect when the queueing engine knows a job is # finished to when the directories become statable. t = time() timeout = float(self._config['execution']['job_finished_timeout']) timed_out = True while (time() - t) < timeout: try: logger.debug(os.listdir(os.path.realpath(os.path.join(node_dir, '..')))) logger.debug(os.listdir(node_dir)) glob(os.path.join(node_dir, 'result_*.pklz')).pop() timed_out = False break except Exception, e: logger.debug(e) sleep(2) if timed_out: result_data = {'hostname': 'unknown', 'result': None, 'traceback': None} results_file = None try: error_message = ('Job id ({0}) finished or terminated, but ' 'results file does not exist after ({1}) ' 'seconds. Batch dir contains crashdump file ' 'if node raised an exception.\n' 'Node working directory: ({2}) '.format( taskid,timeout,node_dir) ) raise IOError(error_message) except IOError, e: result_data['traceback'] = format_exc() else: results_file = glob(os.path.join(node_dir, 'result_*.pklz'))[0] result_data = loadpkl(results_file) result_out = dict(result=None, traceback=None) if isinstance(result_data, dict): result_out['result'] = result_data['result'] result_out['traceback'] = result_data['traceback'] result_out['hostname'] = result_data['hostname'] if results_file: crash_file = os.path.join(node_dir, 'crashstore.pklz') os.rename(results_file, crash_file) else: result_out['result'] = result_data return result_out def _submit_job(self, node, updatehash=False): """submit job and return taskid """ pyscript = create_pyscript(node, updatehash=updatehash) batch_dir, name = os.path.split(pyscript) name = '.'.join(name.split('.')[:-1]) batchscript = '\n'.join((self._template, '%s %s' % (sys.executable, pyscript))) batchscriptfile = os.path.join(batch_dir, 'batchscript_%s.sh' % name) fp = open(batchscriptfile, 'wt') fp.writelines(batchscript) fp.close() return self._submit_batchtask(batchscriptfile, node) def _report_crash(self, node, result=None): if result and result['traceback']: node._result = result['result'] node._traceback = result['traceback'] return report_crash(node, traceback=result['traceback']) else: return report_crash(node) def _clear_task(self, taskid): del self._pending[taskid] class GraphPluginBase(PluginBase): """Base class for plugins that distribute graphs to workflows """ def __init__(self, plugin_args=None): if plugin_args and 'status_callback' in plugin_args: warn('status_callback not supported for Graph submission plugins') super(GraphPluginBase, self).__init__(plugin_args=plugin_args) def run(self, graph, config, updatehash=False): pyfiles = [] dependencies = {} self._config = config nodes = nx.topological_sort(graph) logger.debug('Creating executable python files for each node') for idx, node in enumerate(nodes): pyfiles.append(create_pyscript(node, updatehash=updatehash, store_exception=False)) dependencies[idx] = [nodes.index(prevnode) for prevnode in graph.predecessors(node)] self._submit_graph(pyfiles, dependencies, nodes) def _get_args(self, node, keywords): values = () for keyword in keywords: value = getattr(self, "_" + keyword) if keyword == "template" and os.path.isfile(value): value = open(value).read() if (hasattr(node, "plugin_args") and isinstance(node.plugin_args, dict) and keyword in node.plugin_args): if (keyword == "template" and os.path.isfile(node.plugin_args[keyword])): tmp_value = open(node.plugin_args[keyword]).read() else: tmp_value = node.plugin_args[keyword] if ('overwrite' in node.plugin_args and node.plugin_args['overwrite']): value = tmp_value else: value += tmp_value values += (value, ) return values def _submit_graph(self, pyfiles, dependencies, nodes): """ pyfiles: list of files corresponding to a topological sort dependencies: dictionary of dependencies based on the toplogical sort """ raise NotImplementedError def _get_result(self, taskid): if taskid not in self._pending: raise Exception('Task %d not found' % taskid) if self._is_pending(taskid): return None node_dir = self._pending[taskid] logger.debug(os.listdir(os.path.realpath(os.path.join(node_dir, '..')))) logger.debug(os.listdir(node_dir)) glob(os.path.join(node_dir, 'result_*.pklz')).pop() results_file = glob(os.path.join(node_dir, 'result_*.pklz'))[0] result_data = loadpkl(results_file) result_out = dict(result=None, traceback=None) if isinstance(result_data, dict): result_out['result'] = result_data['result'] result_out['traceback'] = result_data['traceback'] result_out['hostname'] = result_data['hostname'] if results_file: crash_file = os.path.join(node_dir, 'crashstore.pklz') os.rename(results_file, crash_file) else: result_out['result'] = result_data return result_out
# 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 TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class NodeTypesOperations(object): """NodeTypesOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~service_fabric_managed_clusters_management_client.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list_by_managed_clusters( self, resource_group_name, # type: str cluster_name, # type: str **kwargs # type: Any ): # type: (...) -> Iterable["_models.NodeTypeListResult"] """Gets the list of Node types of the specified managed cluster. Gets all Node types of the specified managed cluster. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cluster_name: The name of the cluster resource. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either NodeTypeListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~service_fabric_managed_clusters_management_client.models.NodeTypeListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.NodeTypeListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_managed_clusters.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('NodeTypeListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: error = self._deserialize.failsafe_deserialize(_models.ErrorModel, response) map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_managed_clusters.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/managedClusters/{clusterName}/nodeTypes'} # type: ignore def _restart_initial( self, resource_group_name, # type: str cluster_name, # type: str node_type_name, # type: str parameters, # type: "_models.NodeTypeActionParameters" **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._restart_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), 'nodeTypeName': self._serialize.url("node_type_name", node_type_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'NodeTypeActionParameters') body_content_kwargs['content'] = body_content request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorModel, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _restart_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/managedClusters/{clusterName}/nodeTypes/{nodeTypeName}/restart'} # type: ignore def begin_restart( self, resource_group_name, # type: str cluster_name, # type: str node_type_name, # type: str parameters, # type: "_models.NodeTypeActionParameters" **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Restarts one or more nodes on the node type. Restarts one or more nodes on the node type. It will disable the fabric nodes, trigger a restart on the VMs and activate the nodes back again. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cluster_name: The name of the cluster resource. :type cluster_name: str :param node_type_name: The name of the node type. :type node_type_name: str :param parameters: parameters for restart action. :type parameters: ~service_fabric_managed_clusters_management_client.models.NodeTypeActionParameters :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the ARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._restart_initial( resource_group_name=resource_group_name, cluster_name=cluster_name, node_type_name=node_type_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), 'nodeTypeName': self._serialize.url("node_type_name", node_type_name, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_restart.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/managedClusters/{clusterName}/nodeTypes/{nodeTypeName}/restart'} # type: ignore def _reimage_initial( self, resource_group_name, # type: str cluster_name, # type: str node_type_name, # type: str parameters, # type: "_models.NodeTypeActionParameters" **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._reimage_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), 'nodeTypeName': self._serialize.url("node_type_name", node_type_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'NodeTypeActionParameters') body_content_kwargs['content'] = body_content request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorModel, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _reimage_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/managedClusters/{clusterName}/nodeTypes/{nodeTypeName}/reimage'} # type: ignore def begin_reimage( self, resource_group_name, # type: str cluster_name, # type: str node_type_name, # type: str parameters, # type: "_models.NodeTypeActionParameters" **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Reimages one or more nodes on the node type. Reimages one or more nodes on the node type. It will disable the fabric nodes, trigger a reimage on the VMs and activate the nodes back again. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cluster_name: The name of the cluster resource. :type cluster_name: str :param node_type_name: The name of the node type. :type node_type_name: str :param parameters: parameters for reimage action. :type parameters: ~service_fabric_managed_clusters_management_client.models.NodeTypeActionParameters :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the ARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._reimage_initial( resource_group_name=resource_group_name, cluster_name=cluster_name, node_type_name=node_type_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), 'nodeTypeName': self._serialize.url("node_type_name", node_type_name, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_reimage.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/managedClusters/{clusterName}/nodeTypes/{nodeTypeName}/reimage'} # type: ignore def _delete_node_initial( self, resource_group_name, # type: str cluster_name, # type: str node_type_name, # type: str parameters, # type: "_models.NodeTypeActionParameters" **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._delete_node_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), 'nodeTypeName': self._serialize.url("node_type_name", node_type_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'NodeTypeActionParameters') body_content_kwargs['content'] = body_content request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorModel, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_node_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/managedClusters/{clusterName}/nodeTypes/{nodeTypeName}/deleteNode'} # type: ignore def begin_delete_node( self, resource_group_name, # type: str cluster_name, # type: str node_type_name, # type: str parameters, # type: "_models.NodeTypeActionParameters" **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Deletes one or more nodes on the node type. Deletes one or more nodes on the node type. It will disable the fabric nodes, trigger a delete on the VMs and removes the state from the cluster. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cluster_name: The name of the cluster resource. :type cluster_name: str :param node_type_name: The name of the node type. :type node_type_name: str :param parameters: parameters for delete action. :type parameters: ~service_fabric_managed_clusters_management_client.models.NodeTypeActionParameters :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the ARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._delete_node_initial( resource_group_name=resource_group_name, cluster_name=cluster_name, node_type_name=node_type_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), 'nodeTypeName': self._serialize.url("node_type_name", node_type_name, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete_node.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/managedClusters/{clusterName}/nodeTypes/{nodeTypeName}/deleteNode'} # type: ignore def get( self, resource_group_name, # type: str cluster_name, # type: str node_type_name, # type: str **kwargs # type: Any ): # type: (...) -> "_models.NodeType" """Gets a Service Fabric node type. Get a Service Fabric node type of a given managed cluster. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cluster_name: The name of the cluster resource. :type cluster_name: str :param node_type_name: The name of the node type. :type node_type_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: NodeType, or the result of cls(response) :rtype: ~service_fabric_managed_clusters_management_client.models.NodeType :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.NodeType"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-05-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), 'nodeTypeName': self._serialize.url("node_type_name", node_type_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorModel, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('NodeType', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/managedClusters/{clusterName}/nodeTypes/{nodeTypeName}'} # type: ignore def _create_or_update_initial( self, resource_group_name, # type: str cluster_name, # type: str node_type_name, # type: str parameters, # type: "_models.NodeType" **kwargs # type: Any ): # type: (...) -> "_models.NodeType" cls = kwargs.pop('cls', None) # type: ClsType["_models.NodeType"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), 'nodeTypeName': self._serialize.url("node_type_name", node_type_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'NodeType') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorModel, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('NodeType', pipeline_response) if response.status_code == 202: deserialized = self._deserialize('NodeType', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/managedClusters/{clusterName}/nodeTypes/{nodeTypeName}'} # type: ignore def begin_create_or_update( self, resource_group_name, # type: str cluster_name, # type: str node_type_name, # type: str parameters, # type: "_models.NodeType" **kwargs # type: Any ): # type: (...) -> LROPoller["_models.NodeType"] """Creates or updates a Service Fabric node type. Create or update a Service Fabric node type of a given managed cluster. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cluster_name: The name of the cluster resource. :type cluster_name: str :param node_type_name: The name of the node type. :type node_type_name: str :param parameters: The node type resource. :type parameters: ~service_fabric_managed_clusters_management_client.models.NodeType :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the ARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either NodeType or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~service_fabric_managed_clusters_management_client.models.NodeType] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.NodeType"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, cluster_name=cluster_name, node_type_name=node_type_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('NodeType', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), 'nodeTypeName': self._serialize.url("node_type_name", node_type_name, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/managedClusters/{clusterName}/nodeTypes/{nodeTypeName}'} # type: ignore def update( self, resource_group_name, # type: str cluster_name, # type: str node_type_name, # type: str parameters, # type: "_models.NodeTypeUpdateParameters" **kwargs # type: Any ): # type: (...) -> "_models.NodeType" """Update the tags of a node type resource of a given managed cluster. Update the configuration of a node type of a given managed cluster, only updating tags. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cluster_name: The name of the cluster resource. :type cluster_name: str :param node_type_name: The name of the node type. :type node_type_name: str :param parameters: The parameters to update the node type configuration. :type parameters: ~service_fabric_managed_clusters_management_client.models.NodeTypeUpdateParameters :keyword callable cls: A custom type or function that will be passed the direct response :return: NodeType, or the result of cls(response) :rtype: ~service_fabric_managed_clusters_management_client.models.NodeType :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.NodeType"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), 'nodeTypeName': self._serialize.url("node_type_name", node_type_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'NodeTypeUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorModel, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('NodeType', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/managedClusters/{clusterName}/nodeTypes/{nodeTypeName}'} # type: ignore def _delete_initial( self, resource_group_name, # type: str cluster_name, # type: str node_type_name, # type: str **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-05-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), 'nodeTypeName': self._serialize.url("node_type_name", node_type_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorModel, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/managedClusters/{clusterName}/nodeTypes/{nodeTypeName}'} # type: ignore def begin_delete( self, resource_group_name, # type: str cluster_name, # type: str node_type_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Deletes a Service Fabric node type. Delete a Service Fabric node type of a given managed cluster. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cluster_name: The name of the cluster resource. :type cluster_name: str :param node_type_name: The name of the node type. :type node_type_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the ARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, cluster_name=cluster_name, node_type_name=node_type_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'), 'nodeTypeName': self._serialize.url("node_type_name", node_type_name, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/managedClusters/{clusterName}/nodeTypes/{nodeTypeName}'} # type: ignore
# Copyright 2005-2008 by Frank Kauff & Cymon J. Cox. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. # # Bug reports welcome: fkauff@biologie.uni-kl.de or on Biopython's bugzilla. """Tree class to handle phylogenetic trees. Provides a set of methods to read and write newick-format tree descriptions, get information about trees (monphyly of taxon sets, congruence between trees, common ancestors,...) and to manipulate trees (reroot trees, split terminal nodes). """ from __future__ import print_function import random import sys from . import Nodes PRECISION_BRANCHLENGTH = 6 PRECISION_SUPPORT = 6 NODECOMMENT_START = '[&' NODECOMMENT_END = ']' class TreeError(Exception): pass class NodeData(object): """Stores tree-relevant data associated with nodes (e.g. branches or otus).""" def __init__(self, taxon=None, branchlength=0.0, support=None, comment=None): self.taxon = taxon self.branchlength = branchlength self.support = support self.comment = comment class Tree(Nodes.Chain): """Represents a tree using a chain of nodes with on predecessor (=ancestor) and multiple successors (=subclades). """ # A newick tree is parsed into nested list and then converted to a node list in two stages # mostly due to historical reasons. This could be done in one swoop). Note: parentheses ( ) and # colon : are not allowed in taxon names. This is against NEXUS standard, but makes life much # easier when parsing trees. # NOTE: Tree should store its data class in something like self.dataclass=data, # so that nodes that are generated have easy access to the data class # Some routines use automatically NodeData, this needs to be more concise def __init__(self, tree=None, weight=1.0, rooted=False, name='', data=NodeData, values_are_support=False, max_support=1.0): """Ntree(self,tree).""" Nodes.Chain.__init__(self) self.dataclass = data self.__values_are_support = values_are_support self.max_support = max_support self.weight = weight self.rooted = rooted self.name = name root = Nodes.Node(data()) self.root = self.add(root) if tree: # use the tree we have # if Tree is called from outside Nexus parser, we need to get rid of linebreaks, etc tree = tree.strip().replace('\n', '').replace('\r', '') # there's discrepancy whether newick allows semicolons et the end tree = tree.rstrip(';') subtree_info, base_info = self._parse(tree) root.data = self._add_nodedata(root.data, [[], base_info]) self._add_subtree(parent_id=root.id, tree=subtree_info) def _parse(self, tree): """Parses (a,b,c...)[[[xx]:]yy] into subcomponents and travels down recursively.""" # Remove any leading/trailing white space - want any string starting # with " (..." should be recognised as a leaf, "(..." tree = tree.strip() if tree.count('(') != tree.count(')'): raise TreeError('Parentheses do not match in (sub)tree: ' + tree) if tree.count('(') == 0: # a leaf # check if there's a colon, or a special comment, or both after the taxon name nodecomment = tree.find(NODECOMMENT_START) colon = tree.find(':') if colon == -1 and nodecomment == -1: # none return [tree, [None]] elif colon == -1 and nodecomment > -1: # only special comment return [tree[:nodecomment], self._get_values(tree[nodecomment:])] elif colon > -1 and nodecomment == -1: # only numerical values return [tree[:colon], self._get_values(tree[colon + 1:])] elif colon < nodecomment: # taxon name ends at first colon or with special comment return [tree[:colon], self._get_values(tree[colon + 1:])] else: return [tree[:nodecomment], self._get_values(tree[nodecomment:])] else: closing = tree.rfind(')') val = self._get_values(tree[closing + 1:]) if not val: val = [None] subtrees = [] plevel = 0 prev = 1 for p in range(1, closing): if tree[p] == '(': plevel += 1 elif tree[p] == ')': plevel -= 1 elif tree[p] == ',' and plevel == 0: subtrees.append(tree[prev:p]) prev = p + 1 subtrees.append(tree[prev:closing]) subclades = [self._parse(subtree) for subtree in subtrees] return [subclades, val] def _add_subtree(self, parent_id=None, tree=None): """Adds leaf or tree (in newick format) to a parent_id.""" if parent_id is None: raise TreeError('Need node_id to connect to.') for st in tree: nd = self.dataclass() nd = self._add_nodedata(nd, st) if isinstance(st[0], list): # it's a subtree sn = Nodes.Node(nd) self.add(sn, parent_id) self._add_subtree(sn.id, st[0]) else: # it's a leaf nd.taxon = st[0] leaf = Nodes.Node(nd) self.add(leaf, parent_id) def _add_nodedata(self, nd, st): """Add data to the node parsed from the comments, taxon and support. """ if isinstance(st[1][-1], str) and st[1][-1].startswith(NODECOMMENT_START): nd.comment = st[1].pop(-1) # if the first element is a string, it's the subtree node taxon elif isinstance(st[1][0], str): nd.taxon = st[1][0] st[1] = st[1][1:] if len(st) > 1: if len(st[1]) >= 2: # if there's two values, support comes first. Is that always so? nd.support = st[1][0] if st[1][1] is not None: nd.branchlength = st[1][1] elif len(st[1]) == 1: # otherwise it could be real branchlengths or support as branchlengths if not self.__values_are_support: # default if st[1][0] is not None: nd.branchlength = st[1][0] else: nd.support = st[1][0] return nd def _get_values(self, text): """Extracts values (support/branchlength) from xx[:yyy], xx.""" if text == '': return None nodecomment = None if NODECOMMENT_START in text: # if there's a [&....] comment, cut it out nc_start = text.find(NODECOMMENT_START) nc_end = text.find(NODECOMMENT_END) if nc_end == -1: raise TreeError('Error in tree description: Found %s without matching %s' % (NODECOMMENT_START, NODECOMMENT_END)) nodecomment = text[nc_start:nc_end + 1] text = text[:nc_start] + text[nc_end + 1:] # pase out supports and branchlengths, with internal node taxa info values = [] taxonomy = None for part in [t.strip() for t in text.split(":")]: if part: try: values.append(float(part)) except ValueError: assert taxonomy is None, "Two string taxonomies?" taxonomy = part if taxonomy: values.insert(0, taxonomy) if nodecomment: values.append(nodecomment) return values def _walk(self, node=None): """Return all node_ids downwards from a node.""" if node is None: node = self.root for n in self.node(node).succ: yield n for sn in self._walk(n): yield sn def node(self, node_id): """Return the instance of node_id. node = node(self,node_id) """ if node_id not in self.chain: raise TreeError('Unknown node_id: %d' % node_id) return self.chain[node_id] def split(self, parent_id=None, n=2, branchlength=1.0): """Speciation: generates n (default two) descendants of a node. [new ids] = split(self,parent_id=None,n=2,branchlength=1.0): """ if parent_id is None: raise TreeError('Missing node_id.') ids = [] parent_data = self.chain[parent_id].data for i in range(n): node = Nodes.Node() if parent_data: node.data = self.dataclass() # each node has taxon and branchlength attribute if parent_data.taxon: node.data.taxon = parent_data.taxon + str(i) node.data.branchlength = branchlength ids.append(self.add(node, parent_id)) return ids def search_taxon(self, taxon): """Returns the first matching taxon in self.data.taxon. Not restricted to terminal nodes. node_id = search_taxon(self,taxon) """ for id, node in self.chain.items(): if node.data.taxon == taxon: return id return None def prune(self, taxon): """Prunes a terminal taxon from the tree. id_of_previous_node = prune(self,taxon) If taxon is from a bifurcation, the connectiong node will be collapsed and its branchlength added to remaining terminal node. This might be no longer a meaningful value' """ id = self.search_taxon(taxon) if id is None: raise TreeError('Taxon not found: %s' % taxon) elif id not in self.get_terminals(): raise TreeError('Not a terminal taxon: %s' % taxon) else: prev = self.unlink(id) self.kill(id) if len(self.node(prev).succ) == 1: if prev == self.root: # we deleted one branch of a bifurcating root, then we have to move the root upwards self.root = self.node(self.root).succ[0] self.node(self.root).branchlength = 0.0 self.kill(prev) else: succ = self.node(prev).succ[0] new_bl = self.node(prev).data.branchlength + self.node(succ).data.branchlength self.collapse(prev) self.node(succ).data.branchlength = new_bl return prev def get_taxa(self, node_id=None): """Return a list of all otus downwards from a node. nodes = get_taxa(self,node_id=None) """ if node_id is None: node_id = self.root if node_id not in self.chain: raise TreeError('Unknown node_id: %d.' % node_id) if self.chain[node_id].succ == []: if self.chain[node_id].data: return [self.chain[node_id].data.taxon] else: return None else: list = [] for succ in self.chain[node_id].succ: list.extend(self.get_taxa(succ)) return list def get_terminals(self): """Return a list of all terminal nodes.""" return [i for i in self.all_ids() if self.node(i).succ == []] def is_terminal(self, node): """Returns True if node is a terminal node.""" return self.node(node).succ == [] def is_internal(self, node): """Returns True if node is an internal node.""" return len(self.node(node).succ) > 0 def is_preterminal(self, node): """Returns True if all successors of a node are terminal ones.""" if self.is_terminal(node): return False not in [self.is_terminal(n) for n in self.node(node).succ] else: return False def count_terminals(self, node=None): """Counts the number of terminal nodes that are attached to a node.""" if node is None: node = self.root return len([n for n in self._walk(node) if self.is_terminal(n)]) def collapse_genera(self, space_equals_underscore=True): """Collapses all subtrees which belong to the same genus (i.e share the same first word in their taxon name.)""" while True: for n in self._walk(): if self.is_terminal(n): continue taxa = self.get_taxa(n) genera = [] for t in taxa: if space_equals_underscore: t = t.replace(' ', '_') try: genus = t.split('_', 1)[0] except: genus = 'None' if genus not in genera: genera.append(genus) if len(genera) == 1: self.node(n).data.taxon = genera[0] + ' <collapsed>' # now we kill all nodes downstream nodes2kill = [kn for kn in self._walk(node=n)] for kn in nodes2kill: self.kill(kn) self.node(n).succ = [] break # break out of for loop because node list from _walk will be inconsistent else: # for loop exhausted: no genera to collapse left break # while def sum_branchlength(self, root=None, node=None): """Adds up the branchlengths from root (default self.root) to node. sum = sum_branchlength(self,root=None,node=None) """ if root is None: root = self.root if node is None: raise TreeError('Missing node id.') blen = 0.0 while node is not None and node is not root: blen += self.node(node).data.branchlength node = self.node(node).prev return blen def set_subtree(self, node): """Return subtree as a set of nested sets. sets = set_subtree(self,node) """ if self.node(node).succ == []: return self.node(node).data.taxon else: try: return frozenset(self.set_subtree(n) for n in self.node(node).succ) except: print(node) print(self.node(node).succ) for n in self.node(node).succ: print("%s %s" % (n, self.set_subtree(n))) print([self.set_subtree(n) for n in self.node(node).succ]) raise def is_identical(self, tree2): """Compare tree and tree2 for identity. result = is_identical(self,tree2) """ return self.set_subtree(self.root) == tree2.set_subtree(tree2.root) def is_compatible(self, tree2, threshold, strict=True): """Compares branches with support>threshold for compatibility. result = is_compatible(self,tree2,threshold) """ # check if both trees have the same set of taxa. strict=True enforces this. missing2 = set(self.get_taxa()) - set(tree2.get_taxa()) missing1 = set(tree2.get_taxa()) - set(self.get_taxa()) if strict and (missing1 or missing2): if missing1: print('Taxon/taxa %s is/are missing in tree %s' % (','.join(missing1), self.name)) if missing2: print('Taxon/taxa %s is/are missing in tree %s' % (','.join(missing2), tree2.name)) raise TreeError('Can\'t compare trees with different taxon compositions.') t1 = [(set(self.get_taxa(n)), self.node(n).data.support) for n in self.all_ids() if self.node(n).succ and (self.node(n).data and self.node(n).data.support and self.node(n).data.support >= threshold)] t2 = [(set(tree2.get_taxa(n)), tree2.node(n).data.support) for n in tree2.all_ids() if tree2.node(n).succ and (tree2.node(n).data and tree2.node(n).data.support and tree2.node(n).data.support >= threshold)] conflict = [] for (st1, sup1) in t1: for (st2, sup2) in t2: if not st1.issubset(st2) and not st2.issubset(st1): # don't hiccup on upstream nodes intersect, notin1, notin2 = st1 & st2, st2 - st1, st1 - st2 # all three are non-empty sets # if notin1==missing1 or notin2==missing2 <==> st1.issubset(st2) or st2.issubset(st1) ??? if intersect and not (notin1.issubset(missing1) or notin2.issubset(missing2)): # omit conflicts due to missing taxa conflict.append((st1, sup1, st2, sup2, intersect, notin1, notin2)) return conflict def common_ancestor(self, node1, node2): """Return the common ancestor that connects two nodes. node_id = common_ancestor(self,node1,node2) """ l1 = [self.root] + self.trace(self.root, node1) l2 = [self.root] + self.trace(self.root, node2) return [n for n in l1 if n in l2][-1] def distance(self, node1, node2): """Add and return the sum of the branchlengths between two nodes. dist = distance(self,node1,node2) """ ca = self.common_ancestor(node1, node2) return self.sum_branchlength(ca, node1) + self.sum_branchlength(ca, node2) def is_monophyletic(self, taxon_list): """Return node_id of common ancestor if taxon_list is monophyletic, -1 otherwise. result = is_monophyletic(self,taxon_list) """ if isinstance(taxon_list, str): taxon_set = set([taxon_list]) else: taxon_set = set(taxon_list) node_id = self.root while True: subclade_taxa = set(self.get_taxa(node_id)) if subclade_taxa == taxon_set: # are we there? return node_id else: # check subnodes for subnode in self.chain[node_id].succ: if set(self.get_taxa(subnode)).issuperset(taxon_set): # taxon_set is downstream node_id = subnode break # out of for loop else: return -1 # taxon set was not with successors, for loop exhausted def is_bifurcating(self, node=None): """Return True if tree downstream of node is strictly bifurcating.""" if node is None: node = self.root if node == self.root and len(self.node(node).succ) == 3: # root can be trifurcating, because it has no ancestor return self.is_bifurcating(self.node(node).succ[0]) and \ self.is_bifurcating(self.node(node).succ[1]) and \ self.is_bifurcating(self.node(node).succ[2]) if len(self.node(node).succ) == 2: return self.is_bifurcating(self.node(node).succ[0]) and self.is_bifurcating(self.node(node).succ[1]) elif len(self.node(node).succ) == 0: return True else: return False def branchlength2support(self): """Move values stored in data.branchlength to data.support, and set branchlength to 0.0 This is necessary when support has been stored as branchlength (e.g. paup), and has thus been read in as branchlength. """ for n in self.chain: self.node(n).data.support = self.node(n).data.branchlength self.node(n).data.branchlength = 0.0 def convert_absolute_support(self, nrep): """Convert absolute support (clade-count) to rel. frequencies. Some software (e.g. PHYLIP consense) just calculate how often clades appear, instead of calculating relative frequencies.""" for n in self._walk(): if self.node(n).data.support: self.node(n).data.support /= float(nrep) def has_support(self, node=None): """Returns True if any of the nodes has data.support != None.""" for n in self._walk(node): if self.node(n).data.support: return True else: return False def randomize(self, ntax=None, taxon_list=None, branchlength=1.0, branchlength_sd=None, bifurcate=True): """Generates a random tree with ntax taxa and/or taxa from taxlabels. new_tree = randomize(self,ntax=None,taxon_list=None,branchlength=1.0,branchlength_sd=None,bifurcate=True) Trees are bifurcating by default. (Polytomies not yet supported). """ if not ntax and taxon_list: ntax = len(taxon_list) elif not taxon_list and ntax: taxon_list = ['taxon' + str(i + 1) for i in range(ntax)] elif not ntax and not taxon_list: raise TreeError('Either numer of taxa or list of taxa must be specified.') elif ntax != len(taxon_list): raise TreeError('Length of taxon list must correspond to ntax.') # initiate self with empty root self.__init__() terminals = self.get_terminals() # bifurcate randomly at terminal nodes until ntax is reached while len(terminals) < ntax: newsplit = random.choice(terminals) new_terminals = self.split(parent_id=newsplit, branchlength=branchlength) # if desired, give some variation to the branch length if branchlength_sd: for nt in new_terminals: bl = random.gauss(branchlength, branchlength_sd) if bl < 0: bl = 0 self.node(nt).data.branchlength = bl terminals.extend(new_terminals) terminals.remove(newsplit) # distribute taxon labels randomly random.shuffle(taxon_list) for (node, name) in zip(terminals, taxon_list): self.node(node).data.taxon = name def display(self): """Quick and dirty lists of all nodes.""" table = [('#', 'taxon', 'prev', 'succ', 'brlen', 'blen (sum)', 'support', 'comment')] # Sort this to be consistent across CPython, Jython, etc for i in sorted(self.all_ids()): n = self.node(i) if not n.data: table.append((str(i), '-', str(n.prev), str(n.succ), '-', '-', '-', '-')) else: tx = n.data.taxon if not tx: tx = '-' blength = "%0.2f" % n.data.branchlength if blength is None: blength = '-' sum_blength = '-' else: sum_blength = "%0.2f" % self.sum_branchlength(node=i) support = n.data.support if support is None: support = '-' else: support = "%0.2f" % support comment = n.data.comment if comment is None: comment = '-' table.append((str(i), tx, str(n.prev), str(n.succ), blength, sum_blength, support, comment)) print('\n'.join('%3s %32s %15s %15s %8s %10s %8s %20s' % l for l in table)) print('\nRoot: %s' % self.root) def to_string(self, support_as_branchlengths=False, branchlengths_only=False, plain=True, plain_newick=False, ladderize=None, ignore_comments=True): """Return a paup compatible tree line.""" # if there's a conflict in the arguments, we override plain=True if support_as_branchlengths or branchlengths_only: plain = False self.support_as_branchlengths = support_as_branchlengths self.branchlengths_only = branchlengths_only self.ignore_comments = ignore_comments self.plain = plain def make_info_string(data, terminal=False): """Creates nicely formatted support/branchlengths.""" # CHECK FORMATTING if self.plain: # plain tree only. That's easy. info_string = '' elif self.support_as_branchlengths: # support as branchlengths (eg. PAUP), ignore actual branchlengths if terminal: # terminal branches have 100% support info_string = ':%1.2f' % self.max_support elif data.support: info_string = ':%1.2f' % (data.support) else: info_string = ':0.00' elif self.branchlengths_only: # write only branchlengths, ignore support info_string = ':%1.5f' % (data.branchlength) else: # write suport and branchlengths (e.g. .con tree of mrbayes) if terminal: info_string = ':%1.5f' % (data.branchlength) else: if data.branchlength is not None and data.support is not None: # we have blen and suppport info_string = '%1.2f:%1.5f' % (data.support, data.branchlength) elif data.branchlength is not None: # we have only blen info_string = '0.00000:%1.5f' % (data.branchlength) elif data.support is not None: # we have only support info_string = '%1.2f:0.00000' % (data.support) else: info_string = '0.00:0.00000' if not ignore_comments and hasattr(data, 'nodecomment'): info_string = str(data.nodecomment) + info_string return info_string def ladderize_nodes(nodes, ladderize=None): """Sorts node numbers according to the number of terminal nodes.""" if ladderize in ['left', 'LEFT', 'right', 'RIGHT']: succnode_terminals = sorted((self.count_terminals(node=n), n) for n in nodes) if (ladderize == 'right' or ladderize == 'RIGHT'): succnode_terminals.reverse() if succnode_terminals: succnodes = zip(*succnode_terminals)[1] else: succnodes = [] else: succnodes = nodes return succnodes def newickize(node, ladderize=None): """Convert a node tree to a newick tree recursively.""" if not self.node(node).succ: # terminal return self.node(node).data.taxon + make_info_string(self.node(node).data, terminal=True) else: succnodes = ladderize_nodes(self.node(node).succ, ladderize=ladderize) subtrees = [newickize(sn, ladderize=ladderize) for sn in succnodes] return '(%s)%s' % (','.join(subtrees), make_info_string(self.node(node).data)) treeline = ['tree'] if self.name: treeline.append(self.name) else: treeline.append('a_tree') treeline.append('=') if self.weight != 1: treeline.append('[&W%s]' % str(round(float(self.weight), 3))) if self.rooted: treeline.append('[&R]') succnodes = ladderize_nodes(self.node(self.root).succ) subtrees = [newickize(sn, ladderize=ladderize) for sn in succnodes] treeline.append('(%s)' % ','.join(subtrees)) if plain_newick: return treeline[-1] else: return ' '.join(treeline) + ';' def __str__(self): """Short version of to_string(), gives plain tree""" return self.to_string(plain=True) def unroot(self): """Defines a unrooted Tree structure, using data of a rooted Tree.""" # travel down the rooted tree structure and save all branches and the nodes they connect def _get_branches(node): branches = [] for b in self.node(node).succ: branches.append([node, b, self.node(b).data.branchlength, self.node(b).data.support]) branches.extend(_get_branches(b)) return branches self.unrooted = _get_branches(self.root) # if root is bifurcating, then it is eliminated if len(self.node(self.root).succ) == 2: # find the two branches that connect to root rootbranches = [b for b in self.unrooted if self.root in b[:2]] b1 = self.unrooted.pop(self.unrooted.index(rootbranches[0])) b2 = self.unrooted.pop(self.unrooted.index(rootbranches[1])) # Connect them two each other. If both have support, it should be identical (or one set to None?). # If both have branchlengths, they will be added newbranch = [b1[1], b2[1], b1[2] + b2[2]] if b1[3] is None: newbranch.append(b2[3]) # either None (both rootbranches are unsupported) or some support elif b2[3] is None: newbranch.append(b1[3]) # dito elif b1[3] == b2[3]: newbranch.append(b1[3]) # identical support elif b1[3] == 0 or b2[3] == 0: newbranch.append(b1[3] + b2[3]) # one is 0, take the other else: raise TreeError('Support mismatch in bifurcating root: %f, %f' % (float(b1[3]), float(b2[3]))) self.unrooted.append(newbranch) def root_with_outgroup(self, outgroup=None): def _connect_subtree(parent, child): """Hook subtree starting with node child to parent.""" for i, branch in enumerate(self.unrooted): if parent in branch[:2] and child in branch[:2]: branch = self.unrooted.pop(i) break else: raise TreeError('Unable to connect nodes for rooting: nodes %d and %d are not connected' % (parent, child)) self.link(parent, child) self.node(child).data.branchlength = branch[2] self.node(child).data.support = branch[3] # now check if there are more branches connected to the child, and if so, connect them child_branches = [b for b in self.unrooted if child in b[:2]] for b in child_branches: if child == b[0]: succ = b[1] else: succ = b[0] _connect_subtree(child, succ) # check the outgroup we're supposed to root with if outgroup is None: return self.root outgroup_node = self.is_monophyletic(outgroup) if outgroup_node == -1: return -1 # if tree is already rooted with outgroup on a bifurcating root, # or the outgroup includes all taxa on the tree, then we're fine if (len(self.node(self.root).succ) == 2 and outgroup_node in self.node(self.root).succ) or outgroup_node == self.root: return self.root self.unroot() # now we find the branch that connects outgroup and ingroup # print(self.node(outgroup_node).prev) for i, b in enumerate(self.unrooted): if outgroup_node in b[:2] and self.node(outgroup_node).prev in b[:2]: root_branch = self.unrooted.pop(i) break else: raise TreeError('Unrooted and rooted Tree do not match') if outgroup_node == root_branch[1]: ingroup_node = root_branch[0] else: ingroup_node = root_branch[1] # now we destroy the old tree structure, but keep node data. Nodes will be reconnected according to new outgroup for n in self.all_ids(): self.node(n).prev = None self.node(n).succ = [] # now we just add both subtrees (outgroup and ingroup) branch for branch root = Nodes.Node(data=NodeData()) # new root self.add(root) # add to tree description self.root = root.id # set as root self.unrooted.append([root.id, ingroup_node, root_branch[2], root_branch[3]]) # add branch to ingroup to unrooted tree self.unrooted.append([root.id, outgroup_node, 0.0, 0.0]) # add branch to outgroup to unrooted tree _connect_subtree(root.id, ingroup_node) # add ingroup _connect_subtree(root.id, outgroup_node) # add outgroup # if theres still a lonely node in self.chain, then it's the old root, and we delete it oldroot = [i for i in self.all_ids() if self.node(i).prev is None and i != self.root] if len(oldroot) > 1: raise TreeError('Isolated nodes in tree description: %s' % ','.join(oldroot)) elif len(oldroot) == 1: self.kill(oldroot[0]) return self.root def merge_with_support(self, bstrees=None, constree=None, threshold=0.5, outgroup=None): """Merges clade support (from consensus or list of bootstrap-trees) with phylogeny. tree=merge_bootstrap(phylo,bs_tree=<list_of_trees>) or tree=merge_bootstrap(phylo,consree=consensus_tree with clade support) """ if bstrees and constree: raise TreeError('Specify either list of bootstrap trees or consensus tree, not both') if not (bstrees or constree): raise TreeError('Specify either list of bootstrap trees or consensus tree.') # no outgroup specified: use the smallest clade of the root if outgroup is None: try: succnodes = self.node(self.root).succ smallest = min((len(self.get_taxa(n)), n) for n in succnodes) outgroup = self.get_taxa(smallest[1]) except: raise TreeError("Error determining outgroup.") else: # root with user specified outgroup self.root_with_outgroup(outgroup) if bstrees: # calculate consensus constree = consensus(bstrees, threshold=threshold, outgroup=outgroup) else: if not constree.has_support(): constree.branchlength2support() constree.root_with_outgroup(outgroup) # now we travel all nodes, and add support from consensus, if the clade is present in both for pnode in self._walk(): cnode = constree.is_monophyletic(self.get_taxa(pnode)) if cnode > -1: self.node(pnode).data.support = constree.node(cnode).data.support def consensus(trees, threshold=0.5, outgroup=None): """Compute a majority rule consensus tree of all clades with relative frequency>=threshold from a list of trees.""" total = len(trees) if total == 0: return None # shouldn't we make sure that it's NodeData or subclass?? dataclass = trees[0].dataclass max_support = trees[0].max_support clades = {} # countclades={} alltaxa = set(trees[0].get_taxa()) # calculate calde frequencies c = 0 for t in trees: c += 1 # if c%100==0: # print(c) if alltaxa != set(t.get_taxa()): raise TreeError('Trees for consensus must contain the same taxa') t.root_with_outgroup(outgroup=outgroup) for st_node in t._walk(t.root): subclade_taxa = sorted(t.get_taxa(st_node)) subclade_taxa = str(subclade_taxa) # lists are not hashable if subclade_taxa in clades: clades[subclade_taxa] += float(t.weight) / total else: clades[subclade_taxa] = float(t.weight) / total # if subclade_taxa in countclades: # countclades[subclade_taxa]+=t.weight # else: # countclades[subclade_taxa]=t.weight # weed out clades below threshold delclades = [c for c, p in clades.items() if round(p, 3) < threshold] # round can be necessary for c in delclades: del clades[c] # create a tree with a root node consensus = Tree(name='consensus_%2.1f' % float(threshold), data=dataclass) # each clade needs a node in the new tree, add them as isolated nodes for c, s in clades.items(): node = Nodes.Node(data=dataclass()) node.data.support = s node.data.taxon = set(eval(c)) consensus.add(node) # set root node data consensus.node(consensus.root).data.support = None consensus.node(consensus.root).data.taxon = alltaxa # we sort the nodes by no. of taxa in the clade, so root will be the last consensus_ids = consensus.all_ids() consensus_ids.sort(lambda x, y: len(consensus.node(x).data.taxon) - len(consensus.node(y).data.taxon)) # now we just have to hook each node to the next smallest node that includes all taxa of the current for i, current in enumerate(consensus_ids[:-1]): # skip the last one which is the root # print('----') # print('current: %s' % consensus.node(current).data.taxon) # search remaining nodes for parent in consensus_ids[i + 1:]: # print('parent: %s' % consensus.node(parent).data.taxon) if consensus.node(parent).data.taxon.issuperset(consensus.node(current).data.taxon): break else: sys.exit('corrupt tree structure?') # internal nodes don't have taxa if len(consensus.node(current).data.taxon) == 1: consensus.node(current).data.taxon = consensus.node(current).data.taxon.pop() # reset the support for terminal nodes to maximum # consensus.node(current).data.support=max_support else: consensus.node(current).data.taxon = None consensus.link(parent, current) # eliminate root taxon name consensus.node(consensus_ids[-1]).data.taxon = None if alltaxa != set(consensus.get_taxa()): raise TreeError('FATAL ERROR: consensus tree is corrupt') return consensus
""" Tests for Consulate.acl """ import json import uuid import random import httmock import consulate from consulate import exceptions from . import base ACL_OLD_RULES = """key "" { policy = "read" } key "foo/" { policy = "write" } """ ACL_NEW_RULES = """key_prefix "" { policy = "read" } key "foo/" { policy = "write" } """ ACL_NEW_UPDATE_RULES = """key_prefix "" { policy = "deny" } key "foo/" { policy = "read" } """ POLICYLINKS_SAMPLE = [ dict(Name="policylink_sample"), ] POLICYLINKS_UPDATE_SAMPLE = [ dict(Name="policylink_sample"), dict(Name="policylink_update_sample") ] SERVICE_IDENTITIES_SAMPLE = [dict(ServiceName="db", Datacenters=list("dc1"))] class TestCase(base.TestCase): @staticmethod def uuidv4(): return str(uuid.uuid4()) @staticmethod def random(): return str(random.randint(0, 999999)) def _generate_policies(self): sample = self.consul.acl.create_policy(self.random()) sample_update = self.consul.acl.create_policy(self.random()) return [dict(ID=sample["ID"]), dict(ID=sample_update["ID"])] def _generate_roles(self): role = self.consul.acl.create_role(self.random()) return [dict(ID=role["ID"])] def test_bootstrap_request_exception(self): @httmock.all_requests def response_content(_url_unused, _request): raise OSError with httmock.HTTMock(response_content): with self.assertRaises(exceptions.RequestError): self.consul.acl.bootstrap() def test_bootstrap_success(self): expectation = self.uuidv4() @httmock.all_requests def response_content(_url_unused, request): return httmock.response(200, json.dumps({'ID': expectation}), {}, None, 0, request) with httmock.HTTMock(response_content): result = self.consul.acl.bootstrap() self.assertEqual(result, expectation) def test_bootstrap_raises(self): with self.assertRaises(consulate.Forbidden): self.consul.acl.bootstrap() def test_clone_bad_acl_id(self): with self.assertRaises(consulate.Forbidden): self.consul.acl.clone(self.uuidv4()) def test_clone_forbidden(self): with self.assertRaises(consulate.Forbidden): self.forbidden_consul.acl.clone(self.uuidv4()) def test_create_and_destroy(self): acl_id = self.consul.acl.create(self.uuidv4()) self.assertTrue(self.consul.acl.destroy(acl_id)) def test_create_with_rules(self): acl_id = self.consul.acl.create(self.uuidv4(), rules=ACL_OLD_RULES) value = self.consul.acl.info(acl_id) self.assertEqual(value['Rules'], ACL_OLD_RULES) def test_create_and_info(self): acl_id = self.consul.acl.create(self.uuidv4()) self.assertIsNotNone(acl_id) data = self.consul.acl.info(acl_id) self.assertIsNotNone(data) self.assertEqual(acl_id, data.get('ID')) def test_create_and_list(self): acl_id = self.consul.acl.create(self.uuidv4()) data = self.consul.acl.list() self.assertIn(acl_id, [r.get('ID') for r in data]) def test_create_and_clone(self): acl_id = self.consul.acl.create(self.uuidv4()) clone_id = self.consul.acl.clone(acl_id) data = self.consul.acl.list() self.assertIn(clone_id, [r.get('ID') for r in data]) def test_create_and_update(self): acl_id = str(self.consul.acl.create(self.uuidv4())) self.consul.acl.update(acl_id, 'Foo') data = self.consul.acl.list() self.assertIn('Foo', [r.get('Name') for r in data]) self.assertIn(acl_id, [r.get('ID') for r in data]) def test_create_forbidden(self): with self.assertRaises(consulate.Forbidden): self.forbidden_consul.acl.create(self.uuidv4()) def test_destroy_forbidden(self): with self.assertRaises(consulate.Forbidden): self.forbidden_consul.acl.destroy(self.uuidv4()) def test_info_acl_id_not_found(self): with self.assertRaises(consulate.NotFound): self.forbidden_consul.acl.info(self.uuidv4()) def test_list_request_exception(self): with httmock.HTTMock(base.raise_oserror): with self.assertRaises(exceptions.RequestError): self.consul.acl.list() def test_replication(self): result = self.forbidden_consul.acl.replication() self.assertFalse(result['Enabled']) self.assertFalse(result['Running']) def test_update_not_found_adds_new_key(self): acl_id = self.consul.acl.update(self.uuidv4(), 'Foo2') data = self.consul.acl.list() self.assertIn('Foo2', [r.get('Name') for r in data]) self.assertIn(acl_id, [r.get('ID') for r in data]) def test_update_with_rules(self): acl_id = self.consul.acl.update(self.uuidv4(), name='test', rules=ACL_OLD_RULES) value = self.consul.acl.info(acl_id) self.assertEqual(value['Rules'], ACL_OLD_RULES) def test_update_forbidden(self): with self.assertRaises(consulate.Forbidden): self.forbidden_consul.acl.update(self.uuidv4(), name='test') # NOTE: Everything above here is deprecated post consul-1.4.0 def test_create_policy(self): name = self.random() result = self.consul.acl.create_policy(name=name, rules=ACL_NEW_RULES) self.assertEqual(result['Rules'], ACL_NEW_RULES) def test_create_and_read_policy(self): name = self.random() value = self.consul.acl.create_policy(name=name, rules=ACL_NEW_RULES) result = self.consul.acl.read_policy(value["ID"]) self.assertEqual(result['Rules'], ACL_NEW_RULES) def test_create_and_update_policy(self): name = self.random() value = self.consul.acl.create_policy(name=name, rules=ACL_NEW_RULES) result = self.consul.acl.update_policy(value["ID"], str(value["Name"]), rules=ACL_NEW_UPDATE_RULES) self.assertGreater(result["ModifyIndex"], result["CreateIndex"]) def test_create_and_delete_policy(self): name = self.random() value = self.consul.acl.create_policy(name=name, rules=ACL_NEW_RULES) result = self.consul.acl.delete_policy(value["ID"]) self.assertTrue(result) def test_list_policy_exception(self): with httmock.HTTMock(base.raise_oserror): with self.assertRaises(exceptions.RequestError): self.consul.acl.list_policies() def test_create_role(self): name = self.random() result = self.consul.acl.create_role( name=name, policies=self._generate_policies(), service_identities=SERVICE_IDENTITIES_SAMPLE) self.assertEqual(result['Name'], name) def test_create_and_read_role(self): name = self.random() value = self.consul.acl.create_role( name=name, policies=self._generate_policies(), service_identities=SERVICE_IDENTITIES_SAMPLE) result = self.consul.acl.read_role(value["ID"]) self.assertEqual(result['ID'], value['ID']) def test_create_and_update_role(self): name = self.random() value = self.consul.acl.create_role( name=name, policies=self._generate_policies(), service_identities=SERVICE_IDENTITIES_SAMPLE) result = self.consul.acl.update_role( value["ID"], str(value["Name"]), policies=self._generate_policies()) self.assertGreater(result["ModifyIndex"], result["CreateIndex"]) def test_create_and_delete_role(self): name = self.random() value = self.consul.acl.create_role( name=name, policies=self._generate_policies(), service_identities=SERVICE_IDENTITIES_SAMPLE) result = self.consul.acl.delete_role(value["ID"]) self.assertTrue(result) def test_list_roles_exception(self): with httmock.HTTMock(base.raise_oserror): with self.assertRaises(exceptions.RequestError): self.consul.acl.list_roles() def test_create_token(self): secret_id = self.uuidv4() accessor_id = self.uuidv4() result = self.consul.acl.create_token( accessor_id=accessor_id, secret_id=secret_id, roles=self._generate_roles(), policies=self._generate_policies(), service_identities=SERVICE_IDENTITIES_SAMPLE) self.assertEqual(result['AccessorID'], accessor_id) self.assertEqual(result['SecretID'], secret_id) def test_create_and_read_token(self): secret_id = self.uuidv4() accessor_id = self.uuidv4() value = self.consul.acl.create_token( accessor_id=accessor_id, secret_id=secret_id, roles=self._generate_roles(), policies=self._generate_policies(), service_identities=SERVICE_IDENTITIES_SAMPLE) result = self.consul.acl.read_token(value["AccessorID"]) self.assertEqual(result['AccessorID'], accessor_id) def test_create_and_update_token(self): secret_id = self.uuidv4() accessor_id = self.uuidv4() value = self.consul.acl.create_token( accessor_id=accessor_id, secret_id=secret_id, roles=self._generate_roles(), policies=self._generate_policies(), service_identities=SERVICE_IDENTITIES_SAMPLE) result = self.consul.acl.update_token( str(value["AccessorID"]), policies=self._generate_policies()) self.assertGreater(result["ModifyIndex"], result["CreateIndex"]) def test_create_and_clone_token(self): secret_id = self.uuidv4() accessor_id = self.uuidv4() clone_description = "clone token of " + accessor_id value = self.consul.acl.create_token( accessor_id=accessor_id, secret_id=secret_id, roles=self._generate_roles(), policies=self._generate_policies(), service_identities=SERVICE_IDENTITIES_SAMPLE) result = self.consul.acl.clone_token(value["AccessorID"], description=clone_description) self.assertEqual(result["Description"], clone_description) def test_create_and_delete_token(self): secret_id = self.uuidv4() accessor_id = self.uuidv4() value = self.consul.acl.create_token( accessor_id=accessor_id, secret_id=secret_id, roles=self._generate_roles(), policies=self._generate_policies(), service_identities=SERVICE_IDENTITIES_SAMPLE) result = self.consul.acl.delete_token(value["AccessorID"]) self.assertTrue(result)
#!/usr/bin/env python import codecs from datetime import datetime import json import time import urllib import subprocess from decimal import Decimal from flask import Markup, g, render_template, request from slimit import minify from smartypants import smartypants import app_config import copytext class BetterJSONEncoder(json.JSONEncoder): """ A JSON encoder that intelligently handles datetimes. """ def default(self, obj): if isinstance(obj, datetime): encoded_object = obj.isoformat() else: encoded_object = json.JSONEncoder.default(self, obj) return encoded_object class Includer(object): """ Base class for Javascript and CSS psuedo-template-tags. See `make_context` for an explanation of `asset_depth`. """ def __init__(self, asset_depth=0): self.includes = [] self.tag_string = None self.asset_depth = asset_depth def push(self, path): self.includes.append(path) return '' def _compress(self): raise NotImplementedError() def _relativize_path(self, path): relative_path = path depth = len(request.path.split('/')) - (2 + self.asset_depth) while depth > 0: relative_path = '../%s' % relative_path depth -= 1 return relative_path def render(self, path): if getattr(g, 'compile_includes', False): if path in g.compiled_includes: timestamp_path = g.compiled_includes[path] else: # Add a querystring to the rendered filename to prevent caching timestamp_path = '%s?%i' % (path, int(time.time())) out_path = 'www/%s' % path if path not in g.compiled_includes: print 'Rendering %s' % out_path with codecs.open(out_path, 'w', encoding='utf-8') as f: f.write(self._compress()) # See "fab render" g.compiled_includes[path] = timestamp_path markup = Markup(self.tag_string % self._relativize_path(timestamp_path)) else: response = ','.join(self.includes) response = '\n'.join([ self.tag_string % self._relativize_path(src) for src in self.includes ]) markup = Markup(response) del self.includes[:] return markup class JavascriptIncluder(Includer): """ Psuedo-template tag that handles collecting Javascript and serving appropriate clean or compressed versions. """ def __init__(self, *args, **kwargs): Includer.__init__(self, *args, **kwargs) self.tag_string = '<script type="text/javascript" src="%s"></script>' def _compress(self): output = [] src_paths = [] for src in self.includes: src_paths.append('www/%s' % src) with codecs.open('www/%s' % src, encoding='utf-8') as f: print '- compressing %s' % src output.append(minify(f.read())) context = make_context() context['paths'] = src_paths header = render_template('_js_header.js', **context) output.insert(0, header) return '\n'.join(output) class CSSIncluder(Includer): """ Psuedo-template tag that handles collecting CSS and serving appropriate clean or compressed versions. """ def __init__(self, *args, **kwargs): Includer.__init__(self, *args, **kwargs) self.tag_string = '<link rel="stylesheet" type="text/css" href="%s" />' def _compress(self): output = [] src_paths = [] for src in self.includes: src_paths.append('%s' % src) try: compressed_src = subprocess.check_output(["node_modules/less/bin/lessc", "-x", src]) output.append(compressed_src) except: print 'It looks like "lessc" isn\'t installed. Try running: "npm install"' raise context = make_context() context['paths'] = src_paths header = render_template('_css_header.css', **context) output.insert(0, header) return '\n'.join(output) def flatten_app_config(): """ Returns a copy of app_config containing only configuration variables. """ config = {} # Only all-caps [constant] vars get included for k, v in app_config.__dict__.items(): if k.upper() == k: config[k] = v return config def make_context(asset_depth=0): """ Create a base-context for rendering views. Includes app_config and JS/CSS includers. `asset_depth` indicates how far into the url hierarchy the assets are hosted. If 0, then they are at the root. If 1 then at /foo/, etc. """ context = flatten_app_config() # TODO: Re-add copy spreadsheet, if needed # try: # context['COPY'] = copytext.Copy(app_config.COPY_PATH) # except copytext.CopyException: # pass context['JS'] = JavascriptIncluder(asset_depth=asset_depth) context['CSS'] = CSSIncluder(asset_depth=asset_depth) return context def urlencode_filter(s): """ Filter to urlencode strings. """ if type(s) == 'Markup': s = s.unescape() # Evaulate COPY elements if type(s) is not unicode: s = unicode(s) s = s.encode('utf8') s = urllib.quote_plus(s) return Markup(s) def smarty_filter(s): """ Filter to smartypants strings. """ if type(s) == 'Markup': s = s.unescape() # Evaulate COPY elements if type(s) is not unicode: s = unicode(s) s = s.encode('utf-8') s = smartypants(s) try: return Markup(s) except: print 'This string failed to encode: %s' % s return Markup(s) def format_commas_filter(s, precision=1): """ Formats numbers nicely """ if s: fmt = '{{:,.{0}f}}'.format(precision) return fmt.format(Decimal(s)) else: return '' def format_thousands_filter(s, show_k=True, precision=1): """ Format 1,000 as 1k """ if int(s) % 1000 == 0: s = int(s) / 1000 if show_k: return '{0}k'.format(s) else: return s else: return format_commas_filter(s, 0)
"""Support for Z-Wave lights.""" import logging from threading import Timer from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, ATTR_TRANSITION, ATTR_WHITE_VALUE, DOMAIN, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, SUPPORT_TRANSITION, SUPPORT_WHITE_VALUE, LightEntity, ) from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect import homeassistant.util.color as color_util from . import CONF_REFRESH_DELAY, CONF_REFRESH_VALUE, ZWaveDeviceEntity, const _LOGGER = logging.getLogger(__name__) COLOR_CHANNEL_WARM_WHITE = 0x01 COLOR_CHANNEL_COLD_WHITE = 0x02 COLOR_CHANNEL_RED = 0x04 COLOR_CHANNEL_GREEN = 0x08 COLOR_CHANNEL_BLUE = 0x10 # Some bulbs have an independent warm and cool white light LEDs. These need # to be treated differently, aka the zw098 workaround. Ensure these are added # to DEVICE_MAPPINGS below. # (Manufacturer ID, Product ID) from # https://github.com/OpenZWave/open-zwave/blob/master/config/manufacturer_specific.xml AEOTEC_ZW098_LED_BULB_LIGHT = (0x86, 0x62) AEOTEC_ZWA001_LED_BULB_LIGHT = (0x371, 0x1) AEOTEC_ZWA002_LED_BULB_LIGHT = (0x371, 0x2) HANK_HKZW_RGB01_LED_BULB_LIGHT = (0x208, 0x4) ZIPATO_RGB_BULB_2_LED_BULB_LIGHT = (0x131, 0x3) WORKAROUND_ZW098 = "zw098" DEVICE_MAPPINGS = { AEOTEC_ZW098_LED_BULB_LIGHT: WORKAROUND_ZW098, AEOTEC_ZWA001_LED_BULB_LIGHT: WORKAROUND_ZW098, AEOTEC_ZWA002_LED_BULB_LIGHT: WORKAROUND_ZW098, HANK_HKZW_RGB01_LED_BULB_LIGHT: WORKAROUND_ZW098, ZIPATO_RGB_BULB_2_LED_BULB_LIGHT: WORKAROUND_ZW098, } # Generate midpoint color temperatures for bulbs that have limited # support for white light colors TEMP_COLOR_MAX = 500 # mireds (inverted) TEMP_COLOR_MIN = 154 TEMP_MID_HASS = (TEMP_COLOR_MAX - TEMP_COLOR_MIN) / 2 + TEMP_COLOR_MIN TEMP_WARM_HASS = (TEMP_COLOR_MAX - TEMP_COLOR_MIN) / 3 * 2 + TEMP_COLOR_MIN TEMP_COLD_HASS = (TEMP_COLOR_MAX - TEMP_COLOR_MIN) / 3 + TEMP_COLOR_MIN async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Z-Wave Light from Config Entry.""" @callback def async_add_light(light): """Add Z-Wave Light.""" async_add_entities([light]) async_dispatcher_connect(hass, "zwave_new_light", async_add_light) def get_device(node, values, node_config, **kwargs): """Create Z-Wave entity device.""" refresh = node_config.get(CONF_REFRESH_VALUE) delay = node_config.get(CONF_REFRESH_DELAY) _LOGGER.debug( "node=%d value=%d node_config=%s CONF_REFRESH_VALUE=%s" " CONF_REFRESH_DELAY=%s", node.node_id, values.primary.value_id, node_config, refresh, delay, ) if node.has_command_class(const.COMMAND_CLASS_SWITCH_COLOR): return ZwaveColorLight(values, refresh, delay) return ZwaveDimmer(values, refresh, delay) def brightness_state(value): """Return the brightness and state.""" if value.data > 0: return round((value.data / 99) * 255), STATE_ON return 0, STATE_OFF def byte_to_zwave_brightness(value): """Convert brightness in 0-255 scale to 0-99 scale. `value` -- (int) Brightness byte value from 0-255. """ if value > 0: return max(1, round((value / 255) * 99)) return 0 def ct_to_hs(temp): """Convert color temperature (mireds) to hs.""" colorlist = list( color_util.color_temperature_to_hs( color_util.color_temperature_mired_to_kelvin(temp) ) ) return [int(val) for val in colorlist] class ZwaveDimmer(ZWaveDeviceEntity, LightEntity): """Representation of a Z-Wave dimmer.""" def __init__(self, values, refresh, delay): """Initialize the light.""" ZWaveDeviceEntity.__init__(self, values, DOMAIN) self._brightness = None self._state = None self._supported_features = None self._delay = delay self._refresh_value = refresh self._zw098 = None # Enable appropriate workaround flags for our device # Make sure that we have values for the key before converting to int if self.node.manufacturer_id.strip() and self.node.product_id.strip(): specific_sensor_key = ( int(self.node.manufacturer_id, 16), int(self.node.product_id, 16), ) if ( specific_sensor_key in DEVICE_MAPPINGS and DEVICE_MAPPINGS[specific_sensor_key] == WORKAROUND_ZW098 ): _LOGGER.debug("AEOTEC ZW098 workaround enabled") self._zw098 = 1 # Used for value change event handling self._refreshing = False self._timer = None _LOGGER.debug( "self._refreshing=%s self.delay=%s", self._refresh_value, self._delay ) self.value_added() self.update_properties() def update_properties(self): """Update internal properties based on zwave values.""" # Brightness self._brightness, self._state = brightness_state(self.values.primary) def value_added(self): """Call when a new value is added to this entity.""" self._supported_features = SUPPORT_BRIGHTNESS if self.values.dimming_duration is not None: self._supported_features |= SUPPORT_TRANSITION def value_changed(self): """Call when a value for this entity's node has changed.""" if self._refresh_value: if self._refreshing: self._refreshing = False else: def _refresh_value(): """Use timer callback for delayed value refresh.""" self._refreshing = True self.values.primary.refresh() if self._timer is not None and self._timer.is_alive(): self._timer.cancel() self._timer = Timer(self._delay, _refresh_value) self._timer.start() return super().value_changed() @property def brightness(self): """Return the brightness of this light between 0..255.""" return self._brightness @property def is_on(self): """Return true if device is on.""" return self._state == STATE_ON @property def supported_features(self): """Flag supported features.""" return self._supported_features def _set_duration(self, **kwargs): """Set the transition time for the brightness value. Zwave Dimming Duration values: 0x00 = instant 0x01-0x7F = 1 second to 127 seconds 0x80-0xFE = 1 minute to 127 minutes 0xFF = factory default """ if self.values.dimming_duration is None: if ATTR_TRANSITION in kwargs: _LOGGER.debug("Dimming not supported by %s", self.entity_id) return if ATTR_TRANSITION not in kwargs: self.values.dimming_duration.data = 0xFF return transition = kwargs[ATTR_TRANSITION] if transition <= 127: self.values.dimming_duration.data = int(transition) elif transition > 7620: self.values.dimming_duration.data = 0xFE _LOGGER.warning("Transition clipped to 127 minutes for %s", self.entity_id) else: minutes = int(transition / 60) _LOGGER.debug( "Transition rounded to %d minutes for %s", minutes, self.entity_id ) self.values.dimming_duration.data = minutes + 0x7F def turn_on(self, **kwargs): """Turn the device on.""" self._set_duration(**kwargs) # Zwave multilevel switches use a range of [0, 99] to control # brightness. Level 255 means to set it to previous value. if ATTR_BRIGHTNESS in kwargs: self._brightness = kwargs[ATTR_BRIGHTNESS] brightness = byte_to_zwave_brightness(self._brightness) else: brightness = 255 if self.node.set_dimmer(self.values.primary.value_id, brightness): self._state = STATE_ON def turn_off(self, **kwargs): """Turn the device off.""" self._set_duration(**kwargs) if self.node.set_dimmer(self.values.primary.value_id, 0): self._state = STATE_OFF class ZwaveColorLight(ZwaveDimmer): """Representation of a Z-Wave color changing light.""" def __init__(self, values, refresh, delay): """Initialize the light.""" self._color_channels = None self._hs = None self._ct = None self._white = None super().__init__(values, refresh, delay) def value_added(self): """Call when a new value is added to this entity.""" super().value_added() self._supported_features |= SUPPORT_COLOR if self._zw098: self._supported_features |= SUPPORT_COLOR_TEMP elif self._color_channels is not None and self._color_channels & ( COLOR_CHANNEL_WARM_WHITE | COLOR_CHANNEL_COLD_WHITE ): self._supported_features |= SUPPORT_WHITE_VALUE def update_properties(self): """Update internal properties based on zwave values.""" super().update_properties() if self.values.color is None: return if self.values.color_channels is None: return # Color Channels self._color_channels = self.values.color_channels.data # Color Data String data = self.values.color.data # RGB is always present in the openzwave color data string. rgb = [int(data[1:3], 16), int(data[3:5], 16), int(data[5:7], 16)] self._hs = color_util.color_RGB_to_hs(*rgb) # Parse remaining color channels. Openzwave appends white channels # that are present. index = 7 # Warm white if self._color_channels & COLOR_CHANNEL_WARM_WHITE: warm_white = int(data[index : index + 2], 16) index += 2 else: warm_white = 0 # Cold white if self._color_channels & COLOR_CHANNEL_COLD_WHITE: cold_white = int(data[index : index + 2], 16) index += 2 else: cold_white = 0 # Color temperature. With the AEOTEC ZW098 bulb, only two color # temperatures are supported. The warm and cold channel values # indicate brightness for warm/cold color temperature. if self._zw098: if warm_white > 0: self._ct = TEMP_WARM_HASS self._hs = ct_to_hs(self._ct) elif cold_white > 0: self._ct = TEMP_COLD_HASS self._hs = ct_to_hs(self._ct) else: # RGB color is being used. Just report midpoint. self._ct = TEMP_MID_HASS elif self._color_channels & COLOR_CHANNEL_WARM_WHITE: self._white = warm_white elif self._color_channels & COLOR_CHANNEL_COLD_WHITE: self._white = cold_white # If no rgb channels supported, report None. if not ( self._color_channels & COLOR_CHANNEL_RED or self._color_channels & COLOR_CHANNEL_GREEN or self._color_channels & COLOR_CHANNEL_BLUE ): self._hs = None @property def hs_color(self): """Return the hs color.""" return self._hs @property def white_value(self): """Return the white value of this light between 0..255.""" return self._white @property def color_temp(self): """Return the color temperature.""" return self._ct def turn_on(self, **kwargs): """Turn the device on.""" rgbw = None if ATTR_WHITE_VALUE in kwargs: self._white = kwargs[ATTR_WHITE_VALUE] if ATTR_COLOR_TEMP in kwargs: # Color temperature. With the AEOTEC ZW098 bulb, only two color # temperatures are supported. The warm and cold channel values # indicate brightness for warm/cold color temperature. if self._zw098: if kwargs[ATTR_COLOR_TEMP] > TEMP_MID_HASS: self._ct = TEMP_WARM_HASS rgbw = "#000000ff00" else: self._ct = TEMP_COLD_HASS rgbw = "#00000000ff" elif ATTR_HS_COLOR in kwargs: self._hs = kwargs[ATTR_HS_COLOR] if ATTR_WHITE_VALUE not in kwargs: # white LED must be off in order for color to work self._white = 0 if ( ATTR_WHITE_VALUE in kwargs or ATTR_HS_COLOR in kwargs ) and self._hs is not None: rgbw = "#" for colorval in color_util.color_hs_to_RGB(*self._hs): rgbw += format(colorval, "02x") if self._white is not None: rgbw += format(self._white, "02x") + "00" else: rgbw += "0000" if rgbw and self.values.color: self.values.color.data = rgbw super().turn_on(**kwargs)
import sys import pytz import time import calendar import ConfigParser import cmd from datetime import date, datetime, timedelta from strategy import strategy from exchange import cb_exchange_sim, cb_exchange class runner(cmd.Cmd): def __init__(self): """Create a new runner with provided CLI commands. Default commands are: \n1. exit: quit autotrader \n2. help: display all commands \n3. price: display the most recent bitcoin price \n4. run: start trading on live data \n5. backtest: run a backtest on historic data \n6. load: load a new strategy """ print(" __ _ __ _ __ ") print(" / /_ (_) /__________ _(_)___/ /__ _____") print(" / __ \/ / __/ ___/ __ `/ / __ / _ \/ ___/") print(" / /_/ / / /_/ / / /_/ / / /_/ / __/ / ") print("/_.___/_/\__/_/ \__,_/_/\__,_/\___/_/ ") print("") print("Welcome to bitraider v0.0.4, an algorithmic Bitcoin trader!") cmd.Cmd.__init__(self) self.prompt = '> ' self.intro = "Type a command to get started or type \'help\'" # Init config self.config_path = "settings.ini" self.config = ConfigParser.ConfigParser() try: self.config.read(self.config_path) except Exception, err: print(str(err)) # Set up strategy self.strategies = {} """The currently loaded strategies""" # Try to load a default strategy, if one exists try: default_strategy_module = self.config.get("default_strategy", "module") default_strategy_class = self.config.get("default_strategy", "class") self.load_strategy(default_strategy_module, default_strategy_class) except Exception, err: #print(str(err)) print("No default strategy configured. Run " "\'config default\' to set one") try: self.config.add_section("default_strategy") except: pass self.exchange = cb_exchange_sim(1000, 1) self.accounts = None # Get auth credentials from settings.ini, if they exist, authorize try: self.auth_key = self.config.get("auth", "key") self.auth_secret = self.config.get("auth", "secret") self.auth_password = self.config.get("auth", "password") self.authenticate() except Exception, err: #print(str(err)) print("No authentication configured. Run " "\'config auth\' to set it") try: self.config.add_section("auth") except: pass if self.accounts is not None: print(str(len(self.accounts))+" accounts were found.") for i in range(0, len(self.accounts)): try: print("Account ID: "+str(self.accounts[i]['id'])+" Available Funds: "+str(self.accounts[i]['available'])+" "+str(self.accounts[i]['currency'])+"") except Exception, err: print("Something went wrong while trying to authenticate with the provided credentials. Try running config>auth again.") def do_exit(self, line): sys.exit() def do_price(self, line): self.print_curr_price() def do_run(self, line): self.set_ticker_on() def do_list(self, line): self.list_strategies() def do_config(self, option): """usage: \'config \' [option]""" if option is None: print("error: no cofiguration option specified") else: if option == "auth": if self.accounts is not None: print("Are you sure? Reconfiguring auth will wipe your current auth settings. [y/n]") input = raw_input("> ") if input == "y": print("Paste in your CoinbaseExchange API key:") input = raw_input("> ") self.auth_key = input print("Paste in your CoinbaseExchange API secret:") input = raw_input("> ") self.auth_secret = input print("Paste in your CoinbaseExchange API passphrase:") input = raw_input("> ") if input is not "": self.auth_password = input self.config.set("auth", "key", self.auth_key) self.config.set("auth", "secret", self.auth_secret) self.config.set("auth", "password", self.auth_password) with open(self.config_path, "wb") as config_file: self.config.write(config_file) self.authenticate() elif input == "n": print("Exiting to main menu") pass else: print("Paste in your CoinbaseExchange API key:") input = raw_input("> ") self.auth_key = input print("Paste in your CoinbaseExchange API secret:") input = raw_input("> ") self.auth_secret = input print("Paste in your CoinbaseExchange API passphrase:") input = raw_input("> ") self.auth_password = input self.config.set("auth", "key", self.auth_key) self.config.set("auth", "secret", self.auth_secret) self.config.set("auth", "password", self.auth_password) with open(self.config_path, "wb") as config_file: self.config.write(config_file) self.authenticate() elif option == "default": print("Type the filename (without .py) containing the class which inherits from bitraider.strategy:") option = raw_input("> ") filename = str(option) self.config.set("default_strategy", "module", filename) print("Type the name of the class within "+str(option)+" representing the strategy to load:") option = raw_input("> ") loaded_strategy = str(option) if self.strategies is not None: if loaded_strategy in self.strategies.keys(): print("Error: "+loaded_strategy+" is already loaded") option = raw_input("> ") loaded_strategy = str(option) self.config.set("default_strategy", "class", loaded_strategy) with open(self.config_path, "wb") as config_file: self.config.write(config_file) self.load_strategy(filename, loaded_strategy) def do_load(self, option): print("Type the filename (without .py) containing the class which inherits from bitraider.strategy:") input = raw_input("> ") filename = str(input) print("Type the name of the class within "+str(input)+" representing the strategy to load:") input = raw_input("> ") loaded_strategy = str(input) self.load_strategy(filename, loaded_strategy) def do_backtest(self, option): strategy_to_backtest = "" print("Enter the class name of the strategy to backtest, or press enter to\n" "backtest on the default strategy.") input = raw_input("> ") if input == "": print("Performing backest on default strategy: "+str(self.config.get("default_strategy" ,"class"))) strategy_to_backtest = str(self.config.get("default_strategy", "class")) else: strategy_to_backtest = str(input) usd = 1000 btc = 1 days_back_in_time = 7 print("Enter the number of days back in time to backtest on: ") input = raw_input("> ") if input == "": print("Performing backtest on default of 7 days.") else: days_back_in_time = float(input) print("Performing backtest on last "+str(days_back_in_time)+" days.") curr_time = datetime.now(tz=self.curr_timezone) start_time = curr_time - timedelta(seconds=86400*days_back_in_time) start_time = start_time.isoformat(' ') end_time = curr_time.isoformat(' ') print("Enter the initial USD amount:") input = raw_input("> ") if input == "": print("Using default starting USD amount of $1,000") else: usd = float(input) print("Using starting USD amount of $"+str(usd)) print("Enter the initial BTC amount:") input = raw_input("> ") if input == "": print("Using default starting BTC amount of 1") else: btc = float(input) print("Using starting BTC amount of "+str(btc)) if strategy_to_backtest is not "": self.strategies[strategy_to_backtest].exchange = cb_exchange_sim(start_usd=usd, start_btc=btc) historic_data = self.strategies[strategy_to_backtest].exchange.get_historic_rates(start_time=start_time, end_time=end_time, granularity=self.strategies[strategy_to_backtest].interval) if type(historic_data) is not list: print("API error: "+str(historic_data.get("message", ""))) print("Unable to backtest") pass else: print("Backtesting from "+str(start_time)+" to "+str(end_time)) print("with "+str(len(historic_data))+" timeslices of length "+str(self.strategies[strategy_to_backtest].interval)+" seconds each") self.strategies[strategy_to_backtest].backtest_strategy(historic_data) def do_optimize(self, line): usd = 1000 btc = 1 days_back_in_time = 7 print("Enter the class name of the strategy to be optimized:") input = raw_input("> ") print(self.strategies.keys()) if input not in self.strategies.keys(): print("Error: not found") pass strategy_to_optimize = input print("Enter the timeframe to optimize for i.e. the time to simulate over:") days_back_in_time = 7 input = raw_input("> ") if input == "": print("Performing optimization for default of last 7 days.") else: days_back_in_time = float(input) print("Performing optimization based on last "+str(days_back_in_time)+" days.") curr_time = datetime.now(tz=self.curr_timezone) start_time = curr_time - timedelta(seconds=86400*days_back_in_time) start_time = start_time.isoformat(' ') end_time = curr_time.isoformat(' ') print("Enter the initial USD amount:") input = raw_input("> ") if input == "": print("Using default starting USD amount of $1,000") else: usd = float(input) print("Using starting USD amount of $"+str(usd)) print("Enter the initial BTC amount:") input = raw_input("> ") if input == "": print("Using default starting BTC amount of 1") else: btc = float(input) print("Using starting BTC amount of "+str(btc)) strategy = strategy_to_optimize strategy_attributes = dir(self.strategies[strategy]) bounds_by_attribute = {} print("Note: strategy interval cannot be optimized due to API restraints") self.strategies[strategy].exchange = cb_exchange_sim(start_usd=usd, start_btc=btc) historic_data = self.strategies[strategy].exchange.get_historic_rates(start_time=start_time, end_time=end_time, granularity=self.strategies[strategy].interval) if type(historic_data) is not list: print("API error: "+str(historic_data.get("message", ""))) print("Unable to optimize. Try changing strategy's interval") pass else: print("Optimizing based on time frame of "+str(start_time)+" to "+str(end_time)) print("with "+str(len(historic_data))+" timeslices of length "+str(self.strategies[strategy].interval)+" seconds each") for attribute in strategy_attributes: if "_" not in str(attribute) and str(attribute) != "interval": # Optimizing for interval would poll API too frequently print("Enter the lower bound for attribute: "+str(attribute)+", or press enter to skip:") input = raw_input("> ") if input == "": pass else: lower_bound = float(input) print("Enter the upper bound for attribute: "+str(attribute)+":") input = raw_input("> ") upper_bound = float(input) print("Enter the granularity of this attribute i.e. how many different values to try:") input = raw_input("> ") granularity = float(input) if upper_bound is not None and lower_bound is not None: bounds_by_attribute[str(attribute)] = {"lower":lower_bound, "upper":upper_bound, "granularity":granularity} #self.strategies[strategy][attribute] = float(lower_bound) attribute_vals_by_id = {} config_id = 0 # Initialize attribute_vals_by id for attribute in bounds_by_attribute.keys(): num_shades_of_attr = int(bounds_by_attribute[attribute].get("granularity")) increment = (float(upper_bound) - float(lower_bound))/num_shades_of_attr attr_val = float(lower_bound) for shade in range(num_shades_of_attr): attribute_vals_by_id[str(config_id)] = {} attribute_vals_by_id[str(config_id)][attribute] = attr_val config_id += 1 # Fill in all possible values for the attributes config_id = 0 for attribute in bounds_by_attribute.keys(): num_shades_of_attr = int(bounds_by_attribute[attribute].get("granularity")) increment = (float(upper_bound) - float(lower_bound))/num_shades_of_attr step = 0 attr_val = float(lower_bound) + (increment*step) for shade in range(num_shades_of_attr): attribute_vals_by_id[str(config_id)][attribute] = attr_val config_id += 1 step += 1 performance_by_id = {} performance_vs_mkt = 0 strategy_performance = 0 mkt_performance = 0 # Change the attribute values for this strategy, updating when the performance is highest for configuration in attribute_vals_by_id.keys(): for attribute in attribute_vals_by_id[configuration]: setattr(self.strategies[strategy], attribute, attribute_vals_by_id[configuration][attribute]) performance_vs_mkt, strategy_performance, mkt_performance = self.strategies[strategy].backtest_strategy(historic_data) performance_by_id[str(configuration)] = performance_vs_mkt best_config = "0" for configuration in performance_by_id.keys(): if performance_by_id[configuration] > performance_by_id[best_config]: best_config = configuration print("The best performing strategy configuration is: "+str(attribute_vals_by_id[best_config])) print("With a performance vs market of: "+str(performance_by_id[best_config])) # End python cmd funtions def authenticate(self): try: self.exchange = cb_exchange(self.auth_key, self.auth_secret, self.auth_password) self.accounts = self.exchange.list_accounts() except Exception, err: print("Error! Only unauthorized endpoints are available.") print("error: "+str(err)) print("If you would like bitraider to walk you through authentication, enter the commands: \'config\' > \'auth\'") def set_ticker_on(self): strategy = self.strategies[0] start_time = time.time() lower_bound = start_time upper_bound = start_time + strategy.interval elapsed_time = 0.0 last_intervals_trades = [] while True: curr_time = time.time() elapsed_time = curr_time - start_time if elapsed_time % strategy.interval == 0: # if we've reached a new interval, calculate data for the last interval and pass # it onto the strategy latest_trades = self.exchange.get_trades('BTC-USD') interval_data = [] last_intervals_low = 999999999 last_intervals_high = 0.0 last_intervals_close = 0.0 last_intervals_close = 0.0 last_intervals_volume = 0.0 for trade in latest_trades: # starting with the most recent trade, get trades for the last interval datestring = str(trade.get("time"))[:-3] trade_time = float(calendar.timegm(datetime.strptime(datestring, "%Y-%m-%d %H:%M:%S.%f").timetuple())) if trade_time >= lower_bound and trade_time <= upper_bound: last_intervals_trades.append(trade) if float(trade.get('price')) > last_intervals_high: last_intervals_high = float(trade.get('price')) if float(trade.get('price')) < last_intervals_low: last_intervals_low = float(trade.get('price')) last_intervals_volume += float(trade.get('size')) if len(last_intervals_trades) > 0: last_intervals_close = float(last_intervals_trades[0].get('price')) last_intervals_open = float(last_intervals_trades[-1].get('price')) interval_start_time = curr_time - strategy.interval interval_data.extend([interval_start_time, last_intervals_low, last_intervals_high, last_intervals_open, last_intervals_close, last_intervals_volume]) print("last_intervals_trades: "+str(last_intervals_trades)) print("elapsed: "+str(elapsed_time)) last_intervals_trades = [] lower_bound += strategy.interval upper_bound += strategy.interval # Here's where the magic happens: #strategy.trade(interval_data) def run(self): # Time Configuration self.curr_time = time.time() # Seconds since Jan 1st, 1970 self.curr_timezone = pytz.timezone("US/Central") self.cmdloop() def print_curr_price(self): """Print the most recent price.""" print(self.exchange.get_last_trade('BTC-USD')['price']) def load_strategy(self, module, cls): """Load a user-defined strategy from a file. \n`module`: the filename in the current directory containing the strategy class which inherits from bitraider.strategy (does not include .py) \n`cls`: the classname within the file to load """ import_string = module+"."+cls classname = str(cls) _temp = __import__(module) loaded_strategy_ = getattr(_temp, cls) instance_of_loaded_strategy = loaded_strategy_() self.strategies[classname] = instance_of_loaded_strategy print("Loaded strategy: "+str(cls)+" from file: "+str(module)+".py") def run(): my_runner = runner() my_runner.run() if __name__=="__main__": my_runner = runner() my_runner.run()
# Generated from 'AEDataModel.h' def FOUR_CHAR_CODE(x): return x typeBoolean = FOUR_CHAR_CODE('bool') typeChar = FOUR_CHAR_CODE('TEXT') typeSInt16 = FOUR_CHAR_CODE('shor') typeSInt32 = FOUR_CHAR_CODE('long') typeUInt32 = FOUR_CHAR_CODE('magn') typeSInt64 = FOUR_CHAR_CODE('comp') typeIEEE32BitFloatingPoint = FOUR_CHAR_CODE('sing') typeIEEE64BitFloatingPoint = FOUR_CHAR_CODE('doub') type128BitFloatingPoint = FOUR_CHAR_CODE('ldbl') typeDecimalStruct = FOUR_CHAR_CODE('decm') typeSMInt = typeSInt16 typeShortInteger = typeSInt16 typeInteger = typeSInt32 typeLongInteger = typeSInt32 typeMagnitude = typeUInt32 typeComp = typeSInt64 typeSMFloat = typeIEEE32BitFloatingPoint typeShortFloat = typeIEEE32BitFloatingPoint typeFloat = typeIEEE64BitFloatingPoint typeLongFloat = typeIEEE64BitFloatingPoint typeExtended = FOUR_CHAR_CODE('exte') typeAEList = FOUR_CHAR_CODE('list') typeAERecord = FOUR_CHAR_CODE('reco') typeAppleEvent = FOUR_CHAR_CODE('aevt') typeEventRecord = FOUR_CHAR_CODE('evrc') typeTrue = FOUR_CHAR_CODE('true') typeFalse = FOUR_CHAR_CODE('fals') typeAlias = FOUR_CHAR_CODE('alis') typeEnumerated = FOUR_CHAR_CODE('enum') typeType = FOUR_CHAR_CODE('type') typeAppParameters = FOUR_CHAR_CODE('appa') typeProperty = FOUR_CHAR_CODE('prop') typeFSS = FOUR_CHAR_CODE('fss ') typeFSRef = FOUR_CHAR_CODE('fsrf') typeKeyword = FOUR_CHAR_CODE('keyw') typeSectionH = FOUR_CHAR_CODE('sect') typeWildCard = FOUR_CHAR_CODE('****') typeApplSignature = FOUR_CHAR_CODE('sign') typeQDRectangle = FOUR_CHAR_CODE('qdrt') typeFixed = FOUR_CHAR_CODE('fixd') typeProcessSerialNumber = FOUR_CHAR_CODE('psn ') typeApplicationURL = FOUR_CHAR_CODE('aprl') typeNull = FOUR_CHAR_CODE('null') typeSessionID = FOUR_CHAR_CODE('ssid') typeTargetID = FOUR_CHAR_CODE('targ') typeDispatcherID = FOUR_CHAR_CODE('dspt') keyTransactionIDAttr = FOUR_CHAR_CODE('tran') keyReturnIDAttr = FOUR_CHAR_CODE('rtid') keyEventClassAttr = FOUR_CHAR_CODE('evcl') keyEventIDAttr = FOUR_CHAR_CODE('evid') keyAddressAttr = FOUR_CHAR_CODE('addr') keyOptionalKeywordAttr = FOUR_CHAR_CODE('optk') keyTimeoutAttr = FOUR_CHAR_CODE('timo') keyInteractLevelAttr = FOUR_CHAR_CODE('inte') keyEventSourceAttr = FOUR_CHAR_CODE('esrc') keyMissedKeywordAttr = FOUR_CHAR_CODE('miss') keyOriginalAddressAttr = FOUR_CHAR_CODE('from') keyAcceptTimeoutAttr = FOUR_CHAR_CODE('actm') kAEDescListFactorNone = 0 kAEDescListFactorType = 4 kAEDescListFactorTypeAndSize = 8 kAutoGenerateReturnID = -1 kAnyTransactionID = 0 kAEDataArray = 0 kAEPackedArray = 1 kAEDescArray = 3 kAEKeyDescArray = 4 kAEHandleArray = 2 kAENormalPriority = 0x00000000 kAEHighPriority = 0x00000001 kAENoReply = 0x00000001 kAEQueueReply = 0x00000002 kAEWaitReply = 0x00000003 kAEDontReconnect = 0x00000080 kAEWantReceipt = 0x00000200 kAENeverInteract = 0x00000010 kAECanInteract = 0x00000020 kAEAlwaysInteract = 0x00000030 kAECanSwitchLayer = 0x00000040 kAEDontRecord = 0x00001000 kAEDontExecute = 0x00002000 kAEProcessNonReplyEvents = 0x00008000 kAEDefaultTimeout = -1 kNoTimeOut = -2 kAEInteractWithSelf = 0 kAEInteractWithLocal = 1 kAEInteractWithAll = 2 kAEDoNotIgnoreHandler = 0x00000000 kAEIgnoreAppPhacHandler = 0x00000001 kAEIgnoreAppEventHandler = 0x00000002 kAEIgnoreSysPhacHandler = 0x00000004 kAEIgnoreSysEventHandler = 0x00000008 kAEIngoreBuiltInEventHandler = 0x00000010 # kAEDontDisposeOnResume = (long)0x80000000 kAENoDispatch = 0 # kAEUseStandardDispatch = (long)0xFFFFFFFF keyDirectObject = FOUR_CHAR_CODE('----') keyErrorNumber = FOUR_CHAR_CODE('errn') keyErrorString = FOUR_CHAR_CODE('errs') keyProcessSerialNumber = FOUR_CHAR_CODE('psn ') keyPreDispatch = FOUR_CHAR_CODE('phac') keySelectProc = FOUR_CHAR_CODE('selh') keyAERecorderCount = FOUR_CHAR_CODE('recr') keyAEVersion = FOUR_CHAR_CODE('vers') kCoreEventClass = FOUR_CHAR_CODE('aevt') kAEOpenApplication = FOUR_CHAR_CODE('oapp') kAEOpenDocuments = FOUR_CHAR_CODE('odoc') kAEPrintDocuments = FOUR_CHAR_CODE('pdoc') kAEQuitApplication = FOUR_CHAR_CODE('quit') kAEAnswer = FOUR_CHAR_CODE('ansr') kAEApplicationDied = FOUR_CHAR_CODE('obit') kAEShowPreferences = FOUR_CHAR_CODE('pref') kAEStartRecording = FOUR_CHAR_CODE('reca') kAEStopRecording = FOUR_CHAR_CODE('recc') kAENotifyStartRecording = FOUR_CHAR_CODE('rec1') kAENotifyStopRecording = FOUR_CHAR_CODE('rec0') kAENotifyRecording = FOUR_CHAR_CODE('recr') kAEUnknownSource = 0 kAEDirectCall = 1 kAESameProcess = 2 kAELocalProcess = 3 kAERemoteProcess = 4 cAEList = FOUR_CHAR_CODE('list') cApplication = FOUR_CHAR_CODE('capp') cArc = FOUR_CHAR_CODE('carc') cBoolean = FOUR_CHAR_CODE('bool') cCell = FOUR_CHAR_CODE('ccel') cChar = FOUR_CHAR_CODE('cha ') cColorTable = FOUR_CHAR_CODE('clrt') cColumn = FOUR_CHAR_CODE('ccol') cDocument = FOUR_CHAR_CODE('docu') cDrawingArea = FOUR_CHAR_CODE('cdrw') cEnumeration = FOUR_CHAR_CODE('enum') cFile = FOUR_CHAR_CODE('file') cFixed = FOUR_CHAR_CODE('fixd') cFixedPoint = FOUR_CHAR_CODE('fpnt') cFixedRectangle = FOUR_CHAR_CODE('frct') cGraphicLine = FOUR_CHAR_CODE('glin') cGraphicObject = FOUR_CHAR_CODE('cgob') cGraphicShape = FOUR_CHAR_CODE('cgsh') cGraphicText = FOUR_CHAR_CODE('cgtx') cGroupedGraphic = FOUR_CHAR_CODE('cpic') cInsertionLoc = FOUR_CHAR_CODE('insl') cInsertionPoint = FOUR_CHAR_CODE('cins') cIntlText = FOUR_CHAR_CODE('itxt') cIntlWritingCode = FOUR_CHAR_CODE('intl') cItem = FOUR_CHAR_CODE('citm') cLine = FOUR_CHAR_CODE('clin') cLongDateTime = FOUR_CHAR_CODE('ldt ') cLongFixed = FOUR_CHAR_CODE('lfxd') cLongFixedPoint = FOUR_CHAR_CODE('lfpt') cLongFixedRectangle = FOUR_CHAR_CODE('lfrc') cLongInteger = FOUR_CHAR_CODE('long') cLongPoint = FOUR_CHAR_CODE('lpnt') cLongRectangle = FOUR_CHAR_CODE('lrct') cMachineLoc = FOUR_CHAR_CODE('mLoc') cMenu = FOUR_CHAR_CODE('cmnu') cMenuItem = FOUR_CHAR_CODE('cmen') cObject = FOUR_CHAR_CODE('cobj') cObjectSpecifier = FOUR_CHAR_CODE('obj ') cOpenableObject = FOUR_CHAR_CODE('coob') cOval = FOUR_CHAR_CODE('covl') cParagraph = FOUR_CHAR_CODE('cpar') cPICT = FOUR_CHAR_CODE('PICT') cPixel = FOUR_CHAR_CODE('cpxl') cPixelMap = FOUR_CHAR_CODE('cpix') cPolygon = FOUR_CHAR_CODE('cpgn') cProperty = FOUR_CHAR_CODE('prop') cQDPoint = FOUR_CHAR_CODE('QDpt') cQDRectangle = FOUR_CHAR_CODE('qdrt') cRectangle = FOUR_CHAR_CODE('crec') cRGBColor = FOUR_CHAR_CODE('cRGB') cRotation = FOUR_CHAR_CODE('trot') cRoundedRectangle = FOUR_CHAR_CODE('crrc') cRow = FOUR_CHAR_CODE('crow') cSelection = FOUR_CHAR_CODE('csel') cShortInteger = FOUR_CHAR_CODE('shor') cTable = FOUR_CHAR_CODE('ctbl') cText = FOUR_CHAR_CODE('ctxt') cTextFlow = FOUR_CHAR_CODE('cflo') cTextStyles = FOUR_CHAR_CODE('tsty') cType = FOUR_CHAR_CODE('type') cVersion = FOUR_CHAR_CODE('vers') cWindow = FOUR_CHAR_CODE('cwin') cWord = FOUR_CHAR_CODE('cwor') enumArrows = FOUR_CHAR_CODE('arro') enumJustification = FOUR_CHAR_CODE('just') enumKeyForm = FOUR_CHAR_CODE('kfrm') enumPosition = FOUR_CHAR_CODE('posi') enumProtection = FOUR_CHAR_CODE('prtn') enumQuality = FOUR_CHAR_CODE('qual') enumSaveOptions = FOUR_CHAR_CODE('savo') enumStyle = FOUR_CHAR_CODE('styl') enumTransferMode = FOUR_CHAR_CODE('tran') formUniqueID = FOUR_CHAR_CODE('ID ') kAEAbout = FOUR_CHAR_CODE('abou') kAEAfter = FOUR_CHAR_CODE('afte') kAEAliasSelection = FOUR_CHAR_CODE('sali') kAEAllCaps = FOUR_CHAR_CODE('alcp') kAEArrowAtEnd = FOUR_CHAR_CODE('aren') kAEArrowAtStart = FOUR_CHAR_CODE('arst') kAEArrowBothEnds = FOUR_CHAR_CODE('arbo') kAEAsk = FOUR_CHAR_CODE('ask ') kAEBefore = FOUR_CHAR_CODE('befo') kAEBeginning = FOUR_CHAR_CODE('bgng') kAEBeginsWith = FOUR_CHAR_CODE('bgwt') kAEBeginTransaction = FOUR_CHAR_CODE('begi') kAEBold = FOUR_CHAR_CODE('bold') kAECaseSensEquals = FOUR_CHAR_CODE('cseq') kAECentered = FOUR_CHAR_CODE('cent') kAEChangeView = FOUR_CHAR_CODE('view') kAEClone = FOUR_CHAR_CODE('clon') kAEClose = FOUR_CHAR_CODE('clos') kAECondensed = FOUR_CHAR_CODE('cond') kAEContains = FOUR_CHAR_CODE('cont') kAECopy = FOUR_CHAR_CODE('copy') kAECoreSuite = FOUR_CHAR_CODE('core') kAECountElements = FOUR_CHAR_CODE('cnte') kAECreateElement = FOUR_CHAR_CODE('crel') kAECreatePublisher = FOUR_CHAR_CODE('cpub') kAECut = FOUR_CHAR_CODE('cut ') kAEDelete = FOUR_CHAR_CODE('delo') kAEDoObjectsExist = FOUR_CHAR_CODE('doex') kAEDoScript = FOUR_CHAR_CODE('dosc') kAEDrag = FOUR_CHAR_CODE('drag') kAEDuplicateSelection = FOUR_CHAR_CODE('sdup') kAEEditGraphic = FOUR_CHAR_CODE('edit') kAEEmptyTrash = FOUR_CHAR_CODE('empt') kAEEnd = FOUR_CHAR_CODE('end ') kAEEndsWith = FOUR_CHAR_CODE('ends') kAEEndTransaction = FOUR_CHAR_CODE('endt') kAEEquals = FOUR_CHAR_CODE('= ') kAEExpanded = FOUR_CHAR_CODE('pexp') kAEFast = FOUR_CHAR_CODE('fast') kAEFinderEvents = FOUR_CHAR_CODE('FNDR') kAEFormulaProtect = FOUR_CHAR_CODE('fpro') kAEFullyJustified = FOUR_CHAR_CODE('full') kAEGetClassInfo = FOUR_CHAR_CODE('qobj') kAEGetData = FOUR_CHAR_CODE('getd') kAEGetDataSize = FOUR_CHAR_CODE('dsiz') kAEGetEventInfo = FOUR_CHAR_CODE('gtei') kAEGetInfoSelection = FOUR_CHAR_CODE('sinf') kAEGetPrivilegeSelection = FOUR_CHAR_CODE('sprv') kAEGetSuiteInfo = FOUR_CHAR_CODE('gtsi') kAEGreaterThan = FOUR_CHAR_CODE('> ') kAEGreaterThanEquals = FOUR_CHAR_CODE('>= ') kAEGrow = FOUR_CHAR_CODE('grow') kAEHidden = FOUR_CHAR_CODE('hidn') kAEHiQuality = FOUR_CHAR_CODE('hiqu') kAEImageGraphic = FOUR_CHAR_CODE('imgr') kAEIsUniform = FOUR_CHAR_CODE('isun') kAEItalic = FOUR_CHAR_CODE('ital') kAELeftJustified = FOUR_CHAR_CODE('left') kAELessThan = FOUR_CHAR_CODE('< ') kAELessThanEquals = FOUR_CHAR_CODE('<= ') kAELowercase = FOUR_CHAR_CODE('lowc') kAEMakeObjectsVisible = FOUR_CHAR_CODE('mvis') kAEMiscStandards = FOUR_CHAR_CODE('misc') kAEModifiable = FOUR_CHAR_CODE('modf') kAEMove = FOUR_CHAR_CODE('move') kAENo = FOUR_CHAR_CODE('no ') kAENoArrow = FOUR_CHAR_CODE('arno') kAENonmodifiable = FOUR_CHAR_CODE('nmod') kAEOpen = FOUR_CHAR_CODE('odoc') kAEOpenSelection = FOUR_CHAR_CODE('sope') kAEOutline = FOUR_CHAR_CODE('outl') kAEPageSetup = FOUR_CHAR_CODE('pgsu') kAEPaste = FOUR_CHAR_CODE('past') kAEPlain = FOUR_CHAR_CODE('plan') kAEPrint = FOUR_CHAR_CODE('pdoc') kAEPrintSelection = FOUR_CHAR_CODE('spri') kAEPrintWindow = FOUR_CHAR_CODE('pwin') kAEPutAwaySelection = FOUR_CHAR_CODE('sput') kAEQDAddOver = FOUR_CHAR_CODE('addo') kAEQDAddPin = FOUR_CHAR_CODE('addp') kAEQDAdMax = FOUR_CHAR_CODE('admx') kAEQDAdMin = FOUR_CHAR_CODE('admn') kAEQDBic = FOUR_CHAR_CODE('bic ') kAEQDBlend = FOUR_CHAR_CODE('blnd') kAEQDCopy = FOUR_CHAR_CODE('cpy ') kAEQDNotBic = FOUR_CHAR_CODE('nbic') kAEQDNotCopy = FOUR_CHAR_CODE('ncpy') kAEQDNotOr = FOUR_CHAR_CODE('ntor') kAEQDNotXor = FOUR_CHAR_CODE('nxor') kAEQDOr = FOUR_CHAR_CODE('or ') kAEQDSubOver = FOUR_CHAR_CODE('subo') kAEQDSubPin = FOUR_CHAR_CODE('subp') kAEQDSupplementalSuite = FOUR_CHAR_CODE('qdsp') kAEQDXor = FOUR_CHAR_CODE('xor ') kAEQuickdrawSuite = FOUR_CHAR_CODE('qdrw') kAEQuitAll = FOUR_CHAR_CODE('quia') kAERedo = FOUR_CHAR_CODE('redo') kAERegular = FOUR_CHAR_CODE('regl') kAEReopenApplication = FOUR_CHAR_CODE('rapp') kAEReplace = FOUR_CHAR_CODE('rplc') kAERequiredSuite = FOUR_CHAR_CODE('reqd') kAERestart = FOUR_CHAR_CODE('rest') kAERevealSelection = FOUR_CHAR_CODE('srev') kAERevert = FOUR_CHAR_CODE('rvrt') kAERightJustified = FOUR_CHAR_CODE('rght') kAESave = FOUR_CHAR_CODE('save') kAESelect = FOUR_CHAR_CODE('slct') kAESetData = FOUR_CHAR_CODE('setd') kAESetPosition = FOUR_CHAR_CODE('posn') kAEShadow = FOUR_CHAR_CODE('shad') kAEShowClipboard = FOUR_CHAR_CODE('shcl') kAEShutDown = FOUR_CHAR_CODE('shut') kAESleep = FOUR_CHAR_CODE('slep') kAESmallCaps = FOUR_CHAR_CODE('smcp') kAESpecialClassProperties = FOUR_CHAR_CODE('c@#!') kAEStrikethrough = FOUR_CHAR_CODE('strk') kAESubscript = FOUR_CHAR_CODE('sbsc') kAESuperscript = FOUR_CHAR_CODE('spsc') kAETableSuite = FOUR_CHAR_CODE('tbls') kAETextSuite = FOUR_CHAR_CODE('TEXT') kAETransactionTerminated = FOUR_CHAR_CODE('ttrm') kAEUnderline = FOUR_CHAR_CODE('undl') kAEUndo = FOUR_CHAR_CODE('undo') kAEWholeWordEquals = FOUR_CHAR_CODE('wweq') kAEYes = FOUR_CHAR_CODE('yes ') kAEZoom = FOUR_CHAR_CODE('zoom') kAEMouseClass = FOUR_CHAR_CODE('mous') kAEDown = FOUR_CHAR_CODE('down') kAEUp = FOUR_CHAR_CODE('up ') kAEMoved = FOUR_CHAR_CODE('move') kAEStoppedMoving = FOUR_CHAR_CODE('stop') kAEWindowClass = FOUR_CHAR_CODE('wind') kAEUpdate = FOUR_CHAR_CODE('updt') kAEActivate = FOUR_CHAR_CODE('actv') kAEDeactivate = FOUR_CHAR_CODE('dact') kAECommandClass = FOUR_CHAR_CODE('cmnd') kAEKeyClass = FOUR_CHAR_CODE('keyc') kAERawKey = FOUR_CHAR_CODE('rkey') kAEVirtualKey = FOUR_CHAR_CODE('keyc') kAENavigationKey = FOUR_CHAR_CODE('nave') kAEAutoDown = FOUR_CHAR_CODE('auto') kAEApplicationClass = FOUR_CHAR_CODE('appl') kAESuspend = FOUR_CHAR_CODE('susp') kAEResume = FOUR_CHAR_CODE('rsme') kAEDiskEvent = FOUR_CHAR_CODE('disk') kAENullEvent = FOUR_CHAR_CODE('null') kAEWakeUpEvent = FOUR_CHAR_CODE('wake') kAEScrapEvent = FOUR_CHAR_CODE('scrp') kAEHighLevel = FOUR_CHAR_CODE('high') keyAEAngle = FOUR_CHAR_CODE('kang') keyAEArcAngle = FOUR_CHAR_CODE('parc') keyAEBaseAddr = FOUR_CHAR_CODE('badd') keyAEBestType = FOUR_CHAR_CODE('pbst') keyAEBgndColor = FOUR_CHAR_CODE('kbcl') keyAEBgndPattern = FOUR_CHAR_CODE('kbpt') keyAEBounds = FOUR_CHAR_CODE('pbnd') keyAECellList = FOUR_CHAR_CODE('kclt') keyAEClassID = FOUR_CHAR_CODE('clID') keyAEColor = FOUR_CHAR_CODE('colr') keyAEColorTable = FOUR_CHAR_CODE('cltb') keyAECurveHeight = FOUR_CHAR_CODE('kchd') keyAECurveWidth = FOUR_CHAR_CODE('kcwd') keyAEDashStyle = FOUR_CHAR_CODE('pdst') keyAEData = FOUR_CHAR_CODE('data') keyAEDefaultType = FOUR_CHAR_CODE('deft') keyAEDefinitionRect = FOUR_CHAR_CODE('pdrt') keyAEDescType = FOUR_CHAR_CODE('dstp') keyAEDestination = FOUR_CHAR_CODE('dest') keyAEDoAntiAlias = FOUR_CHAR_CODE('anta') keyAEDoDithered = FOUR_CHAR_CODE('gdit') keyAEDoRotate = FOUR_CHAR_CODE('kdrt') keyAEDoScale = FOUR_CHAR_CODE('ksca') keyAEDoTranslate = FOUR_CHAR_CODE('ktra') keyAEEditionFileLoc = FOUR_CHAR_CODE('eloc') keyAEElements = FOUR_CHAR_CODE('elms') keyAEEndPoint = FOUR_CHAR_CODE('pend') keyAEEventClass = FOUR_CHAR_CODE('evcl') keyAEEventID = FOUR_CHAR_CODE('evti') keyAEFile = FOUR_CHAR_CODE('kfil') keyAEFileType = FOUR_CHAR_CODE('fltp') keyAEFillColor = FOUR_CHAR_CODE('flcl') keyAEFillPattern = FOUR_CHAR_CODE('flpt') keyAEFlipHorizontal = FOUR_CHAR_CODE('kfho') keyAEFlipVertical = FOUR_CHAR_CODE('kfvt') keyAEFont = FOUR_CHAR_CODE('font') keyAEFormula = FOUR_CHAR_CODE('pfor') keyAEGraphicObjects = FOUR_CHAR_CODE('gobs') keyAEID = FOUR_CHAR_CODE('ID ') keyAEImageQuality = FOUR_CHAR_CODE('gqua') keyAEInsertHere = FOUR_CHAR_CODE('insh') keyAEKeyForms = FOUR_CHAR_CODE('keyf') keyAEKeyword = FOUR_CHAR_CODE('kywd') keyAELevel = FOUR_CHAR_CODE('levl') keyAELineArrow = FOUR_CHAR_CODE('arro') keyAEName = FOUR_CHAR_CODE('pnam') keyAENewElementLoc = FOUR_CHAR_CODE('pnel') keyAEObject = FOUR_CHAR_CODE('kobj') keyAEObjectClass = FOUR_CHAR_CODE('kocl') keyAEOffStyles = FOUR_CHAR_CODE('ofst') keyAEOnStyles = FOUR_CHAR_CODE('onst') keyAEParameters = FOUR_CHAR_CODE('prms') keyAEParamFlags = FOUR_CHAR_CODE('pmfg') keyAEPenColor = FOUR_CHAR_CODE('ppcl') keyAEPenPattern = FOUR_CHAR_CODE('pppa') keyAEPenWidth = FOUR_CHAR_CODE('ppwd') keyAEPixelDepth = FOUR_CHAR_CODE('pdpt') keyAEPixMapMinus = FOUR_CHAR_CODE('kpmm') keyAEPMTable = FOUR_CHAR_CODE('kpmt') keyAEPointList = FOUR_CHAR_CODE('ptlt') keyAEPointSize = FOUR_CHAR_CODE('ptsz') keyAEPosition = FOUR_CHAR_CODE('kpos') keyAEPropData = FOUR_CHAR_CODE('prdt') keyAEProperties = FOUR_CHAR_CODE('qpro') keyAEProperty = FOUR_CHAR_CODE('kprp') keyAEPropFlags = FOUR_CHAR_CODE('prfg') keyAEPropID = FOUR_CHAR_CODE('prop') keyAEProtection = FOUR_CHAR_CODE('ppro') keyAERenderAs = FOUR_CHAR_CODE('kren') keyAERequestedType = FOUR_CHAR_CODE('rtyp') keyAEResult = FOUR_CHAR_CODE('----') keyAEResultInfo = FOUR_CHAR_CODE('rsin') keyAERotation = FOUR_CHAR_CODE('prot') keyAERotPoint = FOUR_CHAR_CODE('krtp') keyAERowList = FOUR_CHAR_CODE('krls') keyAESaveOptions = FOUR_CHAR_CODE('savo') keyAEScale = FOUR_CHAR_CODE('pscl') keyAEScriptTag = FOUR_CHAR_CODE('psct') keyAEShowWhere = FOUR_CHAR_CODE('show') keyAEStartAngle = FOUR_CHAR_CODE('pang') keyAEStartPoint = FOUR_CHAR_CODE('pstp') keyAEStyles = FOUR_CHAR_CODE('ksty') keyAESuiteID = FOUR_CHAR_CODE('suit') keyAEText = FOUR_CHAR_CODE('ktxt') keyAETextColor = FOUR_CHAR_CODE('ptxc') keyAETextFont = FOUR_CHAR_CODE('ptxf') keyAETextPointSize = FOUR_CHAR_CODE('ptps') keyAETextStyles = FOUR_CHAR_CODE('txst') keyAETextLineHeight = FOUR_CHAR_CODE('ktlh') keyAETextLineAscent = FOUR_CHAR_CODE('ktas') keyAETheText = FOUR_CHAR_CODE('thtx') keyAETransferMode = FOUR_CHAR_CODE('pptm') keyAETranslation = FOUR_CHAR_CODE('ptrs') keyAETryAsStructGraf = FOUR_CHAR_CODE('toog') keyAEUniformStyles = FOUR_CHAR_CODE('ustl') keyAEUpdateOn = FOUR_CHAR_CODE('pupd') keyAEUserTerm = FOUR_CHAR_CODE('utrm') keyAEWindow = FOUR_CHAR_CODE('wndw') keyAEWritingCode = FOUR_CHAR_CODE('wrcd') keyMiscellaneous = FOUR_CHAR_CODE('fmsc') keySelection = FOUR_CHAR_CODE('fsel') keyWindow = FOUR_CHAR_CODE('kwnd') keyWhen = FOUR_CHAR_CODE('when') keyWhere = FOUR_CHAR_CODE('wher') keyModifiers = FOUR_CHAR_CODE('mods') keyKey = FOUR_CHAR_CODE('key ') keyKeyCode = FOUR_CHAR_CODE('code') keyKeyboard = FOUR_CHAR_CODE('keyb') keyDriveNumber = FOUR_CHAR_CODE('drv#') keyErrorCode = FOUR_CHAR_CODE('err#') keyHighLevelClass = FOUR_CHAR_CODE('hcls') keyHighLevelID = FOUR_CHAR_CODE('hid ') pArcAngle = FOUR_CHAR_CODE('parc') pBackgroundColor = FOUR_CHAR_CODE('pbcl') pBackgroundPattern = FOUR_CHAR_CODE('pbpt') pBestType = FOUR_CHAR_CODE('pbst') pBounds = FOUR_CHAR_CODE('pbnd') pClass = FOUR_CHAR_CODE('pcls') pClipboard = FOUR_CHAR_CODE('pcli') pColor = FOUR_CHAR_CODE('colr') pColorTable = FOUR_CHAR_CODE('cltb') pContents = FOUR_CHAR_CODE('pcnt') pCornerCurveHeight = FOUR_CHAR_CODE('pchd') pCornerCurveWidth = FOUR_CHAR_CODE('pcwd') pDashStyle = FOUR_CHAR_CODE('pdst') pDefaultType = FOUR_CHAR_CODE('deft') pDefinitionRect = FOUR_CHAR_CODE('pdrt') pEnabled = FOUR_CHAR_CODE('enbl') pEndPoint = FOUR_CHAR_CODE('pend') pFillColor = FOUR_CHAR_CODE('flcl') pFillPattern = FOUR_CHAR_CODE('flpt') pFont = FOUR_CHAR_CODE('font') pFormula = FOUR_CHAR_CODE('pfor') pGraphicObjects = FOUR_CHAR_CODE('gobs') pHasCloseBox = FOUR_CHAR_CODE('hclb') pHasTitleBar = FOUR_CHAR_CODE('ptit') pID = FOUR_CHAR_CODE('ID ') pIndex = FOUR_CHAR_CODE('pidx') pInsertionLoc = FOUR_CHAR_CODE('pins') pIsFloating = FOUR_CHAR_CODE('isfl') pIsFrontProcess = FOUR_CHAR_CODE('pisf') pIsModal = FOUR_CHAR_CODE('pmod') pIsModified = FOUR_CHAR_CODE('imod') pIsResizable = FOUR_CHAR_CODE('prsz') pIsStationeryPad = FOUR_CHAR_CODE('pspd') pIsZoomable = FOUR_CHAR_CODE('iszm') pIsZoomed = FOUR_CHAR_CODE('pzum') pItemNumber = FOUR_CHAR_CODE('itmn') pJustification = FOUR_CHAR_CODE('pjst') pLineArrow = FOUR_CHAR_CODE('arro') pMenuID = FOUR_CHAR_CODE('mnid') pName = FOUR_CHAR_CODE('pnam') pNewElementLoc = FOUR_CHAR_CODE('pnel') pPenColor = FOUR_CHAR_CODE('ppcl') pPenPattern = FOUR_CHAR_CODE('pppa') pPenWidth = FOUR_CHAR_CODE('ppwd') pPixelDepth = FOUR_CHAR_CODE('pdpt') pPointList = FOUR_CHAR_CODE('ptlt') pPointSize = FOUR_CHAR_CODE('ptsz') pProtection = FOUR_CHAR_CODE('ppro') pRotation = FOUR_CHAR_CODE('prot') pScale = FOUR_CHAR_CODE('pscl') pScript = FOUR_CHAR_CODE('scpt') pScriptTag = FOUR_CHAR_CODE('psct') pSelected = FOUR_CHAR_CODE('selc') pSelection = FOUR_CHAR_CODE('sele') pStartAngle = FOUR_CHAR_CODE('pang') pStartPoint = FOUR_CHAR_CODE('pstp') pTextColor = FOUR_CHAR_CODE('ptxc') pTextFont = FOUR_CHAR_CODE('ptxf') pTextItemDelimiters = FOUR_CHAR_CODE('txdl') pTextPointSize = FOUR_CHAR_CODE('ptps') pTextStyles = FOUR_CHAR_CODE('txst') pTransferMode = FOUR_CHAR_CODE('pptm') pTranslation = FOUR_CHAR_CODE('ptrs') pUniformStyles = FOUR_CHAR_CODE('ustl') pUpdateOn = FOUR_CHAR_CODE('pupd') pUserSelection = FOUR_CHAR_CODE('pusl') pVersion = FOUR_CHAR_CODE('vers') pVisible = FOUR_CHAR_CODE('pvis') typeAEText = FOUR_CHAR_CODE('tTXT') typeArc = FOUR_CHAR_CODE('carc') typeBest = FOUR_CHAR_CODE('best') typeCell = FOUR_CHAR_CODE('ccel') typeClassInfo = FOUR_CHAR_CODE('gcli') typeColorTable = FOUR_CHAR_CODE('clrt') typeColumn = FOUR_CHAR_CODE('ccol') typeDashStyle = FOUR_CHAR_CODE('tdas') typeData = FOUR_CHAR_CODE('tdta') typeDrawingArea = FOUR_CHAR_CODE('cdrw') typeElemInfo = FOUR_CHAR_CODE('elin') typeEnumeration = FOUR_CHAR_CODE('enum') typeEPS = FOUR_CHAR_CODE('EPS ') typeEventInfo = FOUR_CHAR_CODE('evin') typeFinderWindow = FOUR_CHAR_CODE('fwin') typeFixedPoint = FOUR_CHAR_CODE('fpnt') typeFixedRectangle = FOUR_CHAR_CODE('frct') typeGraphicLine = FOUR_CHAR_CODE('glin') typeGraphicText = FOUR_CHAR_CODE('cgtx') typeGroupedGraphic = FOUR_CHAR_CODE('cpic') typeInsertionLoc = FOUR_CHAR_CODE('insl') typeIntlText = FOUR_CHAR_CODE('itxt') typeIntlWritingCode = FOUR_CHAR_CODE('intl') typeLongDateTime = FOUR_CHAR_CODE('ldt ') typeLongFixed = FOUR_CHAR_CODE('lfxd') typeLongFixedPoint = FOUR_CHAR_CODE('lfpt') typeLongFixedRectangle = FOUR_CHAR_CODE('lfrc') typeLongPoint = FOUR_CHAR_CODE('lpnt') typeLongRectangle = FOUR_CHAR_CODE('lrct') typeMachineLoc = FOUR_CHAR_CODE('mLoc') typeOval = FOUR_CHAR_CODE('covl') typeParamInfo = FOUR_CHAR_CODE('pmin') typePict = FOUR_CHAR_CODE('PICT') typePixelMap = FOUR_CHAR_CODE('cpix') typePixMapMinus = FOUR_CHAR_CODE('tpmm') typePolygon = FOUR_CHAR_CODE('cpgn') typePropInfo = FOUR_CHAR_CODE('pinf') typePtr = FOUR_CHAR_CODE('ptr ') typeQDPoint = FOUR_CHAR_CODE('QDpt') typeQDRegion = FOUR_CHAR_CODE('Qrgn') typeRectangle = FOUR_CHAR_CODE('crec') typeRGB16 = FOUR_CHAR_CODE('tr16') typeRGB96 = FOUR_CHAR_CODE('tr96') typeRGBColor = FOUR_CHAR_CODE('cRGB') typeRotation = FOUR_CHAR_CODE('trot') typeRoundedRectangle = FOUR_CHAR_CODE('crrc') typeRow = FOUR_CHAR_CODE('crow') typeScrapStyles = FOUR_CHAR_CODE('styl') typeScript = FOUR_CHAR_CODE('scpt') typeStyledText = FOUR_CHAR_CODE('STXT') typeSuiteInfo = FOUR_CHAR_CODE('suin') typeTable = FOUR_CHAR_CODE('ctbl') typeTextStyles = FOUR_CHAR_CODE('tsty') typeTIFF = FOUR_CHAR_CODE('TIFF') typeVersion = FOUR_CHAR_CODE('vers') kAEMenuClass = FOUR_CHAR_CODE('menu') kAEMenuSelect = FOUR_CHAR_CODE('mhit') kAEMouseDown = FOUR_CHAR_CODE('mdwn') kAEMouseDownInBack = FOUR_CHAR_CODE('mdbk') kAEKeyDown = FOUR_CHAR_CODE('kdwn') kAEResized = FOUR_CHAR_CODE('rsiz') kAEPromise = FOUR_CHAR_CODE('prom') keyMenuID = FOUR_CHAR_CODE('mid ') keyMenuItem = FOUR_CHAR_CODE('mitm') keyCloseAllWindows = FOUR_CHAR_CODE('caw ') keyOriginalBounds = FOUR_CHAR_CODE('obnd') keyNewBounds = FOUR_CHAR_CODE('nbnd') keyLocalWhere = FOUR_CHAR_CODE('lwhr') typeHIMenu = FOUR_CHAR_CODE('mobj') typeHIWindow = FOUR_CHAR_CODE('wobj') kBySmallIcon = 0 kByIconView = 1 kByNameView = 2 kByDateView = 3 kBySizeView = 4 kByKindView = 5 kByCommentView = 6 kByLabelView = 7 kByVersionView = 8 kAEInfo = 11 kAEMain = 0 kAESharing = 13 kAEZoomIn = 7 kAEZoomOut = 8 kTextServiceClass = FOUR_CHAR_CODE('tsvc') kUpdateActiveInputArea = FOUR_CHAR_CODE('updt') kShowHideInputWindow = FOUR_CHAR_CODE('shiw') kPos2Offset = FOUR_CHAR_CODE('p2st') kOffset2Pos = FOUR_CHAR_CODE('st2p') kUnicodeNotFromInputMethod = FOUR_CHAR_CODE('unim') kGetSelectedText = FOUR_CHAR_CODE('gtxt') keyAETSMDocumentRefcon = FOUR_CHAR_CODE('refc') keyAEServerInstance = FOUR_CHAR_CODE('srvi') keyAETheData = FOUR_CHAR_CODE('kdat') keyAEFixLength = FOUR_CHAR_CODE('fixl') keyAEUpdateRange = FOUR_CHAR_CODE('udng') keyAECurrentPoint = FOUR_CHAR_CODE('cpos') keyAEBufferSize = FOUR_CHAR_CODE('buff') keyAEMoveView = FOUR_CHAR_CODE('mvvw') keyAENextBody = FOUR_CHAR_CODE('nxbd') keyAETSMScriptTag = FOUR_CHAR_CODE('sclg') keyAETSMTextFont = FOUR_CHAR_CODE('ktxf') keyAETSMTextPointSize = FOUR_CHAR_CODE('ktps') keyAETSMEventRecord = FOUR_CHAR_CODE('tevt') keyAETSMEventRef = FOUR_CHAR_CODE('tevr') keyAETextServiceEncoding = FOUR_CHAR_CODE('tsen') keyAETextServiceMacEncoding = FOUR_CHAR_CODE('tmen') typeTextRange = FOUR_CHAR_CODE('txrn') typeComponentInstance = FOUR_CHAR_CODE('cmpi') typeOffsetArray = FOUR_CHAR_CODE('ofay') typeTextRangeArray = FOUR_CHAR_CODE('tray') typeLowLevelEventRecord = FOUR_CHAR_CODE('evtr') typeEventRef = FOUR_CHAR_CODE('evrf') typeText = typeChar kTSMOutsideOfBody = 1 kTSMInsideOfBody = 2 kTSMInsideOfActiveInputArea = 3 kNextBody = 1 kPreviousBody = 2 kCaretPosition = 1 kRawText = 2 kSelectedRawText = 3 kConvertedText = 4 kSelectedConvertedText = 5 kBlockFillText = 6 kOutlineText = 7 kSelectedText = 8 keyAEHiliteRange = FOUR_CHAR_CODE('hrng') keyAEPinRange = FOUR_CHAR_CODE('pnrg') keyAEClauseOffsets = FOUR_CHAR_CODE('clau') keyAEOffset = FOUR_CHAR_CODE('ofst') keyAEPoint = FOUR_CHAR_CODE('gpos') keyAELeftSide = FOUR_CHAR_CODE('klef') keyAERegionClass = FOUR_CHAR_CODE('rgnc') keyAEDragging = FOUR_CHAR_CODE('bool') keyAELeadingEdge = keyAELeftSide typeUnicodeText = FOUR_CHAR_CODE('utxt') typeStyledUnicodeText = FOUR_CHAR_CODE('sutx') typeEncodedString = FOUR_CHAR_CODE('encs') typeCString = FOUR_CHAR_CODE('cstr') typePString = FOUR_CHAR_CODE('pstr') typeMeters = FOUR_CHAR_CODE('metr') typeInches = FOUR_CHAR_CODE('inch') typeFeet = FOUR_CHAR_CODE('feet') typeYards = FOUR_CHAR_CODE('yard') typeMiles = FOUR_CHAR_CODE('mile') typeKilometers = FOUR_CHAR_CODE('kmtr') typeCentimeters = FOUR_CHAR_CODE('cmtr') typeSquareMeters = FOUR_CHAR_CODE('sqrm') typeSquareFeet = FOUR_CHAR_CODE('sqft') typeSquareYards = FOUR_CHAR_CODE('sqyd') typeSquareMiles = FOUR_CHAR_CODE('sqmi') typeSquareKilometers = FOUR_CHAR_CODE('sqkm') typeLiters = FOUR_CHAR_CODE('litr') typeQuarts = FOUR_CHAR_CODE('qrts') typeGallons = FOUR_CHAR_CODE('galn') typeCubicMeters = FOUR_CHAR_CODE('cmet') typeCubicFeet = FOUR_CHAR_CODE('cfet') typeCubicInches = FOUR_CHAR_CODE('cuin') typeCubicCentimeter = FOUR_CHAR_CODE('ccmt') typeCubicYards = FOUR_CHAR_CODE('cyrd') typeKilograms = FOUR_CHAR_CODE('kgrm') typeGrams = FOUR_CHAR_CODE('gram') typeOunces = FOUR_CHAR_CODE('ozs ') typePounds = FOUR_CHAR_CODE('lbs ') typeDegreesC = FOUR_CHAR_CODE('degc') typeDegreesF = FOUR_CHAR_CODE('degf') typeDegreesK = FOUR_CHAR_CODE('degk') kFAServerApp = FOUR_CHAR_CODE('ssrv') kDoFolderActionEvent = FOUR_CHAR_CODE('fola') kFolderActionCode = FOUR_CHAR_CODE('actn') kFolderOpenedEvent = FOUR_CHAR_CODE('fopn') kFolderClosedEvent = FOUR_CHAR_CODE('fclo') kFolderWindowMovedEvent = FOUR_CHAR_CODE('fsiz') kFolderItemsAddedEvent = FOUR_CHAR_CODE('fget') kFolderItemsRemovedEvent = FOUR_CHAR_CODE('flos') kItemList = FOUR_CHAR_CODE('flst') kNewSizeParameter = FOUR_CHAR_CODE('fnsz') kFASuiteCode = FOUR_CHAR_CODE('faco') kFAAttachCommand = FOUR_CHAR_CODE('atfa') kFARemoveCommand = FOUR_CHAR_CODE('rmfa') kFAEditCommand = FOUR_CHAR_CODE('edfa') kFAFileParam = FOUR_CHAR_CODE('faal') kFAIndexParam = FOUR_CHAR_CODE('indx') kAEInternetSuite = FOUR_CHAR_CODE('gurl') kAEISWebStarSuite = FOUR_CHAR_CODE('WWW\xbd') kAEISGetURL = FOUR_CHAR_CODE('gurl') KAEISHandleCGI = FOUR_CHAR_CODE('sdoc') cURL = FOUR_CHAR_CODE('url ') cInternetAddress = FOUR_CHAR_CODE('IPAD') cHTML = FOUR_CHAR_CODE('html') cFTPItem = FOUR_CHAR_CODE('ftp ') kAEISHTTPSearchArgs = FOUR_CHAR_CODE('kfor') kAEISPostArgs = FOUR_CHAR_CODE('post') kAEISMethod = FOUR_CHAR_CODE('meth') kAEISClientAddress = FOUR_CHAR_CODE('addr') kAEISUserName = FOUR_CHAR_CODE('user') kAEISPassword = FOUR_CHAR_CODE('pass') kAEISFromUser = FOUR_CHAR_CODE('frmu') kAEISServerName = FOUR_CHAR_CODE('svnm') kAEISServerPort = FOUR_CHAR_CODE('svpt') kAEISScriptName = FOUR_CHAR_CODE('scnm') kAEISContentType = FOUR_CHAR_CODE('ctyp') kAEISReferrer = FOUR_CHAR_CODE('refr') kAEISUserAgent = FOUR_CHAR_CODE('Agnt') kAEISAction = FOUR_CHAR_CODE('Kact') kAEISActionPath = FOUR_CHAR_CODE('Kapt') kAEISClientIP = FOUR_CHAR_CODE('Kcip') kAEISFullRequest = FOUR_CHAR_CODE('Kfrq') pScheme = FOUR_CHAR_CODE('pusc') pHost = FOUR_CHAR_CODE('HOST') pPath = FOUR_CHAR_CODE('FTPc') pUserName = FOUR_CHAR_CODE('RAun') pUserPassword = FOUR_CHAR_CODE('RApw') pDNSForm = FOUR_CHAR_CODE('pDNS') pURL = FOUR_CHAR_CODE('pURL') pTextEncoding = FOUR_CHAR_CODE('ptxe') pFTPKind = FOUR_CHAR_CODE('kind') eScheme = FOUR_CHAR_CODE('esch') eurlHTTP = FOUR_CHAR_CODE('http') eurlHTTPS = FOUR_CHAR_CODE('htps') eurlFTP = FOUR_CHAR_CODE('ftp ') eurlMail = FOUR_CHAR_CODE('mail') eurlFile = FOUR_CHAR_CODE('file') eurlGopher = FOUR_CHAR_CODE('gphr') eurlTelnet = FOUR_CHAR_CODE('tlnt') eurlNews = FOUR_CHAR_CODE('news') eurlSNews = FOUR_CHAR_CODE('snws') eurlNNTP = FOUR_CHAR_CODE('nntp') eurlMessage = FOUR_CHAR_CODE('mess') eurlMailbox = FOUR_CHAR_CODE('mbox') eurlMulti = FOUR_CHAR_CODE('mult') eurlLaunch = FOUR_CHAR_CODE('laun') eurlAFP = FOUR_CHAR_CODE('afp ') eurlAT = FOUR_CHAR_CODE('at ') eurlEPPC = FOUR_CHAR_CODE('eppc') eurlRTSP = FOUR_CHAR_CODE('rtsp') eurlIMAP = FOUR_CHAR_CODE('imap') eurlNFS = FOUR_CHAR_CODE('unfs') eurlPOP = FOUR_CHAR_CODE('upop') eurlLDAP = FOUR_CHAR_CODE('uldp') eurlUnknown = FOUR_CHAR_CODE('url?') kConnSuite = FOUR_CHAR_CODE('macc') cDevSpec = FOUR_CHAR_CODE('cdev') cAddressSpec = FOUR_CHAR_CODE('cadr') cADBAddress = FOUR_CHAR_CODE('cadb') cAppleTalkAddress = FOUR_CHAR_CODE('cat ') cBusAddress = FOUR_CHAR_CODE('cbus') cEthernetAddress = FOUR_CHAR_CODE('cen ') cFireWireAddress = FOUR_CHAR_CODE('cfw ') cIPAddress = FOUR_CHAR_CODE('cip ') cLocalTalkAddress = FOUR_CHAR_CODE('clt ') cSCSIAddress = FOUR_CHAR_CODE('cscs') cTokenRingAddress = FOUR_CHAR_CODE('ctok') cUSBAddress = FOUR_CHAR_CODE('cusb') pDeviceType = FOUR_CHAR_CODE('pdvt') pDeviceAddress = FOUR_CHAR_CODE('pdva') pConduit = FOUR_CHAR_CODE('pcon') pProtocol = FOUR_CHAR_CODE('pprt') pATMachine = FOUR_CHAR_CODE('patm') pATZone = FOUR_CHAR_CODE('patz') pATType = FOUR_CHAR_CODE('patt') pDottedDecimal = FOUR_CHAR_CODE('pipd') pDNS = FOUR_CHAR_CODE('pdns') pPort = FOUR_CHAR_CODE('ppor') pNetwork = FOUR_CHAR_CODE('pnet') pNode = FOUR_CHAR_CODE('pnod') pSocket = FOUR_CHAR_CODE('psoc') pSCSIBus = FOUR_CHAR_CODE('pscb') pSCSILUN = FOUR_CHAR_CODE('pslu') eDeviceType = FOUR_CHAR_CODE('edvt') eAddressSpec = FOUR_CHAR_CODE('eads') eConduit = FOUR_CHAR_CODE('econ') eProtocol = FOUR_CHAR_CODE('epro') eADB = FOUR_CHAR_CODE('eadb') eAnalogAudio = FOUR_CHAR_CODE('epau') eAppleTalk = FOUR_CHAR_CODE('epat') eAudioLineIn = FOUR_CHAR_CODE('ecai') eAudioLineOut = FOUR_CHAR_CODE('ecal') eAudioOut = FOUR_CHAR_CODE('ecao') eBus = FOUR_CHAR_CODE('ebus') eCDROM = FOUR_CHAR_CODE('ecd ') eCommSlot = FOUR_CHAR_CODE('eccm') eDigitalAudio = FOUR_CHAR_CODE('epda') eDisplay = FOUR_CHAR_CODE('edds') eDVD = FOUR_CHAR_CODE('edvd') eEthernet = FOUR_CHAR_CODE('ecen') eFireWire = FOUR_CHAR_CODE('ecfw') eFloppy = FOUR_CHAR_CODE('efd ') eHD = FOUR_CHAR_CODE('ehd ') eInfrared = FOUR_CHAR_CODE('ecir') eIP = FOUR_CHAR_CODE('epip') eIrDA = FOUR_CHAR_CODE('epir') eIRTalk = FOUR_CHAR_CODE('epit') eKeyboard = FOUR_CHAR_CODE('ekbd') eLCD = FOUR_CHAR_CODE('edlc') eLocalTalk = FOUR_CHAR_CODE('eclt') eMacIP = FOUR_CHAR_CODE('epmi') eMacVideo = FOUR_CHAR_CODE('epmv') eMicrophone = FOUR_CHAR_CODE('ecmi') eModemPort = FOUR_CHAR_CODE('ecmp') eModemPrinterPort = FOUR_CHAR_CODE('empp') eModem = FOUR_CHAR_CODE('edmm') eMonitorOut = FOUR_CHAR_CODE('ecmn') eMouse = FOUR_CHAR_CODE('emou') eNuBusCard = FOUR_CHAR_CODE('ednb') eNuBus = FOUR_CHAR_CODE('enub') ePCcard = FOUR_CHAR_CODE('ecpc') ePCIbus = FOUR_CHAR_CODE('ecpi') ePCIcard = FOUR_CHAR_CODE('edpi') ePDSslot = FOUR_CHAR_CODE('ecpd') ePDScard = FOUR_CHAR_CODE('epds') ePointingDevice = FOUR_CHAR_CODE('edpd') ePostScript = FOUR_CHAR_CODE('epps') ePPP = FOUR_CHAR_CODE('eppp') ePrinterPort = FOUR_CHAR_CODE('ecpp') ePrinter = FOUR_CHAR_CODE('edpr') eSvideo = FOUR_CHAR_CODE('epsv') eSCSI = FOUR_CHAR_CODE('ecsc') eSerial = FOUR_CHAR_CODE('epsr') eSpeakers = FOUR_CHAR_CODE('edsp') eStorageDevice = FOUR_CHAR_CODE('edst') eSVGA = FOUR_CHAR_CODE('epsg') eTokenRing = FOUR_CHAR_CODE('etok') eTrackball = FOUR_CHAR_CODE('etrk') eTrackpad = FOUR_CHAR_CODE('edtp') eUSB = FOUR_CHAR_CODE('ecus') eVideoIn = FOUR_CHAR_CODE('ecvi') eVideoMonitor = FOUR_CHAR_CODE('edvm') eVideoOut = FOUR_CHAR_CODE('ecvo') cKeystroke = FOUR_CHAR_CODE('kprs') pKeystrokeKey = FOUR_CHAR_CODE('kMsg') pModifiers = FOUR_CHAR_CODE('kMod') pKeyKind = FOUR_CHAR_CODE('kknd') eModifiers = FOUR_CHAR_CODE('eMds') eOptionDown = FOUR_CHAR_CODE('Kopt') eCommandDown = FOUR_CHAR_CODE('Kcmd') eControlDown = FOUR_CHAR_CODE('Kctl') eShiftDown = FOUR_CHAR_CODE('Ksft') eCapsLockDown = FOUR_CHAR_CODE('Kclk') eKeyKind = FOUR_CHAR_CODE('ekst') eEscapeKey = 0x6B733500 eDeleteKey = 0x6B733300 eTabKey = 0x6B733000 eReturnKey = 0x6B732400 eClearKey = 0x6B734700 eEnterKey = 0x6B734C00 eUpArrowKey = 0x6B737E00 eDownArrowKey = 0x6B737D00 eLeftArrowKey = 0x6B737B00 eRightArrowKey = 0x6B737C00 eHelpKey = 0x6B737200 eHomeKey = 0x6B737300 ePageUpKey = 0x6B737400 ePageDownKey = 0x6B737900 eForwardDelKey = 0x6B737500 eEndKey = 0x6B737700 eF1Key = 0x6B737A00 eF2Key = 0x6B737800 eF3Key = 0x6B736300 eF4Key = 0x6B737600 eF5Key = 0x6B736000 eF6Key = 0x6B736100 eF7Key = 0x6B736200 eF8Key = 0x6B736400 eF9Key = 0x6B736500 eF10Key = 0x6B736D00 eF11Key = 0x6B736700 eF12Key = 0x6B736F00 eF13Key = 0x6B736900 eF14Key = 0x6B736B00 eF15Key = 0x6B737100 kAEAND = FOUR_CHAR_CODE('AND ') kAEOR = FOUR_CHAR_CODE('OR ') kAENOT = FOUR_CHAR_CODE('NOT ') kAEFirst = FOUR_CHAR_CODE('firs') kAELast = FOUR_CHAR_CODE('last') kAEMiddle = FOUR_CHAR_CODE('midd') kAEAny = FOUR_CHAR_CODE('any ') kAEAll = FOUR_CHAR_CODE('all ') kAENext = FOUR_CHAR_CODE('next') kAEPrevious = FOUR_CHAR_CODE('prev') keyAECompOperator = FOUR_CHAR_CODE('relo') keyAELogicalTerms = FOUR_CHAR_CODE('term') keyAELogicalOperator = FOUR_CHAR_CODE('logc') keyAEObject1 = FOUR_CHAR_CODE('obj1') keyAEObject2 = FOUR_CHAR_CODE('obj2') keyAEDesiredClass = FOUR_CHAR_CODE('want') keyAEContainer = FOUR_CHAR_CODE('from') keyAEKeyForm = FOUR_CHAR_CODE('form') keyAEKeyData = FOUR_CHAR_CODE('seld') keyAERangeStart = FOUR_CHAR_CODE('star') keyAERangeStop = FOUR_CHAR_CODE('stop') keyDisposeTokenProc = FOUR_CHAR_CODE('xtok') keyAECompareProc = FOUR_CHAR_CODE('cmpr') keyAECountProc = FOUR_CHAR_CODE('cont') keyAEMarkTokenProc = FOUR_CHAR_CODE('mkid') keyAEMarkProc = FOUR_CHAR_CODE('mark') keyAEAdjustMarksProc = FOUR_CHAR_CODE('adjm') keyAEGetErrDescProc = FOUR_CHAR_CODE('indc') formAbsolutePosition = FOUR_CHAR_CODE('indx') formRelativePosition = FOUR_CHAR_CODE('rele') formTest = FOUR_CHAR_CODE('test') formRange = FOUR_CHAR_CODE('rang') formPropertyID = FOUR_CHAR_CODE('prop') formName = FOUR_CHAR_CODE('name') typeObjectSpecifier = FOUR_CHAR_CODE('obj ') typeObjectBeingExamined = FOUR_CHAR_CODE('exmn') typeCurrentContainer = FOUR_CHAR_CODE('ccnt') typeToken = FOUR_CHAR_CODE('toke') typeRelativeDescriptor = FOUR_CHAR_CODE('rel ') typeAbsoluteOrdinal = FOUR_CHAR_CODE('abso') typeIndexDescriptor = FOUR_CHAR_CODE('inde') typeRangeDescriptor = FOUR_CHAR_CODE('rang') typeLogicalDescriptor = FOUR_CHAR_CODE('logi') typeCompDescriptor = FOUR_CHAR_CODE('cmpd') typeOSLTokenList = FOUR_CHAR_CODE('ostl') kAEIDoMinimum = 0x0000 kAEIDoWhose = 0x0001 kAEIDoMarking = 0x0004 kAEPassSubDescs = 0x0008 kAEResolveNestedLists = 0x0010 kAEHandleSimpleRanges = 0x0020 kAEUseRelativeIterators = 0x0040 typeWhoseDescriptor = FOUR_CHAR_CODE('whos') formWhose = FOUR_CHAR_CODE('whos') typeWhoseRange = FOUR_CHAR_CODE('wrng') keyAEWhoseRangeStart = FOUR_CHAR_CODE('wstr') keyAEWhoseRangeStop = FOUR_CHAR_CODE('wstp') keyAEIndex = FOUR_CHAR_CODE('kidx') keyAETest = FOUR_CHAR_CODE('ktst')
from django.conf.urls import patterns, include, url from citizengrid import cg_api_views, cvm_webapi import os from . import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() # Routers provide an easy way of automatically determining the URL conf. router = cg_api_views.HybridRouter() # Only admin can see this view router.register(r'users', cg_api_views.UserViewSet) router.register(r'groups', cg_api_views.GroupViewSet) # All registered users router.add_api_view("apps", url(r'^apps/$', cg_api_views.ApplicationListPublicView.as_view(), name='ApplicationListPublicView')) router.add_api_view("myapps", url(r'^myapps/$', cg_api_views.MyApplicationListView.as_view(), name='MyApplicationListView')) router.add_api_view("branches", url(r'^branches/$', cg_api_views.BranchListView.as_view(), name='BranchListView')) router.add_api_view("categories", url(r'^categories/$', cg_api_views.CategoryListView.as_view(), name='CategoryListView')) router.add_api_view("subcategories", url(r'^subcategories/$', cg_api_views.SubCategoryListView.as_view(), name='SubCategoryListView')) router.add_api_view("usercredentials", url(r'^usercredentials/$', cg_api_views.UserCloudCredentialsListView.as_view(), name='UserCloudCredentialsListView')) urlpatterns = patterns('', # Examples: url(r'^cg-webapi/', include('cg_webapi.urls')), url(r'^$', 'citizengrid.views.home', name='home'), url(r'^about', 'citizengrid.views.about', name='about'), url(r'^contact', 'citizengrid.views.contact', name='contact'), url(r'^doc', 'citizengrid.views.userdoc', name='userdoc'), url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), url(r'^cg$', 'citizengrid.secure_views.cg', name='cg_home'), url(r'^js/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.join(settings.STATIC_ROOT, 'js')}), url(r'^css/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.join(settings.STATIC_ROOT, 'css')}), url(r'^img/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.join(settings.STATIC_ROOT, 'img')}), url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), url(r'^font/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.join(settings.STATIC_ROOT, 'fonts')}), url(r'^fonts/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.join(settings.STATIC_ROOT, 'fonts')}), url(r'^cg/upload$', 'citizengrid.secure_views.upload', name='jfu_upload'), url(r'^cg/delupload/(?P<uploadid>\d+)$', 'citizengrid.secure_views.delupload', name='del_file'), url(r'^cg/launchapp/(?P<appid>\d+)/(?P<launchtype>\w+)/(?P<apptag>.*)$', 'citizengrid.launch_views.launchapp', name='launch_app'), url(r'^cg/launchserver/(?P<appid>\d+)/(?P<launchtype>\w*)$', 'citizengrid.launch_views.launchserver', name='launch_server'), url( r'^cg/manage/instances/(?P<task>\w+)/(?P<appid>\w*)/(?P<instancerecord>[-\w]*)$', 'citizengrid.launch_views.manage_instances', name='manage_instances'), url(r'^cg/manage/cred$', 'citizengrid.secure_views.manage_credentials', name='manage_credentials'), url(r'^cg/manage/group/applist$', 'citizengrid.secure_views.application_list', name='application_list'), url(r'^cg/manage/group$', 'citizengrid.secure_views.manage_groups', name='manage_groups'), url(r'^cg/manage/group/edit/(?P<id>\d+)$', 'citizengrid.secure_views.edit_group', name='edit_group'), url(r'^cg/manage/group/create/$', 'citizengrid.secure_views.add_group', name='add_group'), url(r'^cg/manage/groups/$', 'citizengrid.secure_views.groups', name='add_group'), url(r'^cg/manage/group/delete/(?P<id>\d+)$', 'citizengrid.secure_views.delete_group', name='delete_group'), url(r'^cg/manage/group/detail/(?P<id>\d+)$', 'citizengrid.secure_views.detail_group', name='delete_group'), url(r'^cg/manage/group/leave/(?P<id>\d+)$', 'citizengrid.secure_views.leave_group', name='leave_group'), url(r'^cg/manage/group/join/$', 'citizengrid.secure_views.join_group', name='join_group'), url(r'^cg/manage/group/attachapptogrp/(?P<id>\d+)$', 'citizengrid.secure_views.attach_app_to_group', name='attach_app_to_group'), url(r'^cg/manage/group/detachfromgroup/(?P<id>\d+)$', 'citizengrid.secure_views.detach_app_from_group', name='detach_app_from_group'), url(r'^cg/manage/group/applicationgrouptagdetail/$', 'citizengrid.secure_views.application_grp_tag_detail', name='application_grp_tag_detail'), url(r'^cg/manage/applicationgrouptag/(?P<id>\d+)$', 'citizengrid.secure_views.application_grp_tag', name='application_grp_tag'), url(r'^cg/manage/updateaccount$', 'citizengrid.secure_views.update_user_account', name='update_user_account'), url(r'^cg/manage/cred/cloud$', 'citizengrid.secure_views.add_update_credentials', name='add_update_credentials'), url(r'^cg/manage/images/(?P<app>\w+)$', 'citizengrid.secure_views.manage_images', name='manage_images'), url(r'^cg/info/servers$', 'citizengrid.secure_views.get_running_servers', name='get_running_servers'), url(r'^cg/info/cloudcredentials$', 'citizengrid.secure_views.get_cloud_credentials', name='get_cloud_credentials'), url(r'^accounts/login/$', 'django.contrib.auth.views.login'), url(r'^accounts/logout/$', 'django.contrib.auth.views.logout'), url(r'^accounts/register/$', 'citizengrid.views.register'), url(r'^accounts/confirmation/$', 'citizengrid.views.register_confirmation'), url(r'^accounts/', include('password_reset.urls')), url(r'^gettabledata/$', 'citizengrid.secure_views.getTableData'), url(r'^getuserapps/$', 'citizengrid.secure_views.getUserApps'), url(r'^cg/appdetail/(?P<appid>\w+)$', 'citizengrid.secure_views.application_detail'), url(r'^cg/myappdetail/(?P<appid>\w+)$', 'citizengrid.secure_views.my_application'), url(r'^cg/delete/(?P<id>[\w-]+)$', 'citizengrid.secure_views.cg_delete'), # jcohen02 - added to support request in issue #20 # Start virtualbox application client url(r'^cg/apps/(?P<appname>\w+)/start/$', 'citizengrid.secure_views.start_app_client', name='start_app_client'), (r'^branch/(?P<branch>\d+)/all_json_category/$', 'citizengrid.views.all_json_category'), (r'^category/(?P<category>\d+)/all_json_subcategory/$', 'citizengrid.views.all_json_subcategory'), url(r'^cg/app/wizard$', 'citizengrid.secure_views.wrapped_wizard_view', name='wrapped_wizard_view'), # url(r'^api/citizengrid/apps/(?P<appid>\d+)/$', # cg_api_views.ApplicationDetailListView.as_view(), # name='ApplicationDetailListView'), url(r'^api/citizengrid/myapps/(?P<appid>\d+)/$', cg_api_views.MyApplicationDetailListView.as_view(), name='MyApplicationDetailListView'), # start the application locally url(r'^api/citizengrid/apps/(?P<appid>\d+)/startapp/$', 'citizengrid.cg_api_views.startapp_locally', name='start'), url(r'^api/citizengrid/apps/(?P<appid>\d+)/files/$', cg_api_views.ApplicationFileList.as_view(), name='ApplicationFileList'), url( r'^api/citizengrid/apps/(?P<appid>\d+)/files/(?P<fileid>\d+)/$', cg_api_views.ApplicationFileDetail.as_view(), name='ApplicationFileDetail'), # OSImagesList url(r'^api/citizengrid/apps/(?P<appid>\d+)/osimages/$', cg_api_views.ApplicationOpenstackImagesList.as_view(), name='ApplicationOpenstackImagesList'), # OsImage Detail url url( r'^api/citizengrid/apps/(?P<appid>\d+)/osimages/(?P<fileid>\d+)/$', cg_api_views.ApplicationOpenstackImageDetail.as_view(), name='ApplicationOpenstackImageDetail'), # EC2ImagesList url(r'^api/citizengrid/apps/(?P<appid>\d+)/ec2images/$', cg_api_views.ApplicationEc2ImagesList.as_view(), name='ApplicationEc2ImagesList'), # EC2Image Detail url url( r'^api/citizengrid/apps/(?P<appid>\d+)/ec2images/(?P<fileid>\d+)/$', cg_api_views.ApplicationEc2ImageDetail.as_view(), name='ApplicationEc2ImageDetail'), # start EC2 app on cloud url( r'^api/citizengrid/apps/(?P<appid>\d+)/ec2images/(?P<fileid>\d+)/startserver/$', cg_api_views.start_Ec2server, name='start_Ec2server'), # start OpenStack app on cloud url( r'^api/citizengrid/apps/(?P<appid>\d+)/osimages/(?P<fileid>\d+)/startserver/$', cg_api_views.start_OpenstackServer, name='start_OpenstackServer'), # Credentials list url(r'^api/citizengrid/usercredentials/(?P<credid>\d+)/$', cg_api_views.UserCloudCredentialsDetailView.as_view(), name='UserCloudCredentialsDetailView'), # Openstack Instances url(r'^api/citizengrid/apps/(?P<appid>\d+)/osinstances/$', cg_api_views.CloudInstancesList.as_view(), name='CloudInstancesList'), url( r'^api/citizengrid/apps/(?P<appid>\d+)/osinstances/(?P<instanceid>([a-zA-Z])-([0-9a-zA-Z])+)/$', cg_api_views.CloudInstancesDetail.as_view(), name='CloudInstancesDetail'), # AWS Instances url(r'^api/citizengrid/apps/(?P<appid>\d+)/awsinstances/$', cg_api_views.AWSCloudInstancesList.as_view(), name='AWSCloudInstancesList'), url( r'^api/citizengrid/apps/(?P<appid>\d+)/awsinstances/(?P<instanceid>([a-zA-Z])-([0-9a-zA-Z])+)/$', cg_api_views.AWSCloudInstancesDetail.as_view(), name='AWSCloudInstancesDetail'), # stop instance url( r'^api/citizengrid/apps/(?P<appid>\d+)/instances/(?P<instanceid>([a-zA-Z])-([0-9a-zA-Z])+)/stop$', cg_api_views.stopinstance, name='stopinstance'), # Group web api urls # List all groups url(r'^api/citizengrid/manage/group$', cg_api_views.MyGroupList.as_view(), name='MyGroupList'), url(r'^api/citizengrid/manage/group/(?P<pk>\d+)$', cg_api_views.MyGroupDetailView.as_view(), name='MyGroupDetailView'), url(r'^api/citizengrid/manage/group/(?P<groupid>\d+)/leave$', cg_api_views.leave_group, name='leave_group'), url(r'^api/citizengrid/manage/group/join', cg_api_views.join_group, name='join_group'), url(r'^api/citizengrid/manage/group/(?P<groupid>\d+)/attachapp$', cg_api_views.attachapp, name='attachapp'), url(r'^api/citizengrid/manage/group/detachapp/(?P<appid>\d+)$', cg_api_views.detachapp, name='detachapp'), url(r'^api/citizengrid/', include(router.urls)), url(r'^api-auth/citizengrid/', include('rest_framework.urls', namespace='rest_framework')), # CernVM Web API VMCP endpoint + endpoint for non-HTTP url(r'^vmcp$', cvm_webapi.vmcp, name='vmcp'), url(r'^webapi_start$', cvm_webapi.webapi_start, name='webapi_start'), # admin url(r'^admin/', include(admin.site.urls)), )
""" Helper to download lyrics from darklyrics.com """ from __future__ import unicode_literals from threading import Lock import re import requests from bs4 import BeautifulSoup, NavigableString, Tag, Comment import lyricstagger.log as log class Cache(object): """Simple thread-safe cache based on dict""" def __init__(self): self.dict = {} self.lock = Lock() def __getitem__(self, key): with self.lock: return self.dict[key] def __setitem__(self, key, value): with self.lock: self.dict[key] = value def __delitem__(self, key): with self.lock: del self.dict[key] def __contains__(self, item): with self.lock: return item in self.dict def set_artist_page(self, artist: str, page: str): if artist in self: self[artist]["page"] = page else: self[artist] = dict(page=page, album_pages=dict()) def get_artist_page(self, artist: str) -> str: if artist in self: return self[artist]["page"] else: return "" def has_artist(self, artist: str) -> bool: return artist in self def get_album_page(self, artist: str, album: str) -> str: if artist in self: if album in self[artist]["album_pages"]: return self[artist]["album_pages"][album] return None def set_album_page(self, artist: str, album: str, page: str): if artist in self: self[artist]["album_pages"][album] = page else: self[artist] = dict(page="", album_pages=dict(album=page)) def has_album_page(self, artist, album): if artist in self: if album in self[artist]["album_pages"]: return True return False class DarkLyrics(object): """Lyrics Downloader for darklyrics.com""" url = "http://www.darklyrics.com" def __init__(self): self.cache = Cache() @staticmethod def parse(text: str, song: str) -> str: """Parse lyrics from html""" # parse the result soup = BeautifulSoup(text, "html.parser") lyrics_div = soup.find('div', "lyrics") if lyrics_div is None: log.debug("BeautifulSoup failed to find 'lyrics' div") return None for element in lyrics_div(text=lambda txt: isinstance(txt, Comment)): element.extract() lyrics = '' song_found = False for content in lyrics_div.contents: if content.name == "h3": if content.string and re.match(r"^\d+\.\s+%s$" % song, content.string, re.I): song_found = True continue else: if song_found: break song_found = False if song_found: if isinstance(content, NavigableString): lyrics += content.strip() elif isinstance(content, Tag): if (content.string and content.name == "i" and content.string.startswith("[Instrumental]")): return '{{Instrumental}}' elif content.name == "br": lyrics += '\n' if content.name not in ['script', 'a', 'div'] and content.string: lyrics += content.string.strip() return lyrics.strip() @staticmethod def parse_artist_link(data: str) -> str: """Parse search page and return link to artist page""" soup = BeautifulSoup(data, "html.parser") cont_div = soup.find('div', "cont") if not cont_div: log.debug("BeautifulSoup failed to find 'cont' div") return None link = "" artists_found = False for content in cont_div: if content.name == "h3": if content.string and content.string == "Artists:": artists_found = True continue else: if artists_found: break artists_found = False if artists_found: if content.name == 'a': link_a = content else: link_a = content.find('a') if isinstance(link_a, Tag): return link_a['href'] return link @staticmethod def parse_album_link(data: str, album: str) -> str: """Parse artist page and return link to album page""" soup = BeautifulSoup(data, "html.parser") album_divs = soup.find_all('div', "album") if not album_divs: log.debug("BeautifulSoup failed to find 'album' divs") return None link = "" album_found = False for div in album_divs: for content in div: if content.name == "h2": if content.string: possible_album = content else: possible_album = content.find("strong") log.debug(possible_album) if possible_album and re.match(r'"?%s"?' % album, possible_album.string, re.I): album_found = True continue else: if album_found: break album_found = False if album_found: log.debug(content) if content.name == 'a': link_a = content else: link_a = content.find('a') if isinstance(link_a, Tag): replaced = re.sub(r"#\d+|\.\.", "", link_a['href']) return DarkLyrics.url + replaced return link @staticmethod def get_link_content(link: str) -> str: """Perform request and return response text or None""" log.debug("Fetching %s" % link) result = requests.get(link) if result.status_code != 200: log.debug("Got code %d" % result.status_code) return None return result.text def _get_artist_page(self, artist: str) -> str: if self.cache.has_artist(artist): page = self.cache.get_artist_page(artist) if page: log.debug("Found artist '%s' page in cache" % artist) return page else: log.debug("Skipping artist '%s' because we know it's missing on website" % artist) return None else: search_page = self.get_link_content(DarkLyrics.url + "/search?q=" + artist) artist_link = self.parse_artist_link(search_page) if not artist_link: log.debug("Failed to find artist link") # mark this artist in cache as unavailable self.cache.set_artist_page(artist, "") return None artist_page = self.get_link_content(artist_link) log.debug("Adding artist '%s' page to cache" % artist) self.cache.set_artist_page(artist, artist_page) return artist_page def _get_album_page(self, artist: str, album: str) -> str: if self.cache.has_album_page(artist, album): album_page = self.cache.get_album_page(artist, album) if album_page: log.debug("Found album '%s' page in cache" % album) return album_page else: log.debug("Skipping album '%s' because we know it's missing on website" % artist) return None else: artist_page = self._get_artist_page(artist) if artist_page: album_link = self.parse_album_link(artist_page, album) if not album_link: log.debug("Failed to find album link") # mark this album in cache as unavailable self.cache.set_album_page(artist, album, "") return None album_page = self.get_link_content(album_link) log.debug("Adding album '%s' page to cache" % album) self.cache.set_album_page(artist, album, album_page) return album_page else: return None def fetch(self, artist: str, song: str, album: str) -> str: """Fetch lyrics from remote url""" album_page = self._get_album_page(artist, album) if album_page: log.debug("Parsing lyrics for '{0}' - '{1}'".format(artist, song)) return DarkLyrics.parse(album_page, song) log.debug("Failed to parse lyrics") return None
# pylint: disable=too-many-public-methods """Test for letsencrypt_apache.configurator.""" import os import shutil import socket import unittest import mock from acme import challenges from letsencrypt import achallenges from letsencrypt import errors from letsencrypt.tests import acme_util from letsencrypt_apache import configurator from letsencrypt_apache import obj from letsencrypt_apache.tests import util class TwoVhost80Test(util.ApacheTest): """Test two standard well-configured HTTP vhosts.""" def setUp(self): # pylint: disable=arguments-differ super(TwoVhost80Test, self).setUp() self.config = util.get_apache_configurator( self.config_path, self.vhost_path, self.config_dir, self.work_dir) self.config = self.mock_deploy_cert(self.config) self.vh_truth = util.get_vh_truth( self.temp_dir, "debian_apache_2_4/two_vhost_80") def mock_deploy_cert(self, config): """A test for a mock deploy cert""" self.config.real_deploy_cert = self.config.deploy_cert def mocked_deploy_cert(*args, **kwargs): """a helper to mock a deployed cert""" with mock.patch("letsencrypt_apache.configurator.ApacheConfigurator.enable_mod"): config.real_deploy_cert(*args, **kwargs) self.config.deploy_cert = mocked_deploy_cert return self.config def tearDown(self): shutil.rmtree(self.temp_dir) shutil.rmtree(self.config_dir) shutil.rmtree(self.work_dir) @mock.patch("letsencrypt_apache.configurator.le_util.exe_exists") def test_prepare_no_install(self, mock_exe_exists): mock_exe_exists.return_value = False self.assertRaises( errors.NoInstallationError, self.config.prepare) @mock.patch("letsencrypt_apache.parser.ApacheParser") @mock.patch("letsencrypt_apache.configurator.le_util.exe_exists") def test_prepare_version(self, mock_exe_exists, _): mock_exe_exists.return_value = True self.config.version = None self.config.config_test = mock.Mock() self.config.get_version = mock.Mock(return_value=(1, 1)) self.assertRaises( errors.NotSupportedError, self.config.prepare) @mock.patch("letsencrypt_apache.parser.ApacheParser") @mock.patch("letsencrypt_apache.configurator.le_util.exe_exists") def test_prepare_old_aug(self, mock_exe_exists, _): mock_exe_exists.return_value = True self.config.config_test = mock.Mock() # pylint: disable=protected-access self.config._check_aug_version = mock.Mock(return_value=False) self.assertRaises( errors.NotSupportedError, self.config.prepare) def test_add_parser_arguments(self): # pylint: disable=no-self-use from letsencrypt_apache.configurator import ApacheConfigurator # Weak test.. ApacheConfigurator.add_parser_arguments(mock.MagicMock()) @mock.patch("zope.component.getUtility") def test_get_all_names(self, mock_getutility): mock_getutility.notification = mock.MagicMock(return_value=True) names = self.config.get_all_names() self.assertEqual(names, set( ["letsencrypt.demo", "encryption-example.demo", "ip-172-30-0-17"])) @mock.patch("zope.component.getUtility") @mock.patch("letsencrypt_apache.configurator.socket.gethostbyaddr") def test_get_all_names_addrs(self, mock_gethost, mock_getutility): mock_gethost.side_effect = [("google.com", "", ""), socket.error] notification = mock.Mock() notification.notification = mock.Mock(return_value=True) mock_getutility.return_value = notification vhost = obj.VirtualHost( "fp", "ap", set([obj.Addr(("8.8.8.8", "443")), obj.Addr(("zombo.com",)), obj.Addr(("192.168.1.2"))]), True, False) self.config.vhosts.append(vhost) names = self.config.get_all_names() self.assertEqual(len(names), 5) self.assertTrue("zombo.com" in names) self.assertTrue("google.com" in names) self.assertTrue("letsencrypt.demo" in names) def test_add_servernames_alias(self): self.config.parser.add_dir( self.vh_truth[2].path, "ServerAlias", ["*.le.co"]) # pylint: disable=protected-access self.config._add_servernames(self.vh_truth[2]) self.assertEqual( self.vh_truth[2].get_names(), set(["*.le.co", "ip-172-30-0-17"])) def test_get_virtual_hosts(self): """Make sure all vhosts are being properly found. .. note:: If test fails, only finding 1 Vhost... it is likely that it is a problem with is_enabled. If finding only 3, likely is_ssl """ vhs = self.config.get_virtual_hosts() self.assertEqual(len(vhs), 6) found = 0 for vhost in vhs: for truth in self.vh_truth: if vhost == truth: found += 1 break else: raise Exception("Missed: %s" % vhost) # pragma: no cover self.assertEqual(found, 6) # Handle case of non-debian layout get_virtual_hosts with mock.patch( "letsencrypt_apache.configurator.ApacheConfigurator.conf" ) as mock_conf: mock_conf.return_value = False vhs = self.config.get_virtual_hosts() self.assertEqual(len(vhs), 6) @mock.patch("letsencrypt_apache.display_ops.select_vhost") def test_choose_vhost_none_avail(self, mock_select): mock_select.return_value = None self.assertRaises( errors.PluginError, self.config.choose_vhost, "none.com") @mock.patch("letsencrypt_apache.display_ops.select_vhost") def test_choose_vhost_select_vhost_ssl(self, mock_select): mock_select.return_value = self.vh_truth[1] self.assertEqual( self.vh_truth[1], self.config.choose_vhost("none.com")) @mock.patch("letsencrypt_apache.display_ops.select_vhost") def test_choose_vhost_select_vhost_non_ssl(self, mock_select): mock_select.return_value = self.vh_truth[0] chosen_vhost = self.config.choose_vhost("none.com") self.vh_truth[0].aliases.add("none.com") self.assertEqual( self.vh_truth[0].get_names(), chosen_vhost.get_names()) # Make sure we go from HTTP -> HTTPS self.assertFalse(self.vh_truth[0].ssl) self.assertTrue(chosen_vhost.ssl) @mock.patch("letsencrypt_apache.display_ops.select_vhost") def test_choose_vhost_select_vhost_with_temp(self, mock_select): mock_select.return_value = self.vh_truth[0] chosen_vhost = self.config.choose_vhost("none.com", temp=True) self.assertEqual(self.vh_truth[0], chosen_vhost) @mock.patch("letsencrypt_apache.display_ops.select_vhost") def test_choose_vhost_select_vhost_conflicting_non_ssl(self, mock_select): mock_select.return_value = self.vh_truth[3] conflicting_vhost = obj.VirtualHost( "path", "aug_path", set([obj.Addr.fromstring("*:443")]), True, True) self.config.vhosts.append(conflicting_vhost) self.assertRaises( errors.PluginError, self.config.choose_vhost, "none.com") def test_find_best_vhost(self): # pylint: disable=protected-access self.assertEqual( self.vh_truth[3], self.config._find_best_vhost("letsencrypt.demo")) self.assertEqual( self.vh_truth[0], self.config._find_best_vhost("encryption-example.demo")) self.assertEqual( self.config._find_best_vhost("does-not-exist.com"), None) def test_find_best_vhost_variety(self): # pylint: disable=protected-access ssl_vh = obj.VirtualHost( "fp", "ap", set([obj.Addr(("*", "443")), obj.Addr(("zombo.com",))]), True, False) self.config.vhosts.append(ssl_vh) self.assertEqual(self.config._find_best_vhost("zombo.com"), ssl_vh) def test_find_best_vhost_default(self): # pylint: disable=protected-access # Assume only the two default vhosts. self.config.vhosts = [ vh for vh in self.config.vhosts if vh.name not in ["letsencrypt.demo", "encryption-example.demo"] ] self.assertEqual( self.config._find_best_vhost("example.demo"), self.vh_truth[2]) def test_non_default_vhosts(self): # pylint: disable=protected-access self.assertEqual(len(self.config._non_default_vhosts()), 4) def test_is_site_enabled(self): """Test if site is enabled. .. note:: This test currently fails for hard links (which may happen if you move dirs incorrectly) .. warning:: This test does not work when running using the unittest.main() function. It incorrectly copies symlinks. """ self.assertTrue(self.config.is_site_enabled(self.vh_truth[0].filep)) self.assertFalse(self.config.is_site_enabled(self.vh_truth[1].filep)) self.assertTrue(self.config.is_site_enabled(self.vh_truth[2].filep)) self.assertTrue(self.config.is_site_enabled(self.vh_truth[3].filep)) with mock.patch("os.path.isdir") as mock_isdir: mock_isdir.return_value = False self.assertRaises(errors.ConfigurationError, self.config.is_site_enabled, "irrelevant") @mock.patch("letsencrypt.le_util.run_script") @mock.patch("letsencrypt.le_util.exe_exists") @mock.patch("letsencrypt_apache.parser.subprocess.Popen") def test_enable_mod(self, mock_popen, mock_exe_exists, mock_run_script): mock_popen().communicate.return_value = ("Define: DUMP_RUN_CFG", "") mock_popen().returncode = 0 mock_exe_exists.return_value = True self.config.enable_mod("ssl") self.assertTrue("ssl_module" in self.config.parser.modules) self.assertTrue("mod_ssl.c" in self.config.parser.modules) self.assertTrue(mock_run_script.called) def test_enable_mod_unsupported_dirs(self): shutil.rmtree(os.path.join(self.config.parser.root, "mods-enabled")) self.assertRaises( errors.NotSupportedError, self.config.enable_mod, "ssl") @mock.patch("letsencrypt.le_util.exe_exists") def test_enable_mod_no_disable(self, mock_exe_exists): mock_exe_exists.return_value = False self.assertRaises( errors.MisconfigurationError, self.config.enable_mod, "ssl") def test_enable_site(self): # Default 443 vhost self.assertFalse(self.vh_truth[1].enabled) self.config.enable_site(self.vh_truth[1]) self.assertTrue(self.vh_truth[1].enabled) # Go again to make sure nothing fails self.config.enable_site(self.vh_truth[1]) def test_enable_site_failure(self): self.assertRaises( errors.NotSupportedError, self.config.enable_site, obj.VirtualHost("asdf", "afsaf", set(), False, False)) def test_deploy_cert_newssl(self): self.config = util.get_apache_configurator( self.config_path, self.vhost_path, self.config_dir, self.work_dir, version=(2, 4, 16)) self.config.parser.modules.add("ssl_module") self.config.parser.modules.add("mod_ssl.c") # Get the default 443 vhost self.config.assoc["random.demo"] = self.vh_truth[1] self.config = self.mock_deploy_cert(self.config) self.config.deploy_cert( "random.demo", "example/cert.pem", "example/key.pem", "example/cert_chain.pem", "example/fullchain.pem") self.config.save() # Verify ssl_module was enabled. self.assertTrue(self.vh_truth[1].enabled) self.assertTrue("ssl_module" in self.config.parser.modules) loc_cert = self.config.parser.find_dir( "sslcertificatefile", "example/fullchain.pem", self.vh_truth[1].path) loc_key = self.config.parser.find_dir( "sslcertificateKeyfile", "example/key.pem", self.vh_truth[1].path) # Verify one directive was found in the correct file self.assertEqual(len(loc_cert), 1) self.assertEqual(configurator.get_file_path(loc_cert[0]), self.vh_truth[1].filep) self.assertEqual(len(loc_key), 1) self.assertEqual(configurator.get_file_path(loc_key[0]), self.vh_truth[1].filep) def test_deploy_cert_newssl_no_fullchain(self): self.config = util.get_apache_configurator( self.config_path, self.vhost_path, self.config_dir, self.work_dir, version=(2, 4, 16)) self.config = self.mock_deploy_cert(self.config) self.config.parser.modules.add("ssl_module") self.config.parser.modules.add("mod_ssl.c") # Get the default 443 vhost self.config.assoc["random.demo"] = self.vh_truth[1] self.assertRaises(errors.PluginError, lambda: self.config.deploy_cert( "random.demo", "example/cert.pem", "example/key.pem")) def test_deploy_cert_old_apache_no_chain(self): self.config = util.get_apache_configurator( self.config_path, self.vhost_path, self.config_dir, self.work_dir, version=(2, 4, 7)) self.config = self.mock_deploy_cert(self.config) self.config.parser.modules.add("ssl_module") self.config.parser.modules.add("mod_ssl.c") # Get the default 443 vhost self.config.assoc["random.demo"] = self.vh_truth[1] self.assertRaises(errors.PluginError, lambda: self.config.deploy_cert( "random.demo", "example/cert.pem", "example/key.pem")) def test_deploy_cert(self): self.config.parser.modules.add("ssl_module") self.config.parser.modules.add("mod_ssl.c") # Get the default 443 vhost self.config.assoc["random.demo"] = self.vh_truth[1] self.config.deploy_cert( "random.demo", "example/cert.pem", "example/key.pem", "example/cert_chain.pem") self.config.save() # Verify ssl_module was enabled. self.assertTrue(self.vh_truth[1].enabled) self.assertTrue("ssl_module" in self.config.parser.modules) loc_cert = self.config.parser.find_dir( "sslcertificatefile", "example/cert.pem", self.vh_truth[1].path) loc_key = self.config.parser.find_dir( "sslcertificateKeyfile", "example/key.pem", self.vh_truth[1].path) loc_chain = self.config.parser.find_dir( "SSLCertificateChainFile", "example/cert_chain.pem", self.vh_truth[1].path) # Verify one directive was found in the correct file self.assertEqual(len(loc_cert), 1) self.assertEqual(configurator.get_file_path(loc_cert[0]), self.vh_truth[1].filep) self.assertEqual(len(loc_key), 1) self.assertEqual(configurator.get_file_path(loc_key[0]), self.vh_truth[1].filep) self.assertEqual(len(loc_chain), 1) self.assertEqual(configurator.get_file_path(loc_chain[0]), self.vh_truth[1].filep) # One more time for chain directive setting self.config.deploy_cert( "random.demo", "two/cert.pem", "two/key.pem", "two/cert_chain.pem") self.assertTrue(self.config.parser.find_dir( "SSLCertificateChainFile", "two/cert_chain.pem", self.vh_truth[1].path)) def test_deploy_cert_invalid_vhost(self): self.config.parser.modules.add("ssl_module") mock_find = mock.MagicMock() mock_find.return_value = [] self.config.parser.find_dir = mock_find # Get the default 443 vhost self.config.assoc["random.demo"] = self.vh_truth[1] self.assertRaises( errors.PluginError, self.config.deploy_cert, "random.demo", "example/cert.pem", "example/key.pem", "example/cert_chain.pem") def test_is_name_vhost(self): addr = obj.Addr.fromstring("*:80") self.assertTrue(self.config.is_name_vhost(addr)) self.config.version = (2, 2) self.assertFalse(self.config.is_name_vhost(addr)) def test_add_name_vhost(self): self.config.add_name_vhost(obj.Addr.fromstring("*:443")) self.config.add_name_vhost(obj.Addr.fromstring("*:80")) self.assertTrue(self.config.parser.find_dir( "NameVirtualHost", "*:443", exclude=False)) self.assertTrue(self.config.parser.find_dir( "NameVirtualHost", "*:80")) def test_prepare_server_https(self): mock_enable = mock.Mock() self.config.enable_mod = mock_enable mock_find = mock.Mock() mock_add_dir = mock.Mock() mock_find.return_value = [] # This will test the Add listen self.config.parser.find_dir = mock_find self.config.parser.add_dir_to_ifmodssl = mock_add_dir self.config.prepare_server_https("443") # Changing the order these modules are enabled breaks the reverter self.assertEqual(mock_enable.call_args_list[0][0][0], "socache_shmcb") self.assertEqual(mock_enable.call_args[0][0], "ssl") self.assertEqual(mock_enable.call_args[1], {"temp": False}) self.config.prepare_server_https("8080", temp=True) # Changing the order these modules are enabled breaks the reverter self.assertEqual(mock_enable.call_args_list[2][0][0], "socache_shmcb") self.assertEqual(mock_enable.call_args[0][0], "ssl") # Enable mod is temporary self.assertEqual(mock_enable.call_args[1], {"temp": True}) self.assertEqual(mock_add_dir.call_count, 2) def test_prepare_server_https_named_listen(self): mock_find = mock.Mock() mock_find.return_value = ["test1", "test2", "test3"] mock_get = mock.Mock() mock_get.side_effect = ["1.2.3.4:80", "[::1]:80", "1.1.1.1:443"] mock_add_dir = mock.Mock() mock_enable = mock.Mock() self.config.parser.find_dir = mock_find self.config.parser.get_arg = mock_get self.config.parser.add_dir_to_ifmodssl = mock_add_dir self.config.enable_mod = mock_enable # Test Listen statements with specific ip listeed self.config.prepare_server_https("443") # Should only be 2 here, as the third interface # already listens to the correct port self.assertEqual(mock_add_dir.call_count, 2) # Check argument to new Listen statements self.assertEqual(mock_add_dir.call_args_list[0][0][2], ["1.2.3.4:443"]) self.assertEqual(mock_add_dir.call_args_list[1][0][2], ["[::1]:443"]) # Reset return lists and inputs mock_add_dir.reset_mock() mock_get.side_effect = ["1.2.3.4:80", "[::1]:80", "1.1.1.1:443"] # Test self.config.prepare_server_https("8080", temp=True) self.assertEqual(mock_add_dir.call_count, 3) self.assertEqual(mock_add_dir.call_args_list[0][0][2], ["1.2.3.4:8080", "https"]) self.assertEqual(mock_add_dir.call_args_list[1][0][2], ["[::1]:8080", "https"]) self.assertEqual(mock_add_dir.call_args_list[2][0][2], ["1.1.1.1:8080", "https"]) def test_prepare_server_https_mixed_listen(self): mock_find = mock.Mock() mock_find.return_value = ["test1", "test2"] mock_get = mock.Mock() mock_get.side_effect = ["1.2.3.4:8080", "443"] mock_add_dir = mock.Mock() mock_enable = mock.Mock() self.config.parser.find_dir = mock_find self.config.parser.get_arg = mock_get self.config.parser.add_dir_to_ifmodssl = mock_add_dir self.config.enable_mod = mock_enable # Test Listen statements with specific ip listeed self.config.prepare_server_https("443") # Should only be 2 here, as the third interface # already listens to the correct port self.assertEqual(mock_add_dir.call_count, 0) def test_make_vhost_ssl(self): ssl_vhost = self.config.make_vhost_ssl(self.vh_truth[0]) self.assertEqual( ssl_vhost.filep, os.path.join(self.config_path, "sites-available", "encryption-example-le-ssl.conf")) self.assertEqual(ssl_vhost.path, "/files" + ssl_vhost.filep + "/IfModule/VirtualHost") self.assertEqual(len(ssl_vhost.addrs), 1) self.assertEqual(set([obj.Addr.fromstring("*:443")]), ssl_vhost.addrs) self.assertEqual(ssl_vhost.name, "encryption-example.demo") self.assertTrue(ssl_vhost.ssl) self.assertFalse(ssl_vhost.enabled) self.assertTrue(self.config.parser.find_dir( "SSLCertificateFile", None, ssl_vhost.path, False)) self.assertTrue(self.config.parser.find_dir( "SSLCertificateKeyFile", None, ssl_vhost.path, False)) self.assertEqual(self.config.is_name_vhost(self.vh_truth[0]), self.config.is_name_vhost(ssl_vhost)) self.assertEqual(len(self.config.vhosts), 7) def test_clean_vhost_ssl(self): # pylint: disable=protected-access for directive in ["SSLCertificateFile", "SSLCertificateKeyFile", "SSLCertificateChainFile", "SSLCACertificatePath"]: for _ in range(10): self.config.parser.add_dir(self.vh_truth[1].path, directive, ["bogus"]) self.config.save() self.config._clean_vhost(self.vh_truth[1]) self.config.save() loc_cert = self.config.parser.find_dir( 'SSLCertificateFile', None, self.vh_truth[1].path, False) loc_key = self.config.parser.find_dir( 'SSLCertificateKeyFile', None, self.vh_truth[1].path, False) loc_chain = self.config.parser.find_dir( 'SSLCertificateChainFile', None, self.vh_truth[1].path, False) loc_cacert = self.config.parser.find_dir( 'SSLCACertificatePath', None, self.vh_truth[1].path, False) self.assertEqual(len(loc_cert), 1) self.assertEqual(len(loc_key), 1) self.assertEqual(len(loc_chain), 0) self.assertEqual(len(loc_cacert), 10) def test_deduplicate_directives(self): # pylint: disable=protected-access DIRECTIVE = "Foo" for _ in range(10): self.config.parser.add_dir(self.vh_truth[1].path, DIRECTIVE, ["bar"]) self.config.save() self.config._deduplicate_directives(self.vh_truth[1].path, [DIRECTIVE]) self.config.save() self.assertEqual( len(self.config.parser.find_dir( DIRECTIVE, None, self.vh_truth[1].path, False)), 1) def test_remove_directives(self): # pylint: disable=protected-access DIRECTIVES = ["Foo", "Bar"] for directive in DIRECTIVES: for _ in range(10): self.config.parser.add_dir(self.vh_truth[1].path, directive, ["baz"]) self.config.save() self.config._remove_directives(self.vh_truth[1].path, DIRECTIVES) self.config.save() for directive in DIRECTIVES: self.assertEqual( len(self.config.parser.find_dir( directive, None, self.vh_truth[1].path, False)), 0) def test_make_vhost_ssl_extra_vhs(self): self.config.aug.match = mock.Mock(return_value=["p1", "p2"]) self.assertRaises( errors.PluginError, self.config.make_vhost_ssl, self.vh_truth[0]) def test_make_vhost_ssl_bad_write(self): mock_open = mock.mock_open() # This calls open self.config.reverter.register_file_creation = mock.Mock() mock_open.side_effect = IOError with mock.patch("__builtin__.open", mock_open): self.assertRaises( errors.PluginError, self.config.make_vhost_ssl, self.vh_truth[0]) def test_get_ssl_vhost_path(self): # pylint: disable=protected-access self.assertTrue( self.config._get_ssl_vhost_path("example_path").endswith(".conf")) def test_add_name_vhost_if_necessary(self): # pylint: disable=protected-access self.config.save = mock.Mock() self.config.version = (2, 2) self.config._add_name_vhost_if_necessary(self.vh_truth[0]) self.assertTrue(self.config.save.called) new_addrs = set() for addr in self.vh_truth[0].addrs: new_addrs.add(obj.Addr(("_default_", addr.get_port(),))) self.vh_truth[0].addrs = new_addrs self.config._add_name_vhost_if_necessary(self.vh_truth[0]) self.assertEqual(self.config.save.call_count, 2) @mock.patch("letsencrypt_apache.configurator.tls_sni_01.ApacheTlsSni01.perform") @mock.patch("letsencrypt_apache.configurator.ApacheConfigurator.restart") def test_perform(self, mock_restart, mock_perform): # Only tests functionality specific to configurator.perform # Note: As more challenges are offered this will have to be expanded account_key, achall1, achall2 = self.get_achalls() expected = [ achall1.response(account_key), achall2.response(account_key), ] mock_perform.return_value = expected responses = self.config.perform([achall1, achall2]) self.assertEqual(mock_perform.call_count, 1) self.assertEqual(responses, expected) self.assertEqual(mock_restart.call_count, 1) @mock.patch("letsencrypt_apache.configurator.ApacheConfigurator.restart") def test_cleanup(self, mock_restart): _, achall1, achall2 = self.get_achalls() self.config._chall_out.add(achall1) # pylint: disable=protected-access self.config._chall_out.add(achall2) # pylint: disable=protected-access self.config.cleanup([achall1]) self.assertFalse(mock_restart.called) self.config.cleanup([achall2]) self.assertTrue(mock_restart.called) @mock.patch("letsencrypt_apache.configurator.ApacheConfigurator.restart") def test_cleanup_no_errors(self, mock_restart): _, achall1, achall2 = self.get_achalls() self.config._chall_out.add(achall1) # pylint: disable=protected-access self.config.cleanup([achall2]) self.assertFalse(mock_restart.called) self.config.cleanup([achall1, achall2]) self.assertTrue(mock_restart.called) @mock.patch("letsencrypt.le_util.run_script") def test_get_version(self, mock_script): mock_script.return_value = ( "Server Version: Apache/2.4.2 (Debian)", "") self.assertEqual(self.config.get_version(), (2, 4, 2)) mock_script.return_value = ( "Server Version: Apache/2 (Linux)", "") self.assertEqual(self.config.get_version(), (2,)) mock_script.return_value = ( "Server Version: Apache (Debian)", "") self.assertRaises(errors.PluginError, self.config.get_version) mock_script.return_value = ( "Server Version: Apache/2.3{0} Apache/2.4.7".format( os.linesep), "") self.assertRaises(errors.PluginError, self.config.get_version) mock_script.side_effect = errors.SubprocessError("Can't find program") self.assertRaises(errors.PluginError, self.config.get_version) @mock.patch("letsencrypt_apache.configurator.le_util.run_script") def test_restart(self, _): self.config.restart() @mock.patch("letsencrypt_apache.configurator.le_util.run_script") def test_restart_bad_process(self, mock_run_script): mock_run_script.side_effect = [None, errors.SubprocessError] self.assertRaises(errors.MisconfigurationError, self.config.restart) @mock.patch("letsencrypt.le_util.run_script") def test_config_test(self, _): self.config.config_test() @mock.patch("letsencrypt.le_util.run_script") def test_config_test_bad_process(self, mock_run_script): mock_run_script.side_effect = errors.SubprocessError self.assertRaises(errors.MisconfigurationError, self.config.config_test) def test_get_all_certs_keys(self): c_k = self.config.get_all_certs_keys() self.assertEqual(len(c_k), 2) cert, key, path = next(iter(c_k)) self.assertTrue("cert" in cert) self.assertTrue("key" in key) self.assertTrue("default-ssl" in path) def test_get_all_certs_keys_malformed_conf(self): self.config.parser.find_dir = mock.Mock( side_effect=[["path"], [], ["path"], []]) c_k = self.config.get_all_certs_keys() self.assertFalse(c_k) def test_more_info(self): self.assertTrue(self.config.more_info()) def test_get_chall_pref(self): self.assertTrue(isinstance(self.config.get_chall_pref(""), list)) def test_install_ssl_options_conf(self): from letsencrypt_apache.configurator import install_ssl_options_conf path = os.path.join(self.work_dir, "test_it") install_ssl_options_conf(path) self.assertTrue(os.path.isfile(path)) # TEST ENHANCEMENTS def test_supported_enhancements(self): self.assertTrue(isinstance(self.config.supported_enhancements(), list)) @mock.patch("letsencrypt.le_util.exe_exists") def test_enhance_unknown_vhost(self, mock_exe): self.config.parser.modules.add("rewrite_module") mock_exe.return_value = True ssl_vh = obj.VirtualHost( "fp", "ap", set([obj.Addr(("*", "443")), obj.Addr(("satoshi.com",))]), True, False) self.config.vhosts.append(ssl_vh) self.assertRaises( errors.PluginError, self.config.enhance, "satoshi.com", "redirect") def test_enhance_unknown_enhancement(self): self.assertRaises( errors.PluginError, self.config.enhance, "letsencrypt.demo", "unknown_enhancement") @mock.patch("letsencrypt.le_util.run_script") @mock.patch("letsencrypt.le_util.exe_exists") def test_http_header_hsts(self, mock_exe, _): self.config.parser.update_runtime_variables = mock.Mock() self.config.parser.modules.add("mod_ssl.c") mock_exe.return_value = True # This will create an ssl vhost for letsencrypt.demo self.config.enhance("letsencrypt.demo", "ensure-http-header", "Strict-Transport-Security") self.assertTrue("headers_module" in self.config.parser.modules) # Get the ssl vhost for letsencrypt.demo ssl_vhost = self.config.assoc["letsencrypt.demo"] # These are not immediately available in find_dir even with save() and # load(). They must be found in sites-available hsts_header = self.config.parser.find_dir( "Header", None, ssl_vhost.path) # four args to HSTS header self.assertEqual(len(hsts_header), 4) def test_http_header_hsts_twice(self): self.config.parser.modules.add("mod_ssl.c") # skip the enable mod self.config.parser.modules.add("headers_module") # This will create an ssl vhost for letsencrypt.demo self.config.enhance("encryption-example.demo", "ensure-http-header", "Strict-Transport-Security") self.assertRaises( errors.PluginEnhancementAlreadyPresent, self.config.enhance, "encryption-example.demo", "ensure-http-header", "Strict-Transport-Security") @mock.patch("letsencrypt.le_util.run_script") @mock.patch("letsencrypt.le_util.exe_exists") def test_http_header_uir(self, mock_exe, _): self.config.parser.update_runtime_variables = mock.Mock() self.config.parser.modules.add("mod_ssl.c") mock_exe.return_value = True # This will create an ssl vhost for letsencrypt.demo self.config.enhance("letsencrypt.demo", "ensure-http-header", "Upgrade-Insecure-Requests") self.assertTrue("headers_module" in self.config.parser.modules) # Get the ssl vhost for letsencrypt.demo ssl_vhost = self.config.assoc["letsencrypt.demo"] # These are not immediately available in find_dir even with save() and # load(). They must be found in sites-available uir_header = self.config.parser.find_dir( "Header", None, ssl_vhost.path) # four args to HSTS header self.assertEqual(len(uir_header), 4) def test_http_header_uir_twice(self): self.config.parser.modules.add("mod_ssl.c") # skip the enable mod self.config.parser.modules.add("headers_module") # This will create an ssl vhost for letsencrypt.demo self.config.enhance("encryption-example.demo", "ensure-http-header", "Upgrade-Insecure-Requests") self.assertRaises( errors.PluginEnhancementAlreadyPresent, self.config.enhance, "encryption-example.demo", "ensure-http-header", "Upgrade-Insecure-Requests") @mock.patch("letsencrypt.le_util.run_script") @mock.patch("letsencrypt.le_util.exe_exists") def test_redirect_well_formed_http(self, mock_exe, _): self.config.parser.update_runtime_variables = mock.Mock() mock_exe.return_value = True self.config.get_version = mock.Mock(return_value=(2, 2)) # This will create an ssl vhost for letsencrypt.demo self.config.enhance("letsencrypt.demo", "redirect") # These are not immediately available in find_dir even with save() and # load(). They must be found in sites-available rw_engine = self.config.parser.find_dir( "RewriteEngine", "on", self.vh_truth[3].path) rw_rule = self.config.parser.find_dir( "RewriteRule", None, self.vh_truth[3].path) self.assertEqual(len(rw_engine), 1) # three args to rw_rule self.assertEqual(len(rw_rule), 3) self.assertTrue(rw_engine[0].startswith(self.vh_truth[3].path)) self.assertTrue(rw_rule[0].startswith(self.vh_truth[3].path)) self.assertTrue("rewrite_module" in self.config.parser.modules) def test_rewrite_rule_exists(self): # Skip the enable mod self.config.parser.modules.add("rewrite_module") self.config.get_version = mock.Mock(return_value=(2, 3, 9)) self.config.parser.add_dir( self.vh_truth[3].path, "RewriteRule", ["Unknown"]) # pylint: disable=protected-access self.assertTrue(self.config._is_rewrite_exists(self.vh_truth[3])) def test_rewrite_engine_exists(self): # Skip the enable mod self.config.parser.modules.add("rewrite_module") self.config.get_version = mock.Mock(return_value=(2, 3, 9)) self.config.parser.add_dir( self.vh_truth[3].path, "RewriteEngine", "on") # pylint: disable=protected-access self.assertTrue(self.config._is_rewrite_engine_on(self.vh_truth[3])) @mock.patch("letsencrypt.le_util.run_script") @mock.patch("letsencrypt.le_util.exe_exists") def test_redirect_with_existing_rewrite(self, mock_exe, _): self.config.parser.update_runtime_variables = mock.Mock() mock_exe.return_value = True self.config.get_version = mock.Mock(return_value=(2, 2)) # Create a preexisting rewrite rule self.config.parser.add_dir( self.vh_truth[3].path, "RewriteRule", ["UnknownPattern", "UnknownTarget"]) self.config.save() # This will create an ssl vhost for letsencrypt.demo self.config.enhance("letsencrypt.demo", "redirect") # These are not immediately available in find_dir even with save() and # load(). They must be found in sites-available rw_engine = self.config.parser.find_dir( "RewriteEngine", "on", self.vh_truth[3].path) rw_rule = self.config.parser.find_dir( "RewriteRule", None, self.vh_truth[3].path) self.assertEqual(len(rw_engine), 1) # three args to rw_rule + 1 arg for the pre existing rewrite self.assertEqual(len(rw_rule), 5) self.assertTrue(rw_engine[0].startswith(self.vh_truth[3].path)) self.assertTrue(rw_rule[0].startswith(self.vh_truth[3].path)) self.assertTrue("rewrite_module" in self.config.parser.modules) def test_redirect_with_conflict(self): self.config.parser.modules.add("rewrite_module") ssl_vh = obj.VirtualHost( "fp", "ap", set([obj.Addr(("*", "443")), obj.Addr(("zombo.com",))]), True, False) # No names ^ this guy should conflict. # pylint: disable=protected-access self.assertRaises( errors.PluginError, self.config._enable_redirect, ssl_vh, "") def test_redirect_twice(self): # Skip the enable mod self.config.parser.modules.add("rewrite_module") self.config.get_version = mock.Mock(return_value=(2, 3, 9)) self.config.enhance("encryption-example.demo", "redirect") self.assertRaises( errors.PluginEnhancementAlreadyPresent, self.config.enhance, "encryption-example.demo", "redirect") def test_create_own_redirect(self): self.config.parser.modules.add("rewrite_module") self.config.get_version = mock.Mock(return_value=(2, 3, 9)) # For full testing... give names... self.vh_truth[1].name = "default.com" self.vh_truth[1].aliases = set(["yes.default.com"]) # pylint: disable=protected-access self.config._enable_redirect(self.vh_truth[1], "") self.assertEqual(len(self.config.vhosts), 7) def test_create_own_redirect_for_old_apache_version(self): self.config.parser.modules.add("rewrite_module") self.config.get_version = mock.Mock(return_value=(2, 2)) # For full testing... give names... self.vh_truth[1].name = "default.com" self.vh_truth[1].aliases = set(["yes.default.com"]) # pylint: disable=protected-access self.config._enable_redirect(self.vh_truth[1], "") self.assertEqual(len(self.config.vhosts), 7) def test_sift_line(self): # pylint: disable=protected-access small_quoted_target = "RewriteRule ^ \"http://\"" self.assertFalse(self.config._sift_line(small_quoted_target)) https_target = "RewriteRule ^ https://satoshi" self.assertTrue(self.config._sift_line(https_target)) normal_target = "RewriteRule ^/(.*) http://www.a.com:1234/$1 [L,R]" self.assertFalse(self.config._sift_line(normal_target)) @mock.patch("letsencrypt_apache.configurator.zope.component.getUtility") def test_make_vhost_ssl_with_existing_rewrite_rule(self, mock_get_utility): self.config.parser.modules.add("rewrite_module") http_vhost = self.vh_truth[0] self.config.parser.add_dir( http_vhost.path, "RewriteEngine", "on") self.config.parser.add_dir( http_vhost.path, "RewriteRule", ["^", "https://%{SERVER_NAME}%{REQUEST_URI}", "[L,QSA,R=permanent]"]) self.config.save() ssl_vhost = self.config.make_vhost_ssl(self.vh_truth[0]) self.assertTrue(self.config.parser.find_dir( "RewriteEngine", "on", ssl_vhost.path, False)) conf_text = open(ssl_vhost.filep).read() commented_rewrite_rule = ("# RewriteRule ^ " "https://%{SERVER_NAME}%{REQUEST_URI} " "[L,QSA,R=permanent]") self.assertTrue(commented_rewrite_rule in conf_text) mock_get_utility().add_message.assert_called_once_with(mock.ANY, mock.ANY) def get_achalls(self): """Return testing achallenges.""" account_key = self.rsa512jwk achall1 = achallenges.KeyAuthorizationAnnotatedChallenge( challb=acme_util.chall_to_challb( challenges.TLSSNI01( token="jIq_Xy1mXGN37tb4L6Xj_es58fW571ZNyXekdZzhh7Q"), "pending"), domain="encryption-example.demo", account_key=account_key) achall2 = achallenges.KeyAuthorizationAnnotatedChallenge( challb=acme_util.chall_to_challb( challenges.TLSSNI01( token="uqnaPzxtrndteOqtrXb0Asl5gOJfWAnnx6QJyvcmlDU"), "pending"), domain="letsencrypt.demo", account_key=account_key) return account_key, achall1, achall2 def test_make_addrs_sni_ready(self): self.config.version = (2, 2) self.config.make_addrs_sni_ready( set([obj.Addr.fromstring("*:443"), obj.Addr.fromstring("*:80")])) self.assertTrue(self.config.parser.find_dir( "NameVirtualHost", "*:80", exclude=False)) self.assertTrue(self.config.parser.find_dir( "NameVirtualHost", "*:443", exclude=False)) def test_aug_version(self): mock_match = mock.Mock(return_value=["something"]) self.config.aug.match = mock_match # pylint: disable=protected-access self.assertEquals(self.config._check_aug_version(), ["something"]) self.config.aug.match.side_effect = RuntimeError self.assertFalse(self.config._check_aug_version()) if __name__ == "__main__": unittest.main() # pragma: no cover
#!/usr/bin/env python import logging from dipy.direction import (DeterministicMaximumDirectionGetter, ProbabilisticDirectionGetter, ClosestPeakDirectionGetter) from dipy.io.image import load_nifti from dipy.io.peaks import load_peaks from dipy.io.stateful_tractogram import Space, StatefulTractogram from dipy.io.streamline import save_tractogram from dipy.tracking import utils from dipy.tracking.local_tracking import (LocalTracking, ParticleFilteringTracking) from dipy.tracking.stopping_criterion import (BinaryStoppingCriterion, CmcStoppingCriterion, ThresholdStoppingCriterion) from dipy.workflows.workflow import Workflow class LocalFiberTrackingPAMFlow(Workflow): @classmethod def get_short_name(cls): return 'track_local' def _get_direction_getter(self, strategy_name, pam, pmf_threshold, max_angle): """Get Tracking Direction Getter object. Parameters ---------- strategy_name : str String representing direction getter name. pam : instance of PeaksAndMetrics An object with ``gfa``, ``peak_directions``, ``peak_values``, ``peak_indices``, ``odf``, ``shm_coeffs`` as attributes. pmf_threshold : float Threshold for ODF functions. max_angle : float Maximum angle between streamline segments. Returns ------- direction_getter : instance of DirectionGetter Used to get directions for fiber tracking. """ dg, msg = None, '' if strategy_name.lower() in ["deterministic", "det"]: msg = "Deterministic" dg = DeterministicMaximumDirectionGetter.from_shcoeff( pam.shm_coeff, sphere=pam.sphere, max_angle=max_angle, pmf_threshold=pmf_threshold) elif strategy_name.lower() in ["probabilistic", "prob"]: msg = "Probabilistic" dg = ProbabilisticDirectionGetter.from_shcoeff( pam.shm_coeff, sphere=pam.sphere, max_angle=max_angle, pmf_threshold=pmf_threshold) elif strategy_name.lower() in ["closestpeaks", "cp"]: msg = "ClosestPeaks" dg = ClosestPeakDirectionGetter.from_shcoeff( pam.shm_coeff, sphere=pam.sphere, max_angle=max_angle, pmf_threshold=pmf_threshold) elif strategy_name.lower() in ["eudx", ]: msg = "Eudx" dg = pam else: msg = "No direction getter defined. Eudx" dg = pam logging.info('{0} direction getter strategy selected'.format(msg)) return dg def _core_run(self, stopping_path, use_binary_mask, stopping_thr, seeding_path, seed_density, step_size, direction_getter, out_tract, save_seeds): stop, affine = load_nifti(stopping_path) if use_binary_mask: stopping_criterion = BinaryStoppingCriterion(stop > stopping_thr) else: stopping_criterion = ThresholdStoppingCriterion(stop, stopping_thr) logging.info('stopping criterion done') seed_mask, _ = load_nifti(seeding_path) seeds = \ utils.seeds_from_mask( seed_mask, affine, density=[seed_density, seed_density, seed_density]) logging.info('seeds done') tracking_result = LocalTracking(direction_getter, stopping_criterion, seeds, affine, step_size=step_size, save_seeds=save_seeds) logging.info('LocalTracking initiated') if save_seeds: streamlines, seeds = zip(*tracking_result) seeds = {'seeds': seeds} else: streamlines = list(tracking_result) seeds = {} sft = StatefulTractogram(streamlines, seeding_path, Space.RASMM, data_per_streamline=seeds) save_tractogram(sft, out_tract, bbox_valid_check=False) logging.info('Saved {0}'.format(out_tract)) def run(self, pam_files, stopping_files, seeding_files, use_binary_mask=False, stopping_thr=0.2, seed_density=1, step_size=0.5, tracking_method="eudx", pmf_threshold=0.1, max_angle=30., out_dir='', out_tractogram='tractogram.trk', save_seeds=False): """Workflow for Local Fiber Tracking. This workflow use a saved peaks and metrics (PAM) file as input. Parameters ---------- pam_files : string Path to the peaks and metrics files. This path may contain wildcards to use multiple masks at once. stopping_files : string Path to images (e.g. FA) used for stopping criterion for tracking. seeding_files : string A binary image showing where we need to seed for tracking. use_binary_mask : bool, optional If True, uses a binary stopping criterion. If the provided `stopping_files` are not binary, `stopping_thr` will be used to binarize the images. stopping_thr : float, optional Threshold applied to stopping volume's data to identify where tracking has to stop (default 0.2). seed_density : int, optional Number of seeds per dimension inside voxel (default 1). For example, seed_density of 2 means 8 regularly distributed points in the voxel. And seed density of 1 means 1 point at the center of the voxel. step_size : float, optional Step size used for tracking (default 0.5mm). tracking_method : string, optional Select direction getter strategy : - "eudx" (Uses the peaks saved in the pam_files) - "deterministic" or "det" for a deterministic tracking (Uses the sh saved in the pam_files, default) - "probabilistic" or "prob" for a Probabilistic tracking (Uses the sh saved in the pam_files) - "closestpeaks" or "cp" for a ClosestPeaks tracking (Uses the sh saved in the pam_files) pmf_threshold : float, optional Threshold for ODF functions (default 0.1). max_angle : float, optional Maximum angle between streamline segments (range [0, 90], default 30). out_dir : string, optional Output directory (default input file directory). out_tractogram : string, optional Name of the tractogram file to be saved (default 'tractogram.trk'). save_seeds : bool, optional If true, save the seeds associated to their streamline in the 'data_per_streamline' Tractogram dictionary using 'seeds' as the key. References ---------- Garyfallidis, University of Cambridge, PhD thesis 2012. Amirbekian, University of California San Francisco, PhD thesis 2017. """ io_it = self.get_io_iterator() for pams_path, stopping_path, seeding_path, out_tract in io_it: logging.info('Local tracking on {0}' .format(pams_path)) pam = load_peaks(pams_path, verbose=False) dg = self._get_direction_getter(tracking_method, pam, pmf_threshold=pmf_threshold, max_angle=max_angle) self._core_run(stopping_path, use_binary_mask, stopping_thr, seeding_path, seed_density, step_size, dg, out_tract, save_seeds) class PFTrackingPAMFlow(Workflow): @classmethod def get_short_name(cls): return 'track_pft' def run(self, pam_files, wm_files, gm_files, csf_files, seeding_files, step_size=0.2, seed_density=1, pmf_threshold=0.1, max_angle=20., pft_back=2, pft_front=1, pft_count=15, out_dir='', out_tractogram='tractogram.trk', save_seeds=False): """Workflow for Particle Filtering Tracking. This workflow use a saved peaks and metrics (PAM) file as input. Parameters ---------- pam_files : string Path to the peaks and metrics files. This path may contain wildcards to use multiple masks at once. wm_files : string Path to white matter partial volume estimate for tracking (CMC). gm_files : string Path to grey matter partial volume estimate for tracking (CMC). csf_files : string Path to cerebrospinal fluid partial volume estimate for tracking (CMC). seeding_files : string A binary image showing where we need to seed for tracking. step_size : float, optional Step size used for tracking (default 0.2mm). seed_density : int, optional Number of seeds per dimension inside voxel (default 1). For example, seed_density of 2 means 8 regularly distributed points in the voxel. And seed density of 1 means 1 point at the center of the voxel. pmf_threshold : float, optional Threshold for ODF functions (default 0.1). max_angle : float, optional Maximum angle between streamline segments (range [0, 90], default 20). pft_back : float, optional Distance in mm to back track before starting the particle filtering tractography (default 2mm). The total particle filtering tractography distance is equal to back_tracking_dist + front_tracking_dist. pft_front : float, optional Distance in mm to run the particle filtering tractography after the the back track distance (default 1mm). The total particle filtering tractography distance is equal to back_tracking_dist + front_tracking_dist. pft_count : int, optional Number of particles to use in the particle filter (default 15). out_dir : string, optional Output directory (default input file directory) out_tractogram : string, optional Name of the tractogram file to be saved (default 'tractogram.trk') save_seeds : bool, optional If true, save the seeds associated to their streamline in the 'data_per_streamline' Tractogram dictionary using 'seeds' as the key References ---------- Girard, G., Whittingstall, K., Deriche, R., & Descoteaux, M. Towards quantitative connectivity analysis: reducing tractography biases. NeuroImage, 98, 266-278, 2014. """ io_it = self.get_io_iterator() for pams_path, wm_path, gm_path, csf_path, seeding_path, out_tract \ in io_it: logging.info('Particle Filtering tracking on {0}' .format(pams_path)) pam = load_peaks(pams_path, verbose=False) wm, affine, voxel_size = load_nifti(wm_path, return_voxsize=True) gm, _ = load_nifti(gm_path) csf, _ = load_nifti(csf_path) avs = sum(voxel_size) / len(voxel_size) # average_voxel_size stopping_criterion = CmcStoppingCriterion.from_pve( wm, gm, csf, step_size=step_size, average_voxel_size=avs) logging.info('stopping criterion done') seed_mask, _ = load_nifti(seeding_path) seeds = utils.seeds_from_mask(seed_mask, affine, density=[seed_density, seed_density, seed_density]) logging.info('seeds done') dg = ProbabilisticDirectionGetter direction_getter = dg.from_shcoeff(pam.shm_coeff, max_angle=max_angle, sphere=pam.sphere, pmf_threshold=pmf_threshold) tracking_result = ParticleFilteringTracking( direction_getter, stopping_criterion, seeds, affine, step_size=step_size, pft_back_tracking_dist=pft_back, pft_front_tracking_dist=pft_front, pft_max_trial=20, particle_count=pft_count, save_seeds=save_seeds) logging.info('ParticleFilteringTracking initiated') if save_seeds: streamlines, seeds = zip(*tracking_result) seeds = {'seeds': seeds} else: streamlines = list(tracking_result) seeds = {} sft = StatefulTractogram(streamlines, seeding_path, Space.RASMM, data_per_streamline=seeds) save_tractogram(sft, out_tract, bbox_valid_check=False) logging.info('Saved {0}'.format(out_tract))
from rllab.mujoco_py import glfw, mjcore import rllab.mujoco_py.mjconstants as C from rllab.mujoco_py.mjlib import mjlib from ctypes import byref import ctypes from threading import Lock mjCAT_ALL = 7 class EmbeddedViewer(object): def __init__(self): self.last_render_time = 0 self.objects = mjcore.MJVOBJECTS() self.cam = mjcore.MJVCAMERA() self.vopt = mjcore.MJVOPTION() self.ropt = mjcore.MJROPTION() self.con = mjcore.MJRCONTEXT() self.running = False self.speedtype = 1 self.window = None self.model = None self.gui_lock = Lock() self.last_button = 0 self.last_click_time = 0 self.button_left_pressed = False self.button_middle_pressed = False self.button_right_pressed = False self.last_mouse_x = 0 self.last_mouse_y = 0 self.frames = [] def set_model(self, model): self.model = model if model: self.data = model.data else: self.data = None if self.running: if model: mjlib.mjr_makeContext(model.ptr, byref(self.con), 150) else: mjlib.mjr_makeContext(None, byref(self.con), 150) self.render() if model: self.autoscale() def autoscale(self): self.cam.lookat[0] = self.model.stat.center[0] self.cam.lookat[1] = self.model.stat.center[1] self.cam.lookat[2] = self.model.stat.center[2] self.cam.distance = 1.0 * self.model.stat.extent self.cam.camid = -1 self.cam.trackbodyid = -1 if self.window: width, height = glfw.get_framebuffer_size(self.window) mjlib.mjv_updateCameraPose(byref(self.cam), width * 1.0 / height) def get_rect(self): rect = mjcore.MJRRECT(0, 0, 0, 0) rect.width, rect.height = glfw.get_framebuffer_size(self.window) return rect def record_frame(self, **kwargs): self.frames.append({'pos': self.model.data.qpos, 'extra': kwargs}) def clear_frames(self): self.frames = [] def render(self): rect = self.get_rect() arr = (ctypes.c_double * 3)(0, 0, 0) mjlib.mjv_makeGeoms( self.model.ptr, self.data.ptr, byref(self.objects), byref(self.vopt), mjCAT_ALL, 0, None, None, ctypes.cast(arr, ctypes.POINTER(ctypes.c_double))) mjlib.mjv_setCamera(self.model.ptr, self.data.ptr, byref(self.cam)) mjlib.mjv_updateCameraPose( byref(self.cam), rect.width * 1.0 / rect.height) mjlib.mjr_render(0, rect, byref(self.objects), byref( self.ropt), byref(self.cam.pose), byref(self.con)) def render_internal(self): if not self.data: return self.gui_lock.acquire() self.render() self.gui_lock.release() def start(self, window): self.running = True width, height = glfw.get_framebuffer_size(window) width1, height = glfw.get_window_size(window) self.scale = width * 1.0 / width1 self.window = window mjlib.mjv_makeObjects(byref(self.objects), 1000) mjlib.mjv_defaultCamera(byref(self.cam)) mjlib.mjv_defaultOption(byref(self.vopt)) mjlib.mjr_defaultOption(byref(self.ropt)) mjlib.mjr_defaultContext(byref(self.con)) if self.model: mjlib.mjr_makeContext(self.model.ptr, byref(self.con), 150) self.autoscale() else: mjlib.mjr_makeContext(None, byref(self.con), 150) def handle_mouse_move(self, window, xpos, ypos): # no buttons down: nothing to do if not self.button_left_pressed \ and not self.button_middle_pressed \ and not self.button_right_pressed: return # compute mouse displacement, save dx = int(self.scale * xpos) - self.last_mouse_x dy = int(self.scale * ypos) - self.last_mouse_y self.last_mouse_x = int(self.scale * xpos) self.last_mouse_y = int(self.scale * ypos) # require model if not self.model: return # get current window size width, height = glfw.get_framebuffer_size(self.window) # get shift key state mod_shift = glfw.get_key(window, glfw.KEY_LEFT_SHIFT) == glfw.PRESS \ or glfw.get_key(window, glfw.KEY_RIGHT_SHIFT) == glfw.PRESS # determine action based on mouse button action = None if self.button_right_pressed: action = C.MOUSE_MOVE_H if mod_shift else C.MOUSE_MOVE_V elif self.button_left_pressed: action = C.MOUSE_ROTATE_H if mod_shift else C.MOUSE_ROTATE_V else: action = C.MOUSE_ZOOM self.gui_lock.acquire() mjlib.mjv_moveCamera(action, dx, dy, byref(self.cam), width, height) self.gui_lock.release() def handle_mouse_button(self, window, button, act, mods): # update button state self.button_left_pressed = \ glfw.get_mouse_button(window, glfw.MOUSE_BUTTON_LEFT) == glfw.PRESS self.button_middle_pressed = \ glfw.get_mouse_button( window, glfw.MOUSE_BUTTON_MIDDLE) == glfw.PRESS self.button_right_pressed = \ glfw.get_mouse_button( window, glfw.MOUSE_BUTTON_RIGHT) == glfw.PRESS # update mouse position x, y = glfw.get_cursor_pos(window) self.last_mouse_x = int(self.scale * x) self.last_mouse_y = int(self.scale * y) if not self.model: return self.gui_lock.acquire() # save info if act == glfw.PRESS: self.last_button = button self.last_click_time = glfw.get_time() self.gui_lock.release() def handle_scroll(self, window, x_offset, y_offset): # require model if not self.model: return # get current window size width, height = glfw.get_framebuffer_size(window) # scroll self.gui_lock.acquire() mjlib.mjv_moveCamera(C.MOUSE_ZOOM, 0, (-20 * y_offset), byref(self.cam), width, height) self.gui_lock.release() def should_stop(self): return glfw.window_should_close(self.window) def loop_once(self): self.render() # Swap front and back buffers glfw.swap_buffers(self.window) # Poll for and process events glfw.poll_events() def finish(self): glfw.terminate() mjlib.mjr_freeContext(byref(self.con)) mjlib.mjv_freeObjects(byref(self.objects)) self.running = False
from datetime import timedelta from django.utils import timezone from bulbs.content.models import Content, FeatureType, Tag from bulbs.special_coverage.models import SpecialCoverage from example.testcontent.models import TestContentObjTwo from bulbs.utils.test import BaseIndexableTestCase, make_content class BaseCustomSearchFilterTests(BaseIndexableTestCase): """Base test case that sets up some data.""" def setUp(self): super(BaseCustomSearchFilterTests, self).setUp() feature_type_names = ( "News", "Slideshow", "TV Club", "Video", ) feature_types = [] for name in feature_type_names: feature_types.append(FeatureType.objects.create(name=name)) tag_names = ( "Barack Obama", "Joe Biden", "Wow", "Funny", "Politics" ) tags = [] for name in tag_names: tags.append(Tag.objects.create(name=name)) content_data = ( dict( title="Obama Does It Again", feature_type=0, tags=[0, 2, 4] ), dict( title="Biden Does It Again", feature_type=0, tags=[1, 2, 4] ), dict( title="Obama In Slides Is Flawless", feature_type=1, tags=[0, 2, 4] ), dict( title="Obama On TV", feature_type=2, tags=[0, 2] ), dict( title="Flawless video here", feature_type=3, tags=[3, 2] ), dict( title="Both Obama and Biden in One Article", feature_type=3, tags=[0, 1, 2] ), ) time_step = timedelta(hours=12) pubtime = timezone.now() + time_step content_list = [] for data in content_data: data["published"] = pubtime data["feature_type"] = feature_types[data.pop("feature_type")] data["tags"] = [tags[tag_idx] for tag_idx in data.pop("tags")] content = make_content(**data) content_list.append(content) content.index() # reindex for related object updates pubtime -= time_step self.content_list = content_list self.feature_types = feature_types self.tags = tags Content.search_objects.refresh() # NOTE: we updated some field names after I initially typed this up. # NOTE: These functions munge the existing data into the new form. def makeGroups(groups): result = [] for group in groups: if isinstance(group, dict): this_group = group else: this_group = dict(conditions=[]) for condition in group: this_group["conditions"].append(makeCondition(*condition)) result.append(this_group) return result def makeCondition(field, type, values): return dict( field=field, type=type, values=[dict(label=v, value=v) for v in values] ) s_biden = dict( label="All Biden, Baby", query=dict( groups=makeGroups([ [ ("tag", "all", [self.tags[1].slug]), ], ]) ) ) s_obama = dict( label="All Obama, Baby", query=dict( groups=makeGroups([ [ ("tag", "all", [self.tags[0].slug]), ], ]) ) ) # logical and s_b_and_b = dict( label="Obama and Biden, together!", query=dict( groups=makeGroups([ [ ("tag", "all", [ self.tags[0].slug, self.tags[1].slug ]), ], ]) ) ) # logical or s_b_or_b = dict( label="Obama or Biden, whatever!", query=dict( groups=makeGroups([ [ ("tag", "any", [ self.tags[0].slug, self.tags[1].slug ]), ], ]) ) ) # excluding some tags s_lite_obama = dict( label="Obama but not political stuff", query=dict( groups=makeGroups([ [ ("tag", "all", [ self.tags[0].slug, # obama ]), ("tag", "none", [ self.tags[4].slug, # politics ]), ], ]) ) ) # multiple, disjoint groups s_funny_and_slideshows = dict( label="Anything funny and also slideshows!", query=dict( groups=makeGroups([ [ ("tag", "any", [ self.tags[3].slug # funny tags ]), ], [ ("feature-type", "any", [ self.feature_types[1].slug # slideshow ]), ], ]) ) ) # this tag is on everything s_wow = dict( label="Wow!", query=dict( groups=makeGroups([ [ ("tag", "all", [ self.tags[2].slug # funny tags ]), ], ]) ) ) # filter by content type s_doctype = dict( label="Doctype", query=dict( groups=makeGroups([ [ ("content-type", "all", [ TestContentObjTwo.search_objects.mapping.doc_type ]) ] ]) ) ) # include some ids s_one_article = dict( label="Just this article", query=dict( groups=[], included_ids=[self.content_list[0].id] ) ) s_two_articles = dict( label="Just two articles", query=dict( groups=[], included_ids=[ self.content_list[0].id, self.content_list[3].id ] ) ) # exclude ids s_all_but_one_article = dict( label="All but one article", query=dict( groups=[], excluded_ids=[ self.content_list[0].id ] ) ) # last day of articles s_last_day = dict( label="Last day", query=dict( groups=[dict( conditions=[], time="1 day" )], ) ) # pinned s_pinned = dict( label="Pinned something", query=dict( pinned_ids=[ content_list[-1].id # last in time ] ) ) # pinned 2 s_pinned_2 = dict( label="Pinned 2 things", query=dict( pinned_ids=[ content_list[-1].id, # last in time content_list[-2].id # penultimate ] ) ) # pinned 2 with groups s_pinned_2_groups = dict( label="Pinned 2 things with other filters", query=dict( groups=makeGroups([ [ ("tag", "any", [ self.tags[0].slug, self.tags[1].slug, self.tags[2].slug, self.tags[3].slug, self.tags[4].slug ]), ] ]), pinned_ids=[ content_list[-1].id, # last in time content_list[-2].id # penultimate ] ) ) # text query s_text_query = dict( label="Text query", query=dict( query="again" ) ) # text query with pinned ids s_text_query_pinned = dict( label="Text query", query=dict( groups=makeGroups([ [ ("tag", "any", [self.tags[2].slug]), ] ]), pinned_ids=[self.content_list[4].id], query="Flawless" ) ) # saved search and the expected result count self.search_expectations = ( (s_biden, 2), (s_obama, 4), (s_b_and_b, 1), (s_b_or_b, 5), (s_lite_obama, 2), (s_funny_and_slideshows, 2), (s_wow, len(self.content_list)), (s_one_article, 1), (s_two_articles, 2), (s_all_but_one_article, len(self.content_list) - 1), (s_last_day, 3), (s_pinned, len(self.content_list)), (s_pinned_2, len(self.content_list)), (s_pinned_2_groups, len(self.content_list)), (s_doctype, TestContentObjTwo.objects.count()), (s_text_query, 2), (s_text_query_pinned, 2), ) self.preview_expectations = ( (s_biden, 2), (s_obama, 4), (s_b_and_b, 1), (s_b_or_b, 5), (s_lite_obama, 2), (s_funny_and_slideshows, 2), (s_wow, len(self.content_list)), (s_one_article, 1), (s_two_articles, 2), (s_all_but_one_article, len(self.content_list)), # excluded (s_last_day, 3), (s_doctype, TestContentObjTwo.objects.count()), (s_text_query, 2), (s_text_query_pinned, 2), ) self.group_preview_expectations = ( (s_biden, 2), (s_obama, 4), (s_b_and_b, 1), (s_wow, len(self.content_list)), (s_one_article, 1), (s_two_articles, 2), (s_all_but_one_article, len(self.content_list)), # excluded ) # is not published and not is_preview self.unpublished_expectations = ( (s_biden, 2), (s_obama, 4), (s_b_and_b, 1), (s_b_or_b, 5), (s_lite_obama, 2), (s_funny_and_slideshows, 2), (s_wow, len(self.content_list)), (s_one_article, 1), (s_two_articles, 2), (s_all_but_one_article, len(self.content_list) - 1), (s_last_day, 3), (s_pinned, len(self.content_list)), (s_pinned_2, len(self.content_list)), (s_pinned_2_groups, len(self.content_list)), (s_text_query, 2), (s_text_query_pinned, 2), ) # is published and not is_preview self.published_expectations = ( (s_biden, 2), (s_obama, 3), (s_b_and_b, 1), (s_b_or_b, 5 - 1), (s_lite_obama, 2), (s_funny_and_slideshows, 2), (s_wow, len(self.content_list) - 1), (s_one_article, 1 - 1), (s_two_articles, 2 - 1), (s_all_but_one_article, len(self.content_list) - 1), (s_last_day, 2), (s_pinned, len(self.content_list) - 1), (s_pinned_2, len(self.content_list) - 1), (s_pinned_2_groups, len(self.content_list) - 1), (s_text_query, 1), (s_text_query_pinned, 2), ) self.published_not_pinned_expectations = ( (s_biden, 2), (s_obama, 3), (s_b_and_b, 1), (s_b_or_b, 5 - 1), (s_lite_obama, 2), (s_funny_and_slideshows, 2), (s_wow, len(self.content_list) - 1), (s_one_article, 1 - 1), (s_two_articles, 2 - 1), (s_all_but_one_article, len(self.content_list) - 1), (s_last_day, 2), ) # (search filter, (list, of, ids, in, order)), self.ordered_expectations = ( (s_all_but_one_article, (2, 3, 4)), (s_text_query_pinned, (content_list[4].id, content_list[2].id)), ) self.pinned_expectations = ( (s_pinned, ( content_list[-1].id, content_list[0].id, content_list[1].id, )), (s_pinned_2, ( content_list[-2].id, content_list[-1].id, content_list[0].id, content_list[1].id, )), (s_pinned_2_groups, ( content_list[-2].id, content_list[-1].id, content_list[0].id, content_list[1].id, )), ) class SpecialCoverageQueryTests(BaseCustomSearchFilterTests): def setUp(self): super(SpecialCoverageQueryTests, self).setUp() def test_get_content(self): """tests the search results are instances of Content""" query = self.search_expectations[1][0] sc = SpecialCoverage.objects.create( name="All Obama, Baby", description="All Obama, Baby", query=query ) res = sc.get_content() for content in res: self.assertIsInstance(content, Content) def test_has_pinned_content(self): """tests that the .has_pinned_content accurately returns True or False""" query = self.search_expectations[0][0] sc = SpecialCoverage.objects.create( name="All Biden, Baby", description="All Biden, Baby", query=query ) self.assertTrue(hasattr(sc, "has_pinned_content")) self.assertFalse(sc.has_pinned_content) query = self.search_expectations[-1][0] sc = SpecialCoverage.objects.create( name="Text query", description="Text query", query=query ) self.assertTrue(hasattr(sc, "has_pinned_content")) self.assertTrue(sc.has_pinned_content) def test_contents(self): """tests that the .contents accurately returns Content objects""" query = self.search_expectations[2][0] sc = SpecialCoverage.objects.create( name="Obama and Biden, together", description="Obama and Biden, together", query=query ) self.assertTrue(hasattr(sc, "contents")) for content in sc.contents: self.assertIsInstance(content, Content)
######### # Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # * See the License for the specific language governing permissions and # * limitations under the License. import time from cloudify import utils from cloudify import amqp_client from cloudify import constants from cloudify.celery import celery as celery_client from cloudify.decorators import operation from cloudify.exceptions import NonRecoverableError from windows_agent_installer import constants as win_constants from windows_agent_installer import init_worker_installer from windows_agent_installer import constants as win_const # This is the folder under which the agent is # extracted to inside the current directory. # It is set in the packaging process so it # must be hardcoded here. AGENT_FOLDER_NAME = 'CloudifyAgent' # This is where we download the agent to. AGENT_EXEC_FILE_NAME = 'CloudifyAgent.exe' # nssm will install celery and use this name to identify the service AGENT_SERVICE_NAME = 'CloudifyAgent' # location of the agent package on the management machine, # relative to the file server root. AGENT_PACKAGE_PATH = 'packages/agents/CloudifyWindowsAgent.exe' # Path to the agent. We are using global (not user based) paths # because of virtualenv relocation issues on windows. RUNTIME_AGENT_PATH = 'C:\CloudifyAgent' # Agent includes list, Mandatory AGENT_INCLUDES = 'script_runner.tasks,windows_plugin_installer.tasks,'\ 'cloudify.plugins.workflows' def get_agent_package_url(): return '{0}/{1}'.format(utils.get_manager_file_server_url(), AGENT_PACKAGE_PATH) def create_env_string(cloudify_agent): env = { constants.CELERY_WORK_DIR_PATH_KEY: RUNTIME_AGENT_PATH, constants.LOCAL_IP_KEY: cloudify_agent['host'], constants.MANAGER_IP_KEY: utils.get_manager_ip(), constants.MANAGER_FILE_SERVER_BLUEPRINTS_ROOT_URL_KEY: utils.get_manager_file_server_blueprints_root_url(), constants.MANAGER_FILE_SERVER_URL_KEY: utils.get_manager_file_server_url(), constants.MANAGER_REST_PORT_KEY: utils.get_manager_rest_service_port() } env_string = '' for key, value in env.iteritems(): env_string = '{0} {1}={2}' \ .format(env_string, key, value) return env_string.strip() @operation @init_worker_installer def install(ctx, runner=None, cloudify_agent=None, **kwargs): """ Installs the cloudify agent service on the machine. The agent installation consists of the following: 1. Download and extract necessary files. 2. Configure the agent service to auto start on vm launch. 3. Configure the agent service to restart on failure. :param ctx: Invocation context - injected by the @operation :param runner: Injected by the @init_worker_installer :param cloudify_agent: Injected by the @init_worker_installer """ if cloudify_agent.get('delete_amqp_queues'): _delete_amqp_queues(cloudify_agent['name']) ctx.logger.info('Installing agent {0}'.format(cloudify_agent['name'])) agent_exec_path = 'C:\{0}'.format(AGENT_EXEC_FILE_NAME) runner.download(get_agent_package_url(), agent_exec_path) ctx.logger.debug('Extracting agent to C:\\ ...') runner.run('{0} -o{1} -y'.format(agent_exec_path, RUNTIME_AGENT_PATH), quiet=True) params = ('--broker=amqp://guest:guest@{0}:5672// ' '-Ofair ' '--events ' '--app=cloudify ' '-Q {1} ' '--hostname={1} ' '--logfile={2}\celery.log ' '--pidfile={2}\celery.pid ' '--autoscale={3},{4} ' '--include={5} ' '--without-gossip ' '--without-mingle ' .format(utils.get_manager_ip(), cloudify_agent['name'], RUNTIME_AGENT_PATH, cloudify_agent[win_constants.MIN_WORKERS_KEY], cloudify_agent[win_constants.MAX_WORKERS_KEY], AGENT_INCLUDES)) runner.run('{0}\\nssm\\nssm.exe install {1} {0}\Scripts\celeryd.exe {2}' .format(RUNTIME_AGENT_PATH, AGENT_SERVICE_NAME, params)) env = create_env_string(cloudify_agent) runner.run('{0}\\nssm\\nssm.exe set {1} AppEnvironmentExtra {2}' .format(RUNTIME_AGENT_PATH, AGENT_SERVICE_NAME, env)) runner.run('sc config {0} start= auto'.format(AGENT_SERVICE_NAME)) runner.run( 'sc failure {0} reset= {1} actions= restart/{2}'.format( AGENT_SERVICE_NAME, cloudify_agent['service'][ win_const.SERVICE_FAILURE_RESET_TIMEOUT_KEY ], cloudify_agent['service'][ win_const.SERVICE_FAILURE_RESTART_DELAY_KEY ])) ctx.logger.info('Creating parameters file from {0}'.format(params)) runner.put(params, '{0}\AppParameters'.format(RUNTIME_AGENT_PATH)) @operation @init_worker_installer def start(ctx, runner=None, cloudify_agent=None, **kwargs): """ Starts the cloudify agent service on the machine. :param ctx: Invocation context - injected by the @operation :param runner: Injected by the @init_worker_installer :param cloudify_agent: Injected by the @init_worker_installer """ _start(cloudify_agent, ctx, runner) @operation @init_worker_installer def stop(ctx, runner=None, cloudify_agent=None, **kwargs): """ Stops the cloudify agent service on the machine. :param ctx: Invocation context - injected by the @operation :param runner: Injected by the @init_worker_installer :param cloudify_agent: Injected by the @init_worker_installer """ _stop(cloudify_agent, ctx, runner) @operation @init_worker_installer def restart(ctx, runner=None, cloudify_agent=None, **kwargs): """ Restarts the cloudify agent service on the machine. 1. Stop the service. 2. Start the service. :param ctx: Invocation context - injected by the @operation :param runner: Injected by the @init_worker_installer :param cloudify_agent: Injected by the @init_worker_installer """ ctx.logger.info('Restarting agent {0}'.format(cloudify_agent['name'])) _stop(ctx=ctx, runner=runner, cloudify_agent=cloudify_agent) _start(ctx=ctx, runner=runner, cloudify_agent=cloudify_agent) @operation @init_worker_installer def uninstall(ctx, runner=None, cloudify_agent=None, **kwargs): """ Uninstalls the cloudify agent service from the machine. 1. Remove the service from the registry. 2. Delete related files.. :param ctx: Invocation context - injected by the @operation :param runner: Injected by the @init_worker_installer :param cloudify_agent: Injected by the @init_worker_installer """ ctx.logger.info('Uninstalling agent {0}'.format(cloudify_agent['name'])) runner.run('{0} remove {1} confirm'.format('{0}\\nssm\\nssm.exe' .format(RUNTIME_AGENT_PATH), AGENT_SERVICE_NAME)) runner.delete(path=RUNTIME_AGENT_PATH) runner.delete(path='C:\\{0}'.format(AGENT_EXEC_FILE_NAME)) def _delete_amqp_queues(worker_name): # FIXME: this function deletes amqp queues that will be used by worker. # The amqp queues used by celery worker are determined by worker name # and if there are multiple workers with same name celery gets confused. # # Currently the worker name is based solely on hostname, so it will be # re-used if vm gets re-created by auto-heal. # Deleting the queues is a workaround for celery problems this creates. # Having unique worker names is probably a better long-term strategy. client = amqp_client.create_client() try: channel = client.connection.channel() # celery worker queue channel.queue_delete(worker_name) # celery management queue channel.queue_delete('celery@{0}.celery.pidbox'.format(worker_name)) finally: try: client.close() except Exception: pass def _verify_no_celery_error(runner): # don't use os.path.join here since # since the manager is linux # and the agent is windows celery_error_out = '{0}\{1}'.format(RUNTIME_AGENT_PATH, win_constants.CELERY_ERROR_FILE) # this means the celery worker had an uncaught # exception and it wrote its content # to the file above because of our custom # exception handler (see celery.py) if runner.exists(celery_error_out): output = runner.get(celery_error_out) runner.delete(path=celery_error_out) raise NonRecoverableError(output) def _wait_for_started(runner, cloudify_agent): _verify_no_celery_error(runner) worker_name = 'celery@{0}'.format(cloudify_agent['name']) wait_started_timeout = cloudify_agent[ win_constants.AGENT_START_TIMEOUT_KEY ] timeout = time.time() + wait_started_timeout interval = cloudify_agent[win_constants.AGENT_START_INTERVAL_KEY] while time.time() < timeout: stats = get_worker_stats(worker_name) if stats: return time.sleep(interval) _verify_no_celery_error(runner) raise NonRecoverableError('Failed starting agent. waited for {0} seconds.' .format(wait_started_timeout)) def _wait_for_stopped(runner, cloudify_agent): _verify_no_celery_error(runner) worker_name = 'celery@{0}'.format(cloudify_agent['name']) wait_started_timeout = cloudify_agent[ win_constants.AGENT_STOP_TIMEOUT_KEY ] timeout = time.time() + wait_started_timeout interval = cloudify_agent[win_constants.AGENT_STOP_INTERVAL_KEY] while time.time() < timeout: stats = get_worker_stats(worker_name) if not stats: return time.sleep(interval) _verify_no_celery_error(runner) raise NonRecoverableError('Failed stopping agent. waited for {0} seconds.' .format(wait_started_timeout)) def get_worker_stats(worker_name): inspect = celery_client.control.inspect(destination=[worker_name]) stats = (inspect.stats() or {}).get(worker_name) return stats def _stop(cloudify_agent, ctx, runner): ctx.logger.info('Stopping agent {0}'.format(cloudify_agent['name'])) runner.run('sc stop {}'.format(AGENT_SERVICE_NAME)) _wait_for_stopped(runner, cloudify_agent) runner.delete('{0}\celery.pid'.format(RUNTIME_AGENT_PATH), ignore_missing=True) def _start(cloudify_agent, ctx, runner): ctx.logger.info('Starting agent {0}'.format(cloudify_agent['name'])) runner.run('sc start {}'.format(AGENT_SERVICE_NAME)) ctx.logger.info('Waiting for {0} to start...'.format(AGENT_SERVICE_NAME)) _wait_for_started(runner, cloudify_agent)
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: release-1.23 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from kubernetes.client.configuration import Configuration class V2beta1MetricSpec(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'container_resource': 'V2beta1ContainerResourceMetricSource', 'external': 'V2beta1ExternalMetricSource', 'object': 'V2beta1ObjectMetricSource', 'pods': 'V2beta1PodsMetricSource', 'resource': 'V2beta1ResourceMetricSource', 'type': 'str' } attribute_map = { 'container_resource': 'containerResource', 'external': 'external', 'object': 'object', 'pods': 'pods', 'resource': 'resource', 'type': 'type' } def __init__(self, container_resource=None, external=None, object=None, pods=None, resource=None, type=None, local_vars_configuration=None): # noqa: E501 """V2beta1MetricSpec - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._container_resource = None self._external = None self._object = None self._pods = None self._resource = None self._type = None self.discriminator = None if container_resource is not None: self.container_resource = container_resource if external is not None: self.external = external if object is not None: self.object = object if pods is not None: self.pods = pods if resource is not None: self.resource = resource self.type = type @property def container_resource(self): """Gets the container_resource of this V2beta1MetricSpec. # noqa: E501 :return: The container_resource of this V2beta1MetricSpec. # noqa: E501 :rtype: V2beta1ContainerResourceMetricSource """ return self._container_resource @container_resource.setter def container_resource(self, container_resource): """Sets the container_resource of this V2beta1MetricSpec. :param container_resource: The container_resource of this V2beta1MetricSpec. # noqa: E501 :type: V2beta1ContainerResourceMetricSource """ self._container_resource = container_resource @property def external(self): """Gets the external of this V2beta1MetricSpec. # noqa: E501 :return: The external of this V2beta1MetricSpec. # noqa: E501 :rtype: V2beta1ExternalMetricSource """ return self._external @external.setter def external(self, external): """Sets the external of this V2beta1MetricSpec. :param external: The external of this V2beta1MetricSpec. # noqa: E501 :type: V2beta1ExternalMetricSource """ self._external = external @property def object(self): """Gets the object of this V2beta1MetricSpec. # noqa: E501 :return: The object of this V2beta1MetricSpec. # noqa: E501 :rtype: V2beta1ObjectMetricSource """ return self._object @object.setter def object(self, object): """Sets the object of this V2beta1MetricSpec. :param object: The object of this V2beta1MetricSpec. # noqa: E501 :type: V2beta1ObjectMetricSource """ self._object = object @property def pods(self): """Gets the pods of this V2beta1MetricSpec. # noqa: E501 :return: The pods of this V2beta1MetricSpec. # noqa: E501 :rtype: V2beta1PodsMetricSource """ return self._pods @pods.setter def pods(self, pods): """Sets the pods of this V2beta1MetricSpec. :param pods: The pods of this V2beta1MetricSpec. # noqa: E501 :type: V2beta1PodsMetricSource """ self._pods = pods @property def resource(self): """Gets the resource of this V2beta1MetricSpec. # noqa: E501 :return: The resource of this V2beta1MetricSpec. # noqa: E501 :rtype: V2beta1ResourceMetricSource """ return self._resource @resource.setter def resource(self, resource): """Sets the resource of this V2beta1MetricSpec. :param resource: The resource of this V2beta1MetricSpec. # noqa: E501 :type: V2beta1ResourceMetricSource """ self._resource = resource @property def type(self): """Gets the type of this V2beta1MetricSpec. # noqa: E501 type is the type of metric source. It should be one of \"ContainerResource\", \"External\", \"Object\", \"Pods\" or \"Resource\", each mapping to a matching field in the object. Note: \"ContainerResource\" type is available on when the feature-gate HPAContainerMetrics is enabled # noqa: E501 :return: The type of this V2beta1MetricSpec. # noqa: E501 :rtype: str """ return self._type @type.setter def type(self, type): """Sets the type of this V2beta1MetricSpec. type is the type of metric source. It should be one of \"ContainerResource\", \"External\", \"Object\", \"Pods\" or \"Resource\", each mapping to a matching field in the object. Note: \"ContainerResource\" type is available on when the feature-gate HPAContainerMetrics is enabled # noqa: E501 :param type: The type of this V2beta1MetricSpec. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and type is None: # noqa: E501 raise ValueError("Invalid value for `type`, must not be `None`") # noqa: E501 self._type = type def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V2beta1MetricSpec): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V2beta1MetricSpec): return True return self.to_dict() != other.to_dict()
# Copyright 2017 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. # ============================================================================== """Tests for activity module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gast from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import parser from tensorflow.python.autograph.pyct import qual_names from tensorflow.python.autograph.pyct import transformer from tensorflow.python.autograph.pyct.qual_names import QN from tensorflow.python.autograph.pyct.static_analysis import activity from tensorflow.python.autograph.pyct.static_analysis.annos import NodeAnno from tensorflow.python.platform import test class ScopeTest(test.TestCase): def assertMissing(self, qn, scope): self.assertNotIn(qn, scope.read) self.assertNotIn(qn, scope.modified) def assertReadOnly(self, qn, scope): self.assertIn(qn, scope.read) self.assertNotIn(qn, scope.modified) def assertWriteOnly(self, qn, scope): self.assertNotIn(qn, scope.read) self.assertIn(qn, scope.modified) def assertReadWrite(self, qn, scope): self.assertIn(qn, scope.read) self.assertIn(qn, scope.modified) def test_basic(self): scope = activity.Scope(None) self.assertMissing(QN('foo'), scope) scope.mark_read(QN('foo')) self.assertReadOnly(QN('foo'), scope) scope.mark_modified(QN('foo')) self.assertReadWrite(QN('foo'), scope) def test_copy_from(self): scope = activity.Scope(None) scope.mark_modified(QN('foo')) other = activity.Scope(None) other.copy_from(scope) self.assertWriteOnly(QN('foo'), other) scope.mark_modified(QN('bar')) scope.copy_from(other) self.assertMissing(QN('bar'), scope) scope.mark_modified(QN('bar')) scope.merge_from(other) self.assertWriteOnly(QN('bar'), scope) self.assertMissing(QN('bar'), other) def test_copy_of(self): scope = activity.Scope(None) scope.mark_read(QN('foo')) other = activity.Scope.copy_of(scope) self.assertReadOnly(QN('foo'), other) child_scope = activity.Scope(scope) child_scope.mark_read(QN('bar')) other = activity.Scope.copy_of(child_scope) self.assertReadOnly(QN('bar'), other) def test_referenced(self): scope = activity.Scope(None) scope.mark_read(QN('a')) child = activity.Scope(scope) child.mark_read(QN('b')) child2 = activity.Scope(child, isolated=False) child2.mark_read(QN('c')) self.assertTrue(QN('c') in child2.referenced) self.assertTrue(QN('b') in child2.referenced) self.assertFalse(QN('a') in child2.referenced) self.assertTrue(QN('c') in child.referenced) self.assertTrue(QN('b') in child.referenced) self.assertFalse(QN('a') in child.referenced) class ActivityAnalyzerTest(test.TestCase): def _parse_and_analyze(self, test_fn): node, source = parser.parse_entity(test_fn, future_features=()) entity_info = transformer.EntityInfo( source_code=source, source_file=None, future_features=(), namespace={}) node = qual_names.resolve(node) ctx = transformer.Context(entity_info) node = activity.resolve(node, ctx) return node, entity_info def assertSymbolSetsAre(self, expected, actual, name): expected = set(expected) actual = set(str(s) for s in actual) self.assertSetEqual( expected, actual, 'for symbol set: %s\n' ' Expected: %s\n' ' Got: %s\n' ' Missing: %s\n' ' Extra: %s\n' % (name.upper(), expected, actual, expected - actual, actual - expected)) def assertScopeIs(self, scope, used, modified): """Assert the scope contains specific used, modified & created variables.""" self.assertSymbolSetsAre(used, scope.read, 'read') self.assertSymbolSetsAre(modified, scope.modified, 'modified') def test_print_statement(self): def test_fn(a): b = 0 c = 1 print(a, b) return c node, _ = self._parse_and_analyze(test_fn) print_node = node.body[2] if isinstance(print_node, gast.Print): # Python 2 print_args_scope = anno.getanno(print_node, NodeAnno.ARGS_SCOPE) else: # Python 3 assert isinstance(print_node, gast.Expr) # The call node should be the one being annotated. print_node = print_node.value print_args_scope = anno.getanno(print_node, NodeAnno.ARGS_SCOPE) # We basically need to detect which variables are captured by the call # arguments. self.assertScopeIs(print_args_scope, ('a', 'b'), ()) def test_call_args(self): def test_fn(a): b = 0 c = 1 foo(a, b) # pylint:disable=undefined-variable return c node, _ = self._parse_and_analyze(test_fn) call_node = node.body[2].value # We basically need to detect which variables are captured by the call # arguments. self.assertScopeIs( anno.getanno(call_node, NodeAnno.ARGS_SCOPE), ('a', 'b'), ()) def test_call_args_attributes(self): def foo(*_): pass def test_fn(a): a.c = 0 foo(a.b, a.c) return a.d node, _ = self._parse_and_analyze(test_fn) call_node = node.body[1].value self.assertScopeIs( anno.getanno(call_node, NodeAnno.ARGS_SCOPE), ('a', 'a.b', 'a.c'), ()) def test_call_args_subscripts(self): def foo(*_): pass def test_fn(a): b = 1 c = 2 foo(a[0], a[b]) return a[c] node, _ = self._parse_and_analyze(test_fn) call_node = node.body[2].value self.assertScopeIs( anno.getanno(call_node, NodeAnno.ARGS_SCOPE), ('a', 'a[0]', 'a[b]', 'b'), ()) def test_while(self): def test_fn(a): b = a while b > 0: c = b b -= 1 return b, c node, _ = self._parse_and_analyze(test_fn) while_node = node.body[1] self.assertScopeIs( anno.getanno(while_node, NodeAnno.BODY_SCOPE), ('b',), ('b', 'c')) self.assertScopeIs( anno.getanno(while_node, NodeAnno.BODY_SCOPE).parent, ('a', 'b', 'c'), ('b', 'c')) self.assertScopeIs( anno.getanno(while_node, NodeAnno.COND_SCOPE), ('b',), ()) def test_for(self): def test_fn(a): b = a for _ in a: c = b b -= 1 return b, c node, _ = self._parse_and_analyze(test_fn) for_node = node.body[1] self.assertScopeIs( anno.getanno(for_node, NodeAnno.ITERATE_SCOPE), (), ('_')) self.assertScopeIs( anno.getanno(for_node, NodeAnno.BODY_SCOPE), ('b',), ('b', 'c')) self.assertScopeIs( anno.getanno(for_node, NodeAnno.BODY_SCOPE).parent, ('a', 'b', 'c'), ('b', 'c', '_')) def test_if(self): def test_fn(x): if x > 0: x = -x y = 2 * x z = -y else: x = 2 * x y = -x u = -y return z, u node, _ = self._parse_and_analyze(test_fn) if_node = node.body[0] self.assertScopeIs( anno.getanno(if_node, NodeAnno.BODY_SCOPE), ('x', 'y'), ('x', 'y', 'z')) self.assertScopeIs( anno.getanno(if_node, NodeAnno.BODY_SCOPE).parent, ('x', 'y', 'z', 'u'), ('x', 'y', 'z', 'u')) self.assertScopeIs( anno.getanno(if_node, NodeAnno.ORELSE_SCOPE), ('x', 'y'), ('x', 'y', 'u')) self.assertScopeIs( anno.getanno(if_node, NodeAnno.ORELSE_SCOPE).parent, ('x', 'y', 'z', 'u'), ('x', 'y', 'z', 'u')) def test_if_attributes(self): def test_fn(a): if a > 0: a.b = -a.c d = 2 * a else: a.b = a.c d = 1 return d node, _ = self._parse_and_analyze(test_fn) if_node = node.body[0] self.assertScopeIs( anno.getanno(if_node, NodeAnno.BODY_SCOPE), ('a', 'a.c'), ('a.b', 'd')) self.assertScopeIs( anno.getanno(if_node, NodeAnno.ORELSE_SCOPE), ('a', 'a.c'), ('a.b', 'd')) self.assertScopeIs( anno.getanno(if_node, NodeAnno.BODY_SCOPE).parent, ('a', 'a.c', 'd'), ('a.b', 'd')) def test_if_subscripts(self): def test_fn(a, b, c, e): if a > 0: a[b] = -a[c] d = 2 * a else: a[0] = e d = 1 return d node, _ = self._parse_and_analyze(test_fn) if_node = node.body[0] self.assertScopeIs( anno.getanno(if_node, NodeAnno.BODY_SCOPE), ('a', 'b', 'c', 'a[c]'), ('a[b]', 'd')) # TODO(mdan): Should subscript writes (a[0] = 1) be considered to read "a"? self.assertScopeIs( anno.getanno(if_node, NodeAnno.ORELSE_SCOPE), ('a', 'e'), ('a[0]', 'd')) self.assertScopeIs( anno.getanno(if_node, NodeAnno.ORELSE_SCOPE).parent, ('a', 'b', 'c', 'd', 'e', 'a[c]'), ('d', 'a[b]', 'a[0]')) def test_nested_if(self): def test_fn(b): if b > 0: if b < 5: a = b else: a = b * b return a node, _ = self._parse_and_analyze(test_fn) inner_if_node = node.body[0].body[0] self.assertScopeIs( anno.getanno(inner_if_node, NodeAnno.BODY_SCOPE), ('b',), ('a',)) self.assertScopeIs( anno.getanno(inner_if_node, NodeAnno.ORELSE_SCOPE), ('b',), ('a',)) def test_nested_function(self): def test_fn(a): def f(x): y = x * x return y b = a for i in a: c = b b -= f(i) return b, c node, _ = self._parse_and_analyze(test_fn) fn_def_node = node.body[0] self.assertScopeIs( anno.getanno(fn_def_node, NodeAnno.BODY_SCOPE), ('x', 'y'), ('y',)) def test_constructor_attributes(self): class TestClass(object): def __init__(self, a): self.b = a self.b.c = 1 node, _ = self._parse_and_analyze(TestClass) init_node = node.body[0] self.assertScopeIs( anno.getanno(init_node, NodeAnno.BODY_SCOPE), ('self', 'a', 'self.b'), ('self', 'self.b', 'self.b.c')) def test_aug_assign_subscripts(self): def test_fn(a): a[0] += 1 node, _ = self._parse_and_analyze(test_fn) fn_node = node self.assertScopeIs( anno.getanno(fn_node, NodeAnno.BODY_SCOPE), ('a', 'a[0]'), ('a[0]',)) def test_return_vars_are_read(self): def test_fn(a, b, c): # pylint: disable=unused-argument return c node, _ = self._parse_and_analyze(test_fn) fn_node = node self.assertScopeIs(anno.getanno(fn_node, NodeAnno.BODY_SCOPE), ('c',), ()) def test_aug_assign(self): def test_fn(a, b): a += b node, _ = self._parse_and_analyze(test_fn) fn_node = node self.assertScopeIs( anno.getanno(fn_node, NodeAnno.BODY_SCOPE), ('a', 'b'), ('a')) def test_aug_assign_rvalues(self): a = dict(bar=3) def foo(): return a def test_fn(x): foo()['bar'] += x node, _ = self._parse_and_analyze(test_fn) fn_node = node self.assertScopeIs( anno.getanno(fn_node, NodeAnno.BODY_SCOPE), ('foo', 'x'), ()) def test_params(self): def test_fn(a, b): # pylint: disable=unused-argument return b node, _ = self._parse_and_analyze(test_fn) fn_node = node body_scope = anno.getanno(fn_node, NodeAnno.BODY_SCOPE) self.assertScopeIs(body_scope, ('b',), ()) self.assertScopeIs(body_scope.parent, ('b',), ('a', 'b')) args_scope = anno.getanno(fn_node.args, anno.Static.SCOPE) self.assertSymbolSetsAre(('a', 'b'), args_scope.params.keys(), 'params') def test_lambda_captures_reads(self): def test_fn(a, b): return lambda: a + b node, _ = self._parse_and_analyze(test_fn) fn_node = node body_scope = anno.getanno(fn_node, NodeAnno.BODY_SCOPE) self.assertScopeIs(body_scope, ('a', 'b'), ()) # Nothing local to the lambda is tracked. self.assertSymbolSetsAre((), body_scope.params.keys(), 'params') def test_lambda_params_are_isolated(self): def test_fn(a, b): # pylint: disable=unused-argument return lambda a: a + b node, _ = self._parse_and_analyze(test_fn) fn_node = node body_scope = anno.getanno(fn_node, NodeAnno.BODY_SCOPE) self.assertScopeIs(body_scope, ('b',), ()) self.assertSymbolSetsAre((), body_scope.params.keys(), 'params') def test_lambda_complex(self): def test_fn(a, b, c, d): # pylint: disable=unused-argument a = (lambda a, b, c: a + b + c)(d, 1, 2) + b node, _ = self._parse_and_analyze(test_fn) fn_node = node body_scope = anno.getanno(fn_node, NodeAnno.BODY_SCOPE) self.assertScopeIs(body_scope, ('b', 'd'), ('a',)) self.assertSymbolSetsAre((), body_scope.params.keys(), 'params') def test_lambda_nested(self): def test_fn(a, b, c, d, e): # pylint: disable=unused-argument a = lambda a, b: d(lambda b: a + b + c) # pylint: disable=undefined-variable node, _ = self._parse_and_analyze(test_fn) fn_node = node body_scope = anno.getanno(fn_node, NodeAnno.BODY_SCOPE) self.assertScopeIs(body_scope, ('c', 'd'), ('a',)) self.assertSymbolSetsAre((), body_scope.params.keys(), 'params') if __name__ == '__main__': test.main()
# # Copyright (C) 2014 eNovance SAS <licensing@enovance.com> # # Author: Erwan Velu <erwan.velu@enovance.com> # # 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 unittest from sets import Set import os.path import cardiff from cardiff import utils from cardiff import check from cardiff import compare_sets def load_samples(bench_values): module_dir = os.path.dirname(cardiff.__file__) samples_dir = os.path.join(module_dir, '..', 'test_data') for health in utils.find_file(samples_dir, '*.hw_'): bench_values.append(eval(open(health).read())) class TestDetect(unittest.TestCase): def test_cpu(self): l = [] load_samples(l) result = compare_sets.compare(check.search_item(utils.find_sub_element(l, 'serial', 'cpu'), 'serial', "cpu", "(.*)", ['bogomips', 'loops_per_sec', 'bandwidth', 'cache_size'])) self.maxDiff = None for element in result: group = result[element] p = ['CZ3404YWP4', 'CZ3404YWNW', 'CZ3404YWP6', 'CZ3404YWPP', 'CZ3404YWP2', 'CZ3404YWPS', 'CZ3404YWP8', 'CZ3404YWPC', 'CZ3404YWPX', 'CZ3404YWPV', 'CZ3404YWNT', 'CZ3404YWNR', 'CZ3404YWPE', 'CZ3404YWPA', 'CZ3404YWPM', 'CZ3404YWNN', 'CZ3404YWR0', 'CZ3404YWPH', 'CZ3404YWPK'] self.assertEqual(sorted(p), sorted(group)) res = Set([('cpu', 'physical_0', 'cores', '8'), ('cpu', 'physical_1', 'clock', '100000000'), ('cpu', 'physical_0', 'physid', '400'), ('cpu', 'physical_0', 'threads', '16'), ('cpu', 'physical_1', 'frequency', '2000000000'), ('cpu', 'physical_0', 'clock', '100000000'), ('cpu', 'physical_0', 'enabled_cores', '8'), ('cpu', 'physical_0', 'product', 'Intel(R) Xeon(R) CPU E5-2650 0 @ 2.00GHz'), ('cpu', 'physical_1', 'vendor', 'Intel Corp.'), ('cpu', 'physical', 'number', '2'), ('cpu', 'physical_1', 'physid', '401'), ('cpu', 'physical_1', 'product', 'Intel(R) Xeon(R) CPU E5-2650 0 @ 2.00GHz'), ('cpu', 'physical_0', 'vendor', 'Intel Corp.'), ('cpu', 'physical_1', 'threads', '16'), ('cpu', 'physical_0', 'frequency', '2000000000'), ('cpu', 'physical_1', 'enabled_cores', '8'), ('cpu', 'physical_1', 'cores', '8'), ('cpu', 'logical', 'number', '32')]) self.assertEqual(sorted(res), sorted(eval(element))) def test_network_interfaces(self): l = [] load_samples(l) result = compare_sets.compare(check.search_item(utils.find_sub_element(l, 'serial', 'network'), 'serial', "network", "(.*)", ['serial', 'ipv4'])) self.maxDiff = None for element in result: group = result[element] p = ['CZ3404YWP4', 'CZ3404YWNW', 'CZ3404YWP6', 'CZ3404YWNR', 'CZ3404YWP2', 'CZ3404YWPS', 'CZ3404YWP8', 'CZ3404YWPX', 'CZ3404YWNT', 'CZ3404YWR0', 'CZ3404YWPE', 'CZ3404YWPA', 'CZ3404YWPP', 'CZ3404YWPC', 'CZ3404YWNN', 'CZ3404YWPM', 'CZ3404YWPV', 'CZ3404YWPH', 'CZ3404YWPK'] self.assertEqual(sorted(p), sorted(group)) res = Set([('network', 'eth0', 'duplex', 'full'), ('network', 'eth0', 'latency', '0'), ('network', 'eth1', 'autonegotiation', 'on'), ('network', 'eth1', 'duplex', 'full'), ('network', 'eth1', 'link', 'yes'), ('network', 'eth1', 'driver', 'be2net'), ('network', 'eth1', 'businfo', 'pci@0000:04:00.1'), ('network', 'eth0', 'autonegotiation', 'on'), ('network', 'eth0', 'businfo', 'pci@0000:04:00.0'), ('network', 'eth1', 'latency', '0'), ('network', 'eth0', 'driver', 'be2net'), ('network', 'eth0', 'link', 'yes')]) self.assertEqual(sorted(res), sorted(eval(element))) def test_memory_timing(self): l = [] load_samples(l) result = compare_sets.compare(check.search_item(utils.find_sub_element(l, 'serial', 'memory'), 'serial', "memory", "DDR(.*)")) self.maxDiff = None for element in result: group = result[element] p = ['CZ3404YWP4', 'CZ3404YWNW', 'CZ3404YWP6', 'CZ3404YWNR', 'CZ3404YWP2', 'CZ3404YWPS', 'CZ3404YWP8', 'CZ3404YWPX', 'CZ3404YWNT', 'CZ3404YWR0', 'CZ3404YWPE', 'CZ3404YWPA', 'CZ3404YWPP', 'CZ3404YWPC', 'CZ3404YWNN', 'CZ3404YWPM', 'CZ3404YWPV', 'CZ3404YWPH', 'CZ3404YWPK'] self.assertEqual(sorted(p), sorted(group)) res = Set([('memory', 'DDR_1', 'tWTPr', '31'), ('memory', 'DDR_2', 'tFAW', '63'), ('memory', 'DDR_2', 'tCL', '11'), ('memory', 'DDR_2', 'tRFC', '511'), ('memory', 'DDR_2', 'tRRD', '7'), ('memory', 'DDR_2', 'B2B', '31'), ('memory', 'DDR_0', 'tCL', '11'), ('memory', 'DDR_2', 'tRCD', '15'), ('memory', 'DDR_1', 'tRAS', '31'), ('memory', 'DDR_1', 'tRCD', '15'), ('memory', 'DDR', 'type', '3'), ('memory', 'DDR_1', 'tRFC', '511'), ('memory', 'DDR_2', 'tRTPr', '15'), ('memory', 'DDR_0', 'tRAS', '31'), ('memory', 'DDR_2', 'tWTPr', '31'), ('memory', 'DDR_1', 'tWR', '11'), ('memory', 'DDR_0', 'tRTPr', '15'), ('memory', 'DDR_1', 'tRRD', '7'), ('memory', 'DDR_0', 'tFAW', '63'), ('memory', 'DDR_0', 'tRCD', '15'), ('memory', 'DDR_1', 'tRP', '15'), ('memory', 'DDR_1', 'B2B', '31'), ('memory', 'DDR_2', 'tRP', '15'), ('memory', 'DDR_0', 'tRFC', '511'), ('memory', 'DDR_1', 'tFAW', '63'), ('memory', 'DDR_1', 'tRTPr', '15'), ('memory', 'DDR_0', 'tRRD', '7'), ('memory', 'DDR_0', 'tWR', '11'), ('memory', 'DDR_0', 'tWTPr', '31'), ('memory', 'DDR_0', 'tRP', '15'), ('memory', 'DDR_2', 'tWR', '11'), ('memory', 'DDR_1', 'tCL', '11'), ('memory', 'DDR_0', 'B2B', '31'), ('memory', 'DDR_2', 'tRAS', '31')]) self.assertEqual(sorted(res), sorted(eval(element))) def test_firmware(self): l = [] load_samples(l) result = compare_sets.compare(check.search_item(utils.find_sub_element(l, 'serial', 'firmware'), 'serial', "firmware", "(.*)")) self.maxDiff = None for element in result: group = result[element] p = ['CZ3404YWP4', 'CZ3404YWNW', 'CZ3404YWP6', 'CZ3404YWNR', 'CZ3404YWP2', 'CZ3404YWPS', 'CZ3404YWP8', 'CZ3404YWPX', 'CZ3404YWNT', 'CZ3404YWR0', 'CZ3404YWPE', 'CZ3404YWPA', 'CZ3404YWPP', 'CZ3404YWPC', 'CZ3404YWNN', 'CZ3404YWPM', 'CZ3404YWPV', 'CZ3404YWPH', 'CZ3404YWPK'] self.assertEqual(sorted(p), sorted(group)) res = Set([('firmware', 'bios', 'date', '09/18/2013'), ('firmware', 'bios', 'version', 'I31'), ('firmware', 'bios', 'vendor', 'HP')]) self.assertEqual(sorted(res), sorted(eval(element))) def test_systems(self): l = [] load_samples(l) result = compare_sets.compare(check.search_item(utils.find_sub_element(l, 'serial', 'system'), 'serial', "system", "(.*)", ['serial'])) self.maxDiff = None for element in result: group = result[element] p = ['CZ3404YWP4', 'CZ3404YWNW', 'CZ3404YWP6', 'CZ3404YWNR', 'CZ3404YWP2', 'CZ3404YWPS', 'CZ3404YWP8', 'CZ3404YWPX', 'CZ3404YWNT', 'CZ3404YWR0', 'CZ3404YWPE', 'CZ3404YWPA', 'CZ3404YWPP', 'CZ3404YWPC', 'CZ3404YWNN', 'CZ3404YWPM', 'CZ3404YWPV', 'CZ3404YWPH', 'CZ3404YWPK'] self.assertEqual(sorted(p), sorted(group)) res = Set([('system', 'ipmi', 'channel', '2'), ('system', 'product', 'name', 'ProLiant BL460c Gen8 (641016-B21)'), ('system', 'product', 'vendor', 'HP')]) self.assertEqual(sorted(res), sorted(eval(element))) def test_logical_disks(self): l = [] load_samples(l) result = compare_sets.compare(check.search_item(utils.find_sub_element(l, 'serial', 'disk'), 'serial', "disk", "sd(\S+)", ['simultaneous', 'standalone'])) self.maxDiff = None for element in result: group = result[element] p = ['CZ3404YWP4', 'CZ3404YWNW', 'CZ3404YWP6', 'CZ3404YWNR', 'CZ3404YWP2', 'CZ3404YWPS', 'CZ3404YWP8', 'CZ3404YWPX', 'CZ3404YWNT', 'CZ3404YWR0', 'CZ3404YWPE', 'CZ3404YWPA', 'CZ3404YWPP', 'CZ3404YWPC', 'CZ3404YWNN', 'CZ3404YWPM', 'CZ3404YWPV', 'CZ3404YWPH', 'CZ3404YWPK'] self.assertEqual(sorted(p), sorted(group)) res = Set([('disk', 'sdb', 'Write Cache Enable', '0'), ('disk', 'sdb', 'model', 'LOGICAL VOLUME'), ('disk', 'sdb', 'rev', '4.68'), ('disk', 'sdb', 'size', '299'), ('disk', 'sda', 'Write Cache Enable', '0'), ('disk', 'sdb', 'vendor', 'HP'), ('disk', 'sda', 'rev', '4.68'), ('disk', 'sda', 'Read Cache Disable', '0'), ('disk', 'sdb', 'Read Cache Disable', '0'), ('disk', 'sda', 'vendor', 'HP'), ('disk', 'sda', 'model', 'LOGICAL VOLUME'), ('disk', 'sda', 'size', '299')]) self.assertEqual(sorted(res), sorted(eval(element))) def test_hp_physical_disks(self): l = [] load_samples(l) result = compare_sets.compare(check.search_item(utils.find_sub_element(l, 'serial', 'disk'), 'serial', "disk", "(\d+)I:(\d+):(\d+)")) self.maxDiff = None item = 0 for element in result: group = result[element] if item == 0: p = ['CZ3404YWNW'] res = Set([('disk', '1I:1:3', 'size', '1000'), ('disk', '1I:1:7', 'slot', '3'), ('disk', '1I:1:2', 'type', 'SATA'), ('disk', '1I:1:8', 'type', 'SATA'), ('disk', '1I:1:4', 'size', '1000'), ('disk', '1I:1:3', 'slot', '3'), ('disk', '1I:1:2', 'size', '300'), ('disk', '1I:1:1', 'type', 'SATA'), ('disk', '1I:1:4', 'type', 'SATA'), ('disk', '1I:1:6', 'slot', '3'), ('disk', '1I:1:5', 'slot', '3'), ('disk', '1I:1:5', 'size', '1000'), ('disk', '1I:1:5', 'type', 'SATA'), ('disk', '1I:1:3', 'type', 'SATA'), ('disk', '1I:1:2', 'type', 'SAS'), ('disk', '1I:1:6', 'type', 'SATA'), ('disk', '1I:1:1', 'size', '1000'), ('disk', '1I:1:1', 'size', '300'), ('disk', '1I:1:6', 'size', '1000'), ('disk', '1I:1:4', 'slot', '3'), ('disk', '1I:1:8', 'size', '1000'), ('disk', '1I:1:1', 'slot', '0'), ('disk', '1I:1:2', 'slot', '3'), ('disk', '1I:1:1', 'slot', '3'), ('disk', '1I:1:2', 'size', '1000'), ('disk', '1I:1:2', 'slot', '0'), ('disk', '1I:1:7', 'size', '1000'), ('disk', '1I:1:7', 'type', 'SATA'), ('disk', '1I:1:8', 'slot', '3'), ('disk', '1I:1:1', 'type', 'SAS')]) else: p = ['CZ3404YWP4', 'CZ3404YWP6', 'CZ3404YWNR', 'CZ3404YWP2', 'CZ3404YWPS', 'CZ3404YWP8', 'CZ3404YWPX', 'CZ3404YWNT', 'CZ3404YWR0', 'CZ3404YWPE', 'CZ3404YWPA', 'CZ3404YWPP', 'CZ3404YWPC', 'CZ3404YWNN', 'CZ3404YWPM', 'CZ3404YWPV', 'CZ3404YWPH', 'CZ3404YWPK'] res = Set([('disk', '1I:1:2', 'type', 'SAS'), ('disk', '1I:1:1', 'slot', '0'), ('disk', '1I:1:2', 'size', '300'), ('disk', '1I:1:2', 'slot', '0'), ('disk', '1I:1:1', 'size', '300'), ('disk', '1I:1:1', 'type', 'SAS')]) item = item + 1 self.assertEqual(sorted(p), sorted(group)) self.assertEqual(sorted(res), sorted(eval(element)))
import sys import os import subprocess workdirectory="/alice/cern.ch/user/b/blim/Xi1530Extractor" gridworkdirectory="Xi1530Extractor" BASE_PATH=os.path.dirname(os.path.abspath(__file__)) inputfiledirectory=BASE_PATH + "/" savepath=BASE_PATH+"/data/" commandlist = ["submit", "download", "check", "local"] Mode = 5 #0 for submit, 1 for download, 2 for file check, 3 for local job with missing jobs if not os.path.exists(savepath): os.makedirs(savepath) if(len(sys.argv) < 2): print("Usage: python grid.py submit (or download or check or local)") exit() if str(sys.argv[1]) in commandlist: Mode = commandlist.index(str(sys.argv[1])) else: print("Choose from: "+", ".join(commandlist)) exit() # Configuration # NormRangeStudy=1 BinCoutStudy=1 fitstudy=1 default=1 cutvar=1 fitvar=1 # Grid Input files # inputdata = "AnalysisResults_LHC15fi_16deghijklop_17cefgijklmor_SYS_light_fixed.root" inputRsnMCdata = "AnalysisResults_Xi1530LHC18c6b_RsnMC_SYS_fixed.root" inputGenMCdata = "AnalysisResults_Xi1530LHC16_GenMC_final.root" Inputfiles=[ "extract.jdl", "extract.sh", #inputdata, #inputRsnMCdata, #inputGenMCdata, "DrawXi1530.C" ] # Global variables # totaljobs = 0 totalskip = 1 complete = 1 missingjobs = [] #Multi_bins = ["0 100", "0 10", "10 30", "30 50", "50 70", "70 100", "0 0.01", "0.01 0.1"] Multi_bins = ["0 100", "0 10", "10 30", "30 50", "50 70", "70 100"] #Multi_bins = ["30 100"] #Multi_bins = ["0.01 0.1", "0 0.01"] CutSysematic_bins = ["DefaultOption", "TPCNsigmaXi1530PionLoose", "TPCNsigmaXi1530PionTight", "TPCNsigmaXiLoose", "TPCNsigmaXiTight", "Xi1530PionZVertexLoose", "Xi1530PionZVertexTight", "DCADistLambdaDaughtersLoose", "DCADistLambdaDaughtersTight", "DCADistXiDaughtersLoose", "DCADistXiDaughtersTight", "DCADistLambdaPVLoose", "DCADistLambdaPVTight", "V0CosineOfPointingAngleLoose", "V0CosineOfPointingAngleTight", "CascadeCosineOfPointingAngleLoose", "CascadeCosineOfPointingAngleTight", "XiMassWindowLoose", "XiMassWindowTight", "XiTrackCut"] FitSysematic_bins = ["LikeSignBkg", "BkgFit"] Normvariations=["NormVarm", "NormVarp", "NormVarLm", "NormVarLp", "NormVarRm", "NormVarRp"] Fitvariations=["FitVarLm", "FitVarLp", "FitVarRm", "FitVarRp", "FitVarBothm", "FitVarBothp"] Bincountvariations =["BinCountLm", "BinCountRp", "BinCountBothp", "BinCountLp", "BinCountRm", "BinCountBothm"] Bincountvariations_caution=["BinCountLp", "BinCountRm", "BinCountBothm"] ## Some functions ## def if_exist(filename): exists = os.path.isfile(savepath+filename) if exists: return 1 else: return 0 def download(args): global totaljobs global totalskip totaljobs += 1 file = "AnalysisResults_Extracted_" + str(args[0]) + "_Multi_" + "%0.2f"%float(args[1]) + "-" + "%0.2f"%float(args[2]) + "_" + str(args[3]) + str(args[4]) + ".root" if(if_exist(file)): command = "file found, skip download: " + file rproc = subprocess.Popen('echo ' + command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) totalskip += 1 return rproc folderpath = str(args[0]) + str(args[1]) + str(args[2]) + str(args[3]) + str(args[4]) filepath = "alien://" + workdirectory + "/out/" + folderpath + "/" + file localpath = savepath + file command = """echo 'TGrid::Connect(\"alien://\");TFile::Cp(\"""" + filepath + """\", \"""" + localpath + """\");' | root -b -l | grep -v Welcome | grep -v Trying """ #print(command) rproc = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) outtext = rproc.communicate()[1] if "No more images to try" in str(outtext): missingjobs.append(args) return rproc def submit(args): global totaljobs totaljobs += 1 options = str(args[0]) + " " + str(args[1]) + " " + str(args[2]) + " " + str(args[3]) + " " + str(args[4]) command = """echo 'TGrid::Connect(\"alien://\");gGrid->Cd(\"""" + gridworkdirectory + """\");TGridResult *res = gGrid->Command(\"submit extract.jdl """ + options + """\");cout << res->GetKey(0,"jobId") << endl;' | root -b -l | grep -v Welcome | grep -v Trying """ #command = "alien_submit alien:" + workdirectory + "/extract.jdl " + options #old way #print(command) rproc = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) return rproc def filecheck(args): global totaljobs global totalskip totaljobs += 1 file = "AnalysisResults_Extracted_" + str(args[0]) + "_Multi_" + "%0.2f"%float(args[1]) + "-" + "%0.2f"%float(args[2]) + "_" + str(args[3]) + str(args[4]) + ".root" if(if_exist(file)): command = file+ ": available" rproc = subprocess.Popen('echo ' + command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) totalskip += 1 return rproc else: missingjobs.append(args) command = file+ ": Missing ------------------------------------------------------" rproc = subprocess.Popen('echo ' + command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) return rproc def localjob(args): global totaljobs global totalskip totaljobs += 1 file = "AnalysisResults_Extracted_" + str(args[0]) + "_Multi_" + "%0.2f"%float(args[1]) + "-" + "%0.2f"%float(args[2]) + "_" + str(args[3]) + str(args[4]) + ".root" if(if_exist(file)): command = file+ ": available" rproc = subprocess.Popen('echo ' + command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) totalskip += 1 return rproc else: command = """echo '-l -b -q DrawXi1530.C\(""" + str(args[0]) + ","+ str(args[1]) + ","+ str(args[2]) + """,\\\""""+ str(args[3]) + """\\\","""+ str(args[4])+ "\)' >> " + inputfiledirectory + "parallel.txt" rproc = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE) return rproc def doit(args): if(Mode == 0): return submit(args) if(Mode == 1): return download(args) if(Mode == 2): return filecheck(args) if(Mode == 3): return localjob(args) ## #### if Mode is 3: #Initialize subprocess.call("echo '' > " + inputfiledirectory + "parallel.txt", shell=True, stderr=subprocess.PIPE) submitjobs = [] if Mode is 0: for pushfile in Inputfiles: command = """echo 'TGrid::Connect(\"alien://\");TFile::Cp(\"""" + inputfiledirectory + pushfile + """\", \"alien://""" + workdirectory + """/""" + pushfile + """\");' | root -b -l | grep -v Welcome | grep -v Trying """ submitjobs.append(subprocess.Popen(command, shell=True)) for proc in submitjobs: output = proc.communicate() if output[0]: print(output) procs = [] procs_out = [] while(complete): for bins in Multi_bins: if(default): fileinfo = [1, bins.split(" ")[0], bins.split(" ")[1], "Default", 1] proc = doit(fileinfo) fileinfo = [1, bins.split(" ")[0], bins.split(" ")[1], "MCcheck", 1] proc = doit(fileinfo) procs.append(proc) if(NormRangeStudy): for normvariation in Normvariations: for optionnumber in range(1,5): fileinfo = [1, bins.split(" ")[0], bins.split(" ")[1], normvariation, optionnumber] proc = doit(fileinfo) procs.append(proc) for proc in procs: proc.wait() if(fitstudy): for fitvariation in Fitvariations: for optionnumber in range(1,6): fileinfo = [1, bins.split(" ")[0], bins.split(" ")[1], fitvariation, optionnumber] proc = doit(fileinfo) procs.append(proc) for proc in procs: proc.wait() if(BinCoutStudy): for bcvariation in Bincountvariations: for optionnumber in range(1,10): if(bcvariation in Bincountvariations_caution): if(optionnumber > 4): continue else: fileinfo = [1, bins.split(" ")[0], bins.split(" ")[1], bcvariation, optionnumber] proc = doit(fileinfo) procs.append(proc) else: fileinfo = [1, bins.split(" ")[0], bins.split(" ")[1], bcvariation, optionnumber] proc = doit(fileinfo) procs.append(proc) for proc in procs: proc.wait() if(cutvar): for sys in range(1,len(CutSysematic_bins)): fileinfo = [str(sys+1), bins.split(" ")[0], bins.split(" ")[1], CutSysematic_bins[sys], 1] proc = doit(fileinfo) procs.append(proc) for proc in procs: proc.wait() if(fitvar): for sys in FitSysematic_bins: fileinfo = [1, bins.split(" ")[0], bins.split(" ")[1], sys, 1] proc = doit(fileinfo) procs.append(proc) for proc in procs: proc.wait() # waiting for the finishing complete = totaljobs - totalskip print("total " + str(totaljobs) + "jobs / skip: " + str(totalskip)+ "\n") break print("total "+str(len(missingjobs))+" are missing, try to resubmit them") print(missingjobs) jobIds = [] proc = [] if Mode is 1 or 2: answer = raw_input("Resubmit? [yN]: ") if(answer == "y"): takearest = 0 for argument in missingjobs: takearest += 1 proc = submit(argument) procs.append(proc) for proc in procs: output = proc.communicate()[0] jobIds.append(int(s) for output in str.split() if output.isdigit()) print("rebumitted jobs: ") for jobid in jobIds: print(jobid) if(answer == "N"): print("Ok, done.") else: print("?") if Mode is 3: subprocess.call("sed '1d' " + inputfiledirectory + "parallel.txt > tmpfile; mv tmpfile " + inputfiledirectory + "parallel.txt", shell=True, stderr=subprocess.PIPE) subprocess.call("cd " + inputfiledirectory, shell=True, stderr=subprocess.PIPE) answer = raw_input("Start local job? [yN]: ") if(answer == "y"): subprocess.call("cat parallel.txt | xargs -P1 -L 1 root", shell=True, stderr=subprocess.PIPE) if(answer == "N"): print("Ok, done.") else: print("?")
import logging import asyncio try: from asyncio import run except ImportError: from ._asyncio_compat import run # noqa from async_generator import async_generator, yield_ from ..connection import Connection from ..channel import Channel, BaseChannel from ..replies import Reply, AsynchronousReply, ConnectionAborted from ..methods import BasicDeliver, BasicReturn, ChannelClose, ConnectionClose class AsyncioBaseChannel(BaseChannel): def __init__(self, writer, write_limit=50, *args, **kwargs): super().__init__(*args, **kwargs) self._writer = writer # The server can send us two things: a response to a method or # a connection/channel exception. self._response = asyncio.Queue(maxsize=1) self._server_exception = asyncio.Queue(maxsize=1) # A client exception can also happen in # AsyncioConnection._communicate. self._client_exception = asyncio.Queue(maxsize=1) self._write_limit = write_limit self._wrote_without_response = 0 async def _prepare_for_sending(self, method): # Because of asynchronous nature of AMQP, error handling # is difficult. First, we can't know in advance # the exact moment in future when the broker decides to send # us an exception. Second, we can send methods without waiting # for replies from the broker - essentially moving handling # the error from the first errored method call into the second # method call! if self.state in {'closed', 'closing'} and not method.closing: # This covers the case of two methods being sent without waiting # for responses, e.g.: # await channel.method(no_wait=True) # [here an exception is received] # await channel.method(no_wait=True) [raises the exception] # Raising the exception from the second call is at least # confusing, but I don't know a better way to inform # the user about the error. exc = await self._server_exception.get() raise AsynchronousReply(exc) logging.info('[channel_id %s] sending %s', self.channel_id, method) super()._prepare_for_sending(method) self._writer.write(self.data_to_send()) if not method.has_response(): # If there's no response we cant wait for, we should only # drain for I/O to complete. Possible error handling # is deferred to the next await, as described above. await self._writer.drain() # On a non-paused connection, drain won't yield to the event loop # making it impossible for _communicate to ever run. # We fix this by introducing a limit of writes without # awaiting for a reply (basic_publish case). Once the limit is hit, # we explicitly yield to the event loop via asyncio.sleep(0). # # Yes, we could sleep after every single drain but that is # _very_ inefficient. self._wrote_without_response += 1 if self._wrote_without_response > self._write_limit: await asyncio.sleep(0) self._wrote_without_response = 0 return self._wrote_without_response = 0 # If there is a response, then we can handle possible errors # right here, yay! return await self._result_or_exception(self._response.get()) async def _result_or_exception(self, coro=None): fs = [self._client_exception.get(), self._server_exception.get()] if coro is not None: fs.append(coro) done, pending = await asyncio.wait( fs, timeout=2, return_when=asyncio.FIRST_COMPLETED ) for task in pending: task.cancel() response = None for task in done: response = await task if isinstance(response, Exception): raise response return response async def _receive_method(self, method): logging.info('[channel_id %s] receiving %s', self.channel_id, method) # _method_handlers are defined in subclasses handler = self._method_handlers.get(method.__class__) if handler is not None: fut = handler(method) if fut is not None: await fut if isinstance(method, (BasicDeliver, BasicReturn, ChannelClose, ConnectionClose)): # These methods have their own special handling return if method.has_response(): # If the received method has responses, it means the server # sent this method, not the client, thus the client doesn't # wait for the reply and we shouldn't put the method into # self._response return await self._response.put(method) async def __aenter__(self): await self.open() return self async def __aexit__(self, exc_type, exc, traceback): if isinstance(exc, Reply): await self.close( exc.reply_code, exc.reply_text, exc.class_id, exc.method_id, ) else: await self.close() class AsyncioChannel(AsyncioBaseChannel, Channel): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._delivered_messages = asyncio.Queue() self._method_handlers.update({ BasicReturn: self._handle_basic_return, BasicDeliver: self._handle_basic_deliver, }) async def open(self): """Open the channel.""" await self._channel_open() async def close(self, reply_code=200, reply_text='OK', class_id=0, method_id=0): """Close the channel.""" if self.state != 'open': return await self._channel_close( reply_code, reply_text, class_id, method_id ) async def _handle_basic_return(self, method): await self._delivered_messages.put(method.content) async def _handle_basic_deliver(self, method): await self._delivered_messages.put(method.content) async def _handle_channel_close(self, method): await super()._handle_channel_close(method) exc = Reply.from_close_method(method) await self._server_exception.put(exc) self.state = 'closed' @async_generator async def delivered_messages(self): """Yields delivered messages.""" while self.state == 'open': message = await self._delivered_messages.get() await yield_(message) class AsyncioConnection(AsyncioBaseChannel, Connection): def __init__(self, host='localhost', port=5672, *, ssl=None, flags=0, sock=None, local_addr=None, server_hostname=None, **kwargs): super().__init__(writer=None, **kwargs) self._reader = None self._connect_args = { 'host': host, 'port': port, 'ssl': ssl, 'flags': flags, 'sock': sock, 'local_addr': local_addr, 'server_hostname': server_hostname, } self._negotiation = asyncio.Event() self._heartbeat_task = None self._communicate_task = None def _make_channel(self, channel_id): return AsyncioChannel(self._writer, self._write_limit, channel_id) async def _handle_connection_tune(self, method): self._heartbeat_task = asyncio.ensure_future(self._start_heartbeat()) await super()._handle_connection_tune(method) self._negotiation.set() async def _send_heartbeat(self): super()._send_heartbeat() self._writer.write(self.data_to_send()) await self._writer.drain() async def _start_heartbeat(self): if self.negotiated_settings.heartbeat == 0: return transport_closing = self._writer.transport.is_closing while self.state in {'opening', 'open'} and not transport_closing(): await self._send_heartbeat() self._missed_heartbeats += 1 await asyncio.sleep(self.negotiated_settings.heartbeat) async def open(self): """Open the connection.""" self._reader, self._writer = await asyncio.open_connection( **self._connect_args, ) self.initiate_connection() self._writer.write(self.data_to_send()) self._communicate_task = asyncio.ensure_future(self._communicate()) await self._result_or_exception(self._negotiation.wait()) await self._connection_open() async def close(self, reply_code=200, reply_text='OK', class_id=0, method_id=0): """Close the connection and all its channels.""" if self.state != 'open': return for channel in self.channels.values(): if channel.channel_id == 0: continue # Do not try close itself. await channel.close( reply_code, reply_text, class_id, method_id, ) await self._connection_close( reply_code, reply_text, class_id, method_id ) self._writer.close() self._heartbeat_task.cancel() await self._communicate_task async def _handle_connection_close(self, method): await super()._handle_connection_close(method) exc = Reply.from_close_method(method) await self._server_exception.put(exc) self.state = 'closed' async def _communicate(self): try: transport_closing = self._writer.transport.is_closing while (self.state in {'opening', 'open'} and not transport_closing()): frame_max = self.negotiated_settings.frame_max data = await self._reader.read(frame_max) if not data: raise ConnectionAborted for channel_id, methods in self.parse_data(data).items(): channel = self.channels[channel_id] for method in methods: await channel._receive_method(method) except Exception as exc: await self._client_exception.put(exc)
# ***** BEGIN GPL LICENSE BLOCK ***** # # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ***** END GPL LICENCE BLOCK ***** import bpy import bmesh import math import mathutils as mathu from bpy.props import * from bpy.types import Operator, AddonPreferences from . import mi_utils_base as ut_base from . import mi_looptools as loop_t from mathutils import Vector, Matrix # Settings class MI_MakeArc_Settings(bpy.types.PropertyGroup): arc_axis = bpy.props.FloatVectorProperty(name="Arc Axis", description="Arc Axis", default=(0.0, 0.0, 1.0), size=3) class MI_Make_Arc_Axis(bpy.types.Operator): """Draw a line with the mouse""" bl_idname = "mira.make_arc_get_axis" bl_label = "Arc Axis From Selected Face" bl_description = "Arc Axis From Selected Face" bl_options = {'REGISTER', 'UNDO'} def execute(self, context): active_obj = context.scene.objects.active bm = bmesh.from_edit_mesh(active_obj.data) bm.verts.ensure_lookup_table() sel_polys = [f for f in bm.faces if f.select] if sel_polys: nor = sel_polys[0].normal.copy() world_nor = ut_base.get_normal_world(nor, active_obj.matrix_world, active_obj.matrix_world.inverted()) context.scene.mi_makearc_settings.arc_axis = world_nor return {'FINISHED'} class MI_Make_Arc(bpy.types.Operator): """Draw a line with the mouse""" bl_idname = "mira.make_arc" bl_label = "Make Arc" bl_description = "Make Arc" bl_options = {'REGISTER', 'UNDO'} reset_values = BoolProperty(default=False) reverse_direction = BoolProperty(default=False) spread_mode = EnumProperty( items=(('Normal', 'Normal', ''), ('Even', 'Even', '') ), default = 'Normal' ) direction_vector = EnumProperty( items=(('Custom', 'Custom', ''), ('Middle', 'Middle', ''), ('MiddleCrossed', 'MiddleCrossed', '') ), default = 'Custom' ) upvec_offset = FloatProperty(name="Offset", description="Offset Arc", default=0.0) scale_arc = FloatProperty(name="Scale", description="Scale Arc", default=0.0) rotate_arc_axis = bpy.props.FloatProperty(name="Rotate", description="Rotate Arc Axis", default=0) rotate_axis = bpy.props.FloatVectorProperty(name="Rotate Axis", description="Rotate Axis", default=(0.0, 0.0, 1.0), size=3) def reset_all_values(self): self.reverse_direction = False self.spread_mode = 'Normal' self.direction_vector = 'Custom' self.upvec_offset = 0.0 self.scale_arc = 0.0 self.rotate_arc_axis = 0.0 self.reset_values = False def invoke(self, context, event): self.rotate_axis = context.scene.mi_makearc_settings.arc_axis return self.execute(context) def execute(self, context): if self.reset_values is True: self.reset_all_values() active_obj = context.scene.objects.active bm = bmesh.from_edit_mesh(active_obj.data) bm.verts.ensure_lookup_table() #verts = [v for v in bm.verts if v.select] # get loops loops = loop_t.get_connected_input(bm) loops = loop_t.check_loops(loops, bm) if not loops: self.report({'WARNING'}, "No Loops!") return {'CANCELLED'} first_indexes = [] if isinstance(bm.select_history[0], bmesh.types.BMVert): for element in bm.select_history: first_indexes.append(element.index) elif isinstance(bm.select_history[0], bmesh.types.BMEdge): for element in bm.select_history: el_verts = element.verts first_indexes.append(el_verts[0].index) first_indexes.append(el_verts[1].index) for loop in loops: if loop[1] is True: continue loop_verts = [] for ind in loop[0]: loop_verts.append(bm.verts[ind]) # for the case if we need to reverse it if loop[0][-1] in first_indexes: loop_verts = list(reversed(loop_verts)) # reverse again for the direction if self.reverse_direction is True: loop_verts = list(reversed(loop_verts)) # positions first_vert_pos = active_obj.matrix_world * loop_verts[0].co last_vert_pos = active_obj.matrix_world * loop_verts[-1].co loop_centr_orig = first_vert_pos.lerp(last_vert_pos, 0.5) relative_dist = (first_vert_pos - loop_centr_orig).length sidevec = (first_vert_pos - last_vert_pos).normalized() obj_matrix = active_obj.matrix_world obj_matrix_inv = obj_matrix.inverted() if self.direction_vector == 'Custom': rot_dir = Vector((self.rotate_axis[0], self.rotate_axis[1], self.rotate_axis[2])).normalized() elif self.direction_vector == 'MiddleCrossed': middle_nor = loop_verts[int(len(loop_verts) / 2)].normal.copy().normalized() middle_nor = ut_base.get_normal_world(middle_nor, obj_matrix, obj_matrix_inv) rot_dir = middle_nor.cross(sidevec).normalized() # fix only for MiddleCrossed if not self.reverse_direction: rot_dir.negate() else: middle_nor = loop_verts[int(len(loop_verts) / 2)].normal.copy().normalized() middle_nor = ut_base.get_normal_world(middle_nor, obj_matrix, obj_matrix_inv) middle_nor = middle_nor.cross(sidevec).normalized() rot_dir = middle_nor.cross(sidevec).normalized() rot_dir.negate() upvec = rot_dir.cross(sidevec).normalized() loop_centr = ( self.upvec_offset * upvec * relative_dist ) + loop_centr_orig loop_angle = (first_vert_pos - loop_centr).normalized().angle((last_vert_pos - loop_centr).normalized()) if self.upvec_offset > 0: loop_angle = math.radians( (360 - math.degrees(loop_angle)) ) # even spread line_data = None if self.spread_mode == 'Even': world_verts = [active_obj.matrix_world * vert.co for vert in loop_verts] line_data = [] line_length = 0.0 for i, vec in enumerate(world_verts): if i == 0: line_data.append(0) else: line_length += (vec - world_verts[i-1]).length line_data.append(line_length) # make arc! for i, vert in enumerate(loop_verts): if i != 0 and i != len(loop_verts)-1: if self.spread_mode == 'Normal': rot_angle = loop_angle * (i / (len(loop_verts) - 1)) else: rot_angle = loop_angle * (line_data[i] / line_data[len(loop_verts)-1]) rot_mat = Matrix.Rotation(rot_angle, 3, rot_dir) vert_pos = (rot_mat * (first_vert_pos - loop_centr)) + loop_centr if self.scale_arc != 0: vert_rel_dist = mathu.geometry.distance_point_to_plane(vert_pos, loop_centr_orig, upvec) vert_rel_dist_max = self.upvec_offset + relative_dist if vert_rel_dist != 0 and vert_rel_dist_max != 0: vert_pos_offset = vert_rel_dist / vert_rel_dist_max vert_pos += (self.scale_arc * upvec * vert_pos_offset * vert_rel_dist_max) # rotate arc if self.rotate_arc_axis != 0: rot_mat_2 = Matrix.Rotation(math.radians(self.rotate_arc_axis), 3, sidevec) vert_pos = (rot_mat_2 * (vert_pos - loop_centr_orig)) + loop_centr_orig vert.co = active_obj.matrix_world.inverted() * vert_pos bm.normal_update() bmesh.update_edit_mesh(active_obj.data) return {'FINISHED'}
# Copyright (c) 2009 Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.protocols.tls}. """ try: from twisted.protocols.tls import TLSMemoryBIOProtocol, TLSMemoryBIOFactory except ImportError: # Skip the whole test module if it can't be imported. skip = "pyOpenSSL 0.10 or newer required for twisted.protocol.tls" else: # Otherwise, the pyOpenSSL dependency must be satisfied, so all these # imports will work. from OpenSSL.crypto import X509Type from OpenSSL.SSL import TLSv1_METHOD, Error, Context, ConnectionType from twisted.internet.ssl import ClientContextFactory, PrivateCertificate from twisted.internet.ssl import DefaultOpenSSLContextFactory from twisted.python.filepath import FilePath from twisted.internet.interfaces import ISystemHandle, ISSLTransport from twisted.internet.error import ConnectionDone from twisted.internet.defer import Deferred, gatherResults from twisted.internet.protocol import Protocol, ClientFactory, ServerFactory from twisted.protocols.loopback import loopbackAsync, collapsingPumpPolicy from twisted.trial.unittest import TestCase from twisted.test.test_tcp import ConnectionLostNotifyingProtocol from twisted.test.test_ssl import certPath from twisted.test.proto_helpers import StringTransport class HandshakeCallbackContextFactory: """ L{HandshakeCallbackContextFactory} is a factory for SSL contexts which allows applications to get notification when the SSL handshake completes. @ivar _finished: A L{Deferred} which will be called back when the handshake is done. """ # pyOpenSSL needs to expose this. # https://bugs.launchpad.net/pyopenssl/+bug/372832 SSL_CB_HANDSHAKE_DONE = 0x20 def __init__(self): self._finished = Deferred() def factoryAndDeferred(cls): """ Create a new L{HandshakeCallbackContextFactory} and return a two-tuple of it and a L{Deferred} which will fire when a connection created with it completes a TLS handshake. """ contextFactory = cls() return contextFactory, contextFactory._finished factoryAndDeferred = classmethod(factoryAndDeferred) def _info(self, connection, where, ret): """ This is the "info callback" on the context. It will be called periodically by pyOpenSSL with information about the state of a connection. When it indicates the handshake is complete, it will fire C{self._finished}. """ if where & self.SSL_CB_HANDSHAKE_DONE: self._finished.callback(None) def getContext(self): """ Create and return an SSL context configured to use L{self._info} as the info callback. """ context = Context(TLSv1_METHOD) context.set_info_callback(self._info) return context class AccumulatingProtocol(Protocol): """ A protocol which collects the bytes it receives and closes its connection after receiving a certain minimum of data. @ivar howMany: The number of bytes of data to wait for before closing the connection. @ivar receiving: A C{list} of C{str} of the bytes received so far. """ def __init__(self, howMany): self.howMany = howMany def connectionMade(self): self.received = [] def dataReceived(self, bytes): self.received.append(bytes) if sum(map(len, self.received)) >= self.howMany: self.transport.loseConnection() class TLSMemoryBIOTests(TestCase): """ Tests for the implementation of L{ISSLTransport} which runs over another L{ITransport}. """ def test_interfaces(self): """ L{TLSMemoryBIOProtocol} instances provide L{ISSLTransport} and L{ISystemHandle}. """ proto = TLSMemoryBIOProtocol(None, None) self.assertTrue(ISSLTransport.providedBy(proto)) self.assertTrue(ISystemHandle.providedBy(proto)) def test_getHandle(self): """ L{TLSMemoryBIOProtocol.getHandle} returns the L{OpenSSL.SSL.Connection} instance it uses to actually implement TLS. This may seem odd. In fact, it is. The L{OpenSSL.SSL.Connection} is not actually the "system handle" here, nor even an object the reactor knows about directly. However, L{twisted.internet.ssl.Certificate}'s C{peerFromTransport} and C{hostFromTransport} methods depend on being able to get an L{OpenSSL.SSL.Connection} object in order to work properly. Implementing L{ISystemHandle.getHandle} like this is the easiest way for those APIs to be made to work. If they are changed, then it may make sense to get rid of this implementation of L{ISystemHandle} and return the underlying socket instead. """ factory = ClientFactory() contextFactory = ClientContextFactory() wrapperFactory = TLSMemoryBIOFactory(contextFactory, True, factory) proto = TLSMemoryBIOProtocol(wrapperFactory, Protocol()) transport = StringTransport() proto.makeConnection(transport) self.assertIsInstance(proto.getHandle(), ConnectionType) def test_makeConnection(self): """ When L{TLSMemoryBIOProtocol} is connected to a transport, it connects the protocol it wraps to a transport. """ clientProtocol = Protocol() clientFactory = ClientFactory() clientFactory.protocol = lambda: clientProtocol contextFactory = ClientContextFactory() wrapperFactory = TLSMemoryBIOFactory( contextFactory, True, clientFactory) sslProtocol = wrapperFactory.buildProtocol(None) transport = StringTransport() sslProtocol.makeConnection(transport) self.assertNotIdentical(clientProtocol.transport, None) self.assertNotIdentical(clientProtocol.transport, transport) def test_handshake(self): """ The TLS handshake is performed when L{TLSMemoryBIOProtocol} is connected to a transport. """ clientFactory = ClientFactory() clientFactory.protocol = Protocol clientContextFactory, handshakeDeferred = ( HandshakeCallbackContextFactory.factoryAndDeferred()) wrapperFactory = TLSMemoryBIOFactory( clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) serverFactory = ServerFactory() serverFactory.protocol = Protocol serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath) wrapperFactory = TLSMemoryBIOFactory( serverContextFactory, False, serverFactory) sslServerProtocol = wrapperFactory.buildProtocol(None) connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol) # Only wait for the handshake to complete. Anything after that isn't # important here. return handshakeDeferred def test_handshakeFailure(self): """ L{TLSMemoryBIOProtocol} reports errors in the handshake process to the application-level protocol object using its C{connectionLost} method and disconnects the underlying transport. """ clientConnectionLost = Deferred() clientFactory = ClientFactory() clientFactory.protocol = ( lambda: ConnectionLostNotifyingProtocol( clientConnectionLost)) clientContextFactory = HandshakeCallbackContextFactory() wrapperFactory = TLSMemoryBIOFactory( clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) serverConnectionLost = Deferred() serverFactory = ServerFactory() serverFactory.protocol = ( lambda: ConnectionLostNotifyingProtocol( serverConnectionLost)) # This context factory rejects any clients which do not present a # certificate. certificateData = FilePath(certPath).getContent() certificate = PrivateCertificate.loadPEM(certificateData) serverContextFactory = certificate.options(certificate) wrapperFactory = TLSMemoryBIOFactory( serverContextFactory, False, serverFactory) sslServerProtocol = wrapperFactory.buildProtocol(None) connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol) def cbConnectionLost(protocol): # The connection should close on its own in response to the error # induced by the client not supplying the required certificate. # After that, check to make sure the protocol's connectionLost was # called with the right thing. protocol.lostConnectionReason.trap(Error) clientConnectionLost.addCallback(cbConnectionLost) serverConnectionLost.addCallback(cbConnectionLost) # Additionally, the underlying transport should have been told to # go away. return gatherResults([ clientConnectionLost, serverConnectionLost, connectionDeferred]) def test_getPeerCertificate(self): """ L{TLSMemoryBIOFactory.getPeerCertificate} returns the L{OpenSSL.crypto.X509Type} instance representing the peer's certificate. """ # Set up a client and server so there's a certificate to grab. clientFactory = ClientFactory() clientFactory.protocol = Protocol clientContextFactory, handshakeDeferred = ( HandshakeCallbackContextFactory.factoryAndDeferred()) wrapperFactory = TLSMemoryBIOFactory( clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) serverFactory = ServerFactory() serverFactory.protocol = Protocol serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath) wrapperFactory = TLSMemoryBIOFactory( serverContextFactory, False, serverFactory) sslServerProtocol = wrapperFactory.buildProtocol(None) connectionDeferred = loopbackAsync( sslServerProtocol, sslClientProtocol) # Wait for the handshake def cbHandshook(ignored): # Grab the server's certificate and check it out cert = sslClientProtocol.getPeerCertificate() self.assertIsInstance(cert, X509Type) self.assertEquals( cert.digest('md5'), '9B:A4:AB:43:10:BE:82:AE:94:3E:6B:91:F2:F3:40:E8') handshakeDeferred.addCallback(cbHandshook) return handshakeDeferred def test_writeAfterHandshake(self): """ Bytes written to L{TLSMemoryBIOProtocol} before the handshake is complete are received by the protocol on the other side of the connection once the handshake succeeds. """ bytes = "some bytes" clientProtocol = Protocol() clientFactory = ClientFactory() clientFactory.protocol = lambda: clientProtocol clientContextFactory, handshakeDeferred = ( HandshakeCallbackContextFactory.factoryAndDeferred()) wrapperFactory = TLSMemoryBIOFactory( clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) serverProtocol = AccumulatingProtocol(len(bytes)) serverFactory = ServerFactory() serverFactory.protocol = lambda: serverProtocol serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath) wrapperFactory = TLSMemoryBIOFactory( serverContextFactory, False, serverFactory) sslServerProtocol = wrapperFactory.buildProtocol(None) connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol) # Wait for the handshake to finish before writing anything. def cbHandshook(ignored): clientProtocol.transport.write(bytes) # The server will drop the connection once it gets the bytes. return connectionDeferred handshakeDeferred.addCallback(cbHandshook) # Once the connection is lost, make sure the server received the # expected bytes. def cbDisconnected(ignored): self.assertEquals("".join(serverProtocol.received), bytes) handshakeDeferred.addCallback(cbDisconnected) return handshakeDeferred def test_writeBeforeHandshake(self): """ Bytes written to L{TLSMemoryBIOProtocol} before the handshake is complete are received by the protocol on the other side of the connection once the handshake succeeds. """ bytes = "some bytes" class SimpleSendingProtocol(Protocol): def connectionMade(self): self.transport.write(bytes) clientFactory = ClientFactory() clientFactory.protocol = SimpleSendingProtocol clientContextFactory, handshakeDeferred = ( HandshakeCallbackContextFactory.factoryAndDeferred()) wrapperFactory = TLSMemoryBIOFactory( clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) serverProtocol = AccumulatingProtocol(len(bytes)) serverFactory = ServerFactory() serverFactory.protocol = lambda: serverProtocol serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath) wrapperFactory = TLSMemoryBIOFactory( serverContextFactory, False, serverFactory) sslServerProtocol = wrapperFactory.buildProtocol(None) connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol) # Wait for the connection to end, then make sure the server received # the bytes sent by the client. def cbConnectionDone(ignored): self.assertEquals("".join(serverProtocol.received), bytes) connectionDeferred.addCallback(cbConnectionDone) return connectionDeferred def test_writeSequence(self): """ Bytes written to L{TLSMemoryBIOProtocol} with C{writeSequence} are received by the protocol on the other side of the connection. """ bytes = "some bytes" class SimpleSendingProtocol(Protocol): def connectionMade(self): self.transport.writeSequence(list(bytes)) clientFactory = ClientFactory() clientFactory.protocol = SimpleSendingProtocol clientContextFactory = HandshakeCallbackContextFactory() wrapperFactory = TLSMemoryBIOFactory( clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) serverProtocol = AccumulatingProtocol(len(bytes)) serverFactory = ServerFactory() serverFactory.protocol = lambda: serverProtocol serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath) wrapperFactory = TLSMemoryBIOFactory( serverContextFactory, False, serverFactory) sslServerProtocol = wrapperFactory.buildProtocol(None) connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol) # Wait for the connection to end, then make sure the server received # the bytes sent by the client. def cbConnectionDone(ignored): self.assertEquals("".join(serverProtocol.received), bytes) connectionDeferred.addCallback(cbConnectionDone) return connectionDeferred def test_multipleWrites(self): """ If multiple separate TLS messages are received in a single chunk from the underlying transport, all of the application bytes from each message are delivered to the application-level protocol. """ bytes = [str(i) for i in range(10)] class SimpleSendingProtocol(Protocol): def connectionMade(self): for b in bytes: self.transport.write(b) clientFactory = ClientFactory() clientFactory.protocol = SimpleSendingProtocol clientContextFactory = HandshakeCallbackContextFactory() wrapperFactory = TLSMemoryBIOFactory( clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) serverProtocol = AccumulatingProtocol(sum(map(len, bytes))) serverFactory = ServerFactory() serverFactory.protocol = lambda: serverProtocol serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath) wrapperFactory = TLSMemoryBIOFactory( serverContextFactory, False, serverFactory) sslServerProtocol = wrapperFactory.buildProtocol(None) connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol, collapsingPumpPolicy) # Wait for the connection to end, then make sure the server received # the bytes sent by the client. def cbConnectionDone(ignored): self.assertEquals("".join(serverProtocol.received), ''.join(bytes)) connectionDeferred.addCallback(cbConnectionDone) return connectionDeferred def test_hugeWrite(self): """ If a very long string is passed to L{TLSMemoryBIOProtocol.write}, any trailing part of it which cannot be send immediately is buffered and sent later. """ bytes = "some bytes" factor = 8192 class SimpleSendingProtocol(Protocol): def connectionMade(self): self.transport.write(bytes * factor) clientFactory = ClientFactory() clientFactory.protocol = SimpleSendingProtocol clientContextFactory = HandshakeCallbackContextFactory() wrapperFactory = TLSMemoryBIOFactory( clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) serverProtocol = AccumulatingProtocol(len(bytes) * factor) serverFactory = ServerFactory() serverFactory.protocol = lambda: serverProtocol serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath) wrapperFactory = TLSMemoryBIOFactory( serverContextFactory, False, serverFactory) sslServerProtocol = wrapperFactory.buildProtocol(None) connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol) # Wait for the connection to end, then make sure the server received # the bytes sent by the client. def cbConnectionDone(ignored): self.assertEquals("".join(serverProtocol.received), bytes * factor) connectionDeferred.addCallback(cbConnectionDone) return connectionDeferred def test_disorderlyShutdown(self): """ If a L{TLSMemoryBIOProtocol} loses its connection unexpectedly, this is reported to the application. """ clientConnectionLost = Deferred() clientFactory = ClientFactory() clientFactory.protocol = ( lambda: ConnectionLostNotifyingProtocol( clientConnectionLost)) clientContextFactory = HandshakeCallbackContextFactory() wrapperFactory = TLSMemoryBIOFactory( clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) # Client speaks first, so the server can be dumb. serverProtocol = Protocol() connectionDeferred = loopbackAsync(serverProtocol, sslClientProtocol) # Now destroy the connection. serverProtocol.transport.loseConnection() # And when the connection completely dies, check the reason. def cbDisconnected(clientProtocol): clientProtocol.lostConnectionReason.trap(Error) clientConnectionLost.addCallback(cbDisconnected) return clientConnectionLost def test_loseConnectionAfterHandshake(self): """ L{TLSMemoryBIOProtocol.loseConnection} sends a TLS close alert and shuts down the underlying connection. """ clientConnectionLost = Deferred() clientFactory = ClientFactory() clientFactory.protocol = ( lambda: ConnectionLostNotifyingProtocol( clientConnectionLost)) clientContextFactory, handshakeDeferred = ( HandshakeCallbackContextFactory.factoryAndDeferred()) wrapperFactory = TLSMemoryBIOFactory( clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) serverProtocol = Protocol() serverFactory = ServerFactory() serverFactory.protocol = lambda: serverProtocol serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath) wrapperFactory = TLSMemoryBIOFactory( serverContextFactory, False, serverFactory) sslServerProtocol = wrapperFactory.buildProtocol(None) connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol) # Wait for the handshake before dropping the connection. def cbHandshake(ignored): serverProtocol.transport.loseConnection() # Now wait for the client to notice. return clientConnectionLost handshakeDeferred.addCallback(cbHandshake) # Wait for the connection to end, then make sure the client was # notified of a handshake failure. def cbConnectionDone(clientProtocol): clientProtocol.lostConnectionReason.trap(ConnectionDone) # The server should have closed its underlying transport, in # addition to whatever it did to shut down the TLS layer. self.assertTrue(serverProtocol.transport.q.disconnect) # The client should also have closed its underlying transport once # it saw the server shut down the TLS layer, so as to avoid relying # on the server to close the underlying connection. self.assertTrue(clientProtocol.transport.q.disconnect) handshakeDeferred.addCallback(cbConnectionDone) return handshakeDeferred
import os import cv2 import tensorflow as tf import numpy as np class NeuralNetwork: def __init__(self, good_dir, bad_dir, frame_shape, trained=False, epochs=20): """ Initializes a simple convolution network for proper edge classification :param frames_and_labels: list of [frame, label] elements :param frames_shape: shape of the frame :param trained: whether the network is trained already :param epochs: number of epochs to run the training """ # Hyperparameters self.learning_rate = 0.0001 self.epochs = epochs self.keep_prob = 0.9 self.saver = None self.save_path = "./trained_networks/edge_classification_small" self.frames = None # will turn into np.array after pre_process self.labels = None # will turn into np.array after pre_process self.frame_shape = frame_shape self.batch_size = 40 self.frame_label_queue = [] self.trained = trained # pre-process frames self.pre_process(good_dir, bad_dir) # train network if not trained if not self.trained: self.train_network() def run(self, frames): test_frames = np.float32(frames) self.run_network(test_frames) def normalize(self, frame): filter_frame = np.zeros(list(self.frame_shape)) for c in range(3): filter_frame[:, :, c] = frame[:, :, c] / 255 return filter_frame def pre_process(self, dir_good, dir_bad): frames_and_labels = [] for entry in os.listdir(dir_good): path = "%s/%s" % (dir_good, entry) frames_and_labels.append([path, 1]) for entry in os.listdir(dir_bad): path = "%s/%s" % (dir_bad, entry) frames_and_labels.append([path, 0]) np.random.seed(1) shuffled = np.array(frames_and_labels) np.random.shuffle(shuffled) self.frame_label_queue = shuffled.tolist() def process(self, frames_and_labels): """ Normalizes the frame through with respect to each channel :param frames_and_labels: list with frames and labels :return: list which can easily be put into tf.placeholder object """ #shuffle the frames self.frames = None self.labels = None # normalize the frame frames = [] labels = [] for frame_and_label in frames_and_labels: frame = frame_and_label[0] label = [frame_and_label[1]] frame = cv2.imread(frame) if frame.shape == self.frame_shape: frame = self.normalize(frame) frames.append(frame) labels.append(label) self.frames = np.float32(frames) self.labels = np.float32(labels) def conv2d(self, x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides): """ Apply convolution then max pooling to x_tensor :param x_tensor: TensorFlow Tensor :param conv_num_outputs: Number of outputs for the convolutional layer :param conv_ksize: kernal size 2-D Tuple for the convolutional layer :param conv_strides: Stride 2-D Tuple for convolution :param pool_ksize: kernal size 2-D Tuple for pool :param pool_strides: Stride 2-D Tuple for pool : return: A tensor that represents convolution and max pooling of x_tensor """ # define strides, W, and b depth_original = x_tensor.get_shape().as_list()[3] conv_strides = [1] + list(conv_strides) + [1] W_shape = list(conv_ksize) + [depth_original] + [conv_num_outputs] W1 = tf.Variable(tf.truncated_normal(W_shape, stddev=0.01)) b1 = tf.Variable(tf.truncated_normal([conv_num_outputs], stddev=0.01)) # apply a convolution x = tf.nn.conv2d(x_tensor, W1, strides=conv_strides, padding='SAME') x = tf.nn.bias_add(x, b1) x = tf.nn.relu(x) # define max_strides, ksize_shape pool_strides = [1] + list(pool_strides) + [1] pool_ksize = [1] + list(pool_ksize) + [1] x = tf.nn.max_pool(x, ksize=pool_ksize, strides=pool_strides, padding='SAME') return x def create_batches(self, batch_size): pass def fully_connected(self, x_tensor, num_outputs): """ Creates a fully connected neural network layer :param x_tensor: input tensor :param num_outputs: number of outputs :return: output of a fully connected layer """ return tf.contrib.layers.fully_connected(inputs=x_tensor, num_outputs=num_outputs, activation_fn=tf.sigmoid) def output_layer(self, x_tensor, num_outputs): return tf.contrib.layers.fully_connected(inputs=x_tensor, num_outputs=num_outputs, activation_fn=None) def train_network(self): """ trains a network with preprocessed data """ tf.reset_default_graph() tf.set_random_seed(1) x = tf.placeholder(tf.float32, shape=[None] + list(self.frame_shape), name="input") y = tf.placeholder(tf.float32, shape=[None, 1] , name="y") keep_prob = tf.placeholder(tf.float32, name="keep_prob") # Convolution # output = self.conv2d(x, 32, (3, 3), (1, 1), (2,2), (2,2)) # output = self.conv2d(output, 64, (3, 3), (1, 1), (2, 2), (2, 2)) output = self.conv2d(x, 5, (3, 3), (1, 1), (2, 2), (2, 2)) output = self.conv2d(output, 10, (3, 3), (2, 2), (2, 2), (2, 2)) output = tf.nn.dropout(output, keep_prob) output = tf.contrib.layers.flatten(output) # Fully Connected Layer output = self.fully_connected(output, 15) output = self.fully_connected(output, 1) output = tf.identity(output, name="output") # cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=output, labels=y)) error = tf.subtract(y, output) cost = tf.reduce_mean(tf.square(error)) optimizer = tf.train.AdamOptimizer(self.learning_rate).minimize(cost) # init = tf.global_variables_initializer() if not self.trained: with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print("Number of epochs: %s" % (self.epochs)) number_batches = int(len(self.frame_label_queue) / self.batch_size) print("Number of batches: %s" % (number_batches)) data_size = len(self.frame_label_queue) repeat_size = 3 for _ in range(repeat_size): batch_init = 0 batch_end = self.batch_size for batch in range(number_batches): # for train_frame, train_label in zip(train_frames, train_labels): if data_size - batch_init < self.batch_size: batch_end = data_size if batch_end - batch_init == 0: break print(len(self.frame_label_queue[batch_init:batch_end])) self.process(self.frame_label_queue[batch_init:batch_end]) print("----- Batch %s -----" % (batch+1)) for epoch in range(self.epochs): sess.run(optimizer, feed_dict={x:self.frames, y:self.labels, keep_prob:self.keep_prob, }) print("Epoch: %s Error: %s" % (epoch, sess.run(cost, feed_dict={x:self.frames, y:self.labels, keep_prob: self.keep_prob, }))) batch_init += self.batch_size batch_end += self.batch_size # Save Model self.saver = tf.train.Saver() self.saver.save(sess, self.save_path) self.trained = True def run_network(self, test_frame): frames = np.resize(test_frame, tuple([1] + list(self.frame_shape))) # tf.reset_default_graph() loaded_graph = tf.Graph() with tf.Session(graph=loaded_graph) as sess: # Load model loader = tf.train.import_meta_graph(self.save_path + '.meta') loader.restore(sess, self.save_path) # load tensors loaded_x = loaded_graph.get_tensor_by_name('input:0') loaded_keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0') loaded_output = loaded_graph.get_tensor_by_name('output:0') value = sess.run(loaded_output, feed_dict={loaded_x: frames, loaded_keep_prob: 1.0}) return value #TODO: Implement retrain function for training on the go
import tensorflow as tf import time import numpy as np import mdl_data import sys GPUNUM = sys.argv[1] FILEPATH = sys.argv[2] # Network Parameters learning_rate = 0.001 training_epochs = 20 batch_size = 256 display_step = 1 n_input_img = 4096 # YLI_MED image data input (data shape: 4096, fc7 layer output) n_hidden_1_img = 1000 # 1st layer num features 1000 n_hidden_2_img = 600 # 2nd layer num features 600 n_input_aud = 2000 # YLI_MED audio data input (data shape: 2000, mfcc output) n_hidden_1_aud = 1000 # 1st layer num features 1000 n_hidden_2_aud = 600 # 2nd layer num features 600 n_hidden_1_in = 600 n_hidden_1_out = 256 n_hidden_2_out = 128 n_classes = 10 # YLI_MED total classes (0-9 digits) dropout = 0.75 with tf.device('/gpu:' + GPUNUM): #-------------------------------Struct Graph # tf Graph input x_aud = tf.placeholder("float", [None, n_input_aud]) x_img = tf.placeholder("float", [None, n_input_img]) y = tf.placeholder("float", [None, n_classes]) keep_prob = tf.placeholder(tf.float32) #dropout (keep probability) keep_tr = tf.placeholder(tf.float32) def calculatCA(_tp1, _tp2, size, _b_size): first = True tp1 = tf.split(0, _b_size, _tp1) tp2 = tf.split(0, _b_size, _tp2) for i in range(_b_size): input1 = tf.reshape(tp1[i], shape=[size, 1]) input2 = tf.reshape(tp2[i], shape=[size, 1]) upper = tf.matmul(tf.transpose(tf.sub(input1, tf.reduce_mean(input1))), tf.sub(input2, tf.reduce_mean(input2))) _tp1 = tf.reduce_sum(tf.mul(tf.sub(input1, tf.reduce_mean(input1)), tf.sub(input1, tf.reduce_mean(input1)))) _tp2 = tf.reduce_sum(tf.mul(tf.sub(input2, tf.reduce_mean(input2)), tf.sub(input2, tf.reduce_mean(input2)))) down = tf.sqrt(tf.mul(_tp1, _tp2)) factor = tf.abs(tf.div(upper, down)) if first: output = factor first = False else: output = tf.concat(1, [output, factor]) return tf.transpose(output) # Create model def multilayer_perceptron(_X_aud, _X_img, _w_aud, _b_aud, _w_img, _b_img, _w_out, _b_out, _dropout, _b_size): #aud aud_layer_1 = tf.nn.relu(tf.add(tf.matmul(_X_aud, _w_aud['h1']), _b_aud['b1'])) #Hidden layer with RELU activation aud_layer_2 = tf.nn.relu(tf.add(tf.matmul(aud_layer_1, _w_aud['h2']), _b_aud['b2'])) #Hidden layer with RELU activation #aud_out = tf.matmul(aud_layer_2, _w_aud['out']) + _b_aud['out'] #Image img_layer_1 = tf.nn.relu(tf.add(tf.matmul(_X_img, _w_img['h1']), _b_img['b1'])) #Hidden layer with RELU activation drop_1 = tf.nn.dropout(img_layer_1, _dropout) img_layer_2 = tf.nn.relu(tf.add(tf.matmul(drop_1, _w_img['h2']), _b_img['b2'])) #Hidden layer with RELU activation drop_2 = tf.nn.dropout(img_layer_2, _dropout) #img_out = tf.matmul(drop_2, _w_img['out']) + _b_img['out'] ''' Merge with CA ''' factor = calculatCA(aud_layer_2, drop_2, 600, _b_size) factor = tf.reshape(tf.diag(factor), shape=[_b_size, _b_size]) merge_sum = tf.add(aud_layer_2, drop_2) facmat = tf.nn.relu(tf.matmul(factor, merge_sum)) #out_drop = tf.nn.dropout(merge_sum, _dropout) out_layer_1 = tf.nn.relu(tf.add(tf.matmul(facmat, _w_out['h1']), _b_out['b1'])) #Hidden layer with RELU activation out_layer_2 = tf.nn.relu(tf.add(tf.matmul(out_layer_1, _w_out['h2']), _b_out['b2'])) #Hidden layer with RELU activation #return out_drop return tf.matmul(out_layer_2, _w_out['out']) + _b_out['out'] # Store layers weight & bias w_out = { 'h1': tf.Variable(tf.random_normal([n_hidden_1_in, n_hidden_1_out])), 'h2': tf.Variable(tf.random_normal([n_hidden_1_out, n_hidden_2_out])), 'out': tf.Variable(tf.random_normal([n_hidden_2_out, n_classes])) } b_out = { 'b1': tf.Variable(tf.random_normal([n_hidden_1_out])), 'b2': tf.Variable(tf.random_normal([n_hidden_2_out])), 'out': tf.Variable(tf.random_normal([n_classes])) } w_aud = { 'h1': tf.Variable(tf.random_normal([n_input_aud, n_hidden_1_aud])), 'h2': tf.Variable(tf.random_normal([n_hidden_1_aud, n_hidden_2_aud])), 'out': tf.Variable(tf.random_normal([n_hidden_2_aud, n_classes])) } b_aud = { 'b1': tf.Variable(tf.random_normal([n_hidden_1_aud])), 'b2': tf.Variable(tf.random_normal([n_hidden_2_aud])), 'out': tf.Variable(tf.random_normal([n_classes])) } w_img = { 'h1': tf.Variable(tf.random_normal([n_input_img, n_hidden_1_img])), 'h2': tf.Variable(tf.random_normal([n_hidden_1_img, n_hidden_2_img])), 'out': tf.Variable(tf.random_normal([n_hidden_2_img, n_classes])) } b_img = { 'b1': tf.Variable(tf.random_normal([n_hidden_1_img])), 'b2': tf.Variable(tf.random_normal([n_hidden_2_img])), 'out': tf.Variable(tf.random_normal([n_classes])) } # Construct model pred = multilayer_perceptron(x_aud, x_img, w_aud, b_aud, w_img, b_img, w_out, b_out, keep_prob, batch_size) # Define loss and optimizer cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) # Softmax loss optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Adam Optimizer # Initializing the variables init = tf.initialize_all_variables() #-------------------------------Load data #Source reference: https://github.com/aymericdamien/TensorFlow-Examples.git/input_data.py def dense_to_one_hot(labels_dense, num_classes=10): """Convert class labels from scalars to one-hot vectors.""" num_labels = labels_dense.shape[0] index_offset = np.arange(num_labels) * num_classes labels_one_hot = np.zeros((num_labels, num_classes)) labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 return labels_one_hot # Load data data = mdl_data.YLIMED('YLIMED_info.csv', FILEPATH + '/YLIMED150924/audio/mfcc20', FILEPATH + '/YLIMED150924/keyframe/fc7') X_img_train = data.get_img_X_train() X_aud_train = data.get_aud_X_train() y_train = data.get_y_train() Y_train = dense_to_one_hot(y_train) # Shuffle initial data p = np.random.permutation(len(Y_train)) X_img_train = X_img_train[p] X_aud_train = X_aud_train[p] Y_train = Y_train[p] # Load test data X_img_test = data.get_img_X_test() X_aud_test = data.get_aud_X_test() y_test = data.get_y_test() Y_test = dense_to_one_hot(y_test) #-------------------------------Launch the graph with tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True)) as sess: sess.run(init) #Training cycle for epoch in range(training_epochs): avg_cost = 0. total_batch = int(len(Y_train)/batch_size) #Loop oveer all batches for i in range(total_batch): batch_x_aud, batch_x_img, batch_ys, finish = data.next_batch_multi(X_aud_train, X_img_train, Y_train, batch_size, len(Y_train)) # Fit traning using batch data sess.run(optimizer, feed_dict = {x_aud: batch_x_aud, x_img: batch_x_img, y: batch_ys, keep_prob: dropout}) # Compute average loss avg_cost += sess.run(cost, feed_dict = {x_aud: batch_x_aud, x_img: batch_x_img, y: batch_ys, keep_prob: 1.}) / total_batch #Shuffling if finish: p = np.random.permutation(len(Y_train)) X_aud_train = X_aud_train[p] X_img_train = X_img_train[p] Y_train = Y_train[p] # Display logs per epoch step if epoch % display_step == 0: print "Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost) print "Optimization Finished!" # Test model batch_size = 1 pred = multilayer_perceptron(x_aud, x_img, w_aud, b_aud, w_img, b_img, w_out, b_out, keep_prob, batch_size) correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) test = tf.reduce_sum(tf.cast(correct_prediction, "float")) total = 0 correct = 0 for i in range(int(len(Y_test)/batch_size)): total += batch_size batch_x_aud, batch_x_img, batch_ys, finish = data.next_batch_multi(X_aud_test, X_img_test, Y_test, batch_size, len(Y_test)) correct += test.eval({x_aud: batch_x_aud, x_img: batch_x_img, y: batch_ys, keep_prob: 1.}) print int(len(Y_test)/batch_size) print correct print total print float(correct/total) print 'MM1CA.py' # Calculate accuracy #accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) #for epoch in range(Y_test): # print "Accuracy:", accuracy.eval({x_aud: X_aud_test, x_img: X_img_test, y: Y_test, keep_prob: 1.})