gt
stringclasses
1 value
context
stringlengths
2.49k
119k
from __future__ import absolute_import import sys import unicodedata import six """ Client to pyros node, Python style. Required for multiprocess communication. """ # When importing this your environment should already be setup # and pyzmp should be found (from ROS packages or from python packages) import pyzmp from pyros_common.exceptions import PyrosException # TODO : Requirement : Check TOTAL send/receive SYMMETRY. # If needed get rid of **kwargs arguments in call. Makes the interface less obvious and can trap unaware devs. class PyrosServiceNotFound(PyrosException): def __init__(self, message): super(PyrosServiceNotFound, self).__init__(message) # CAREFUL : exceptions must be pickleable ( we need to pass all arguments to the superclass ) class PyrosServiceTimeout(PyrosException): def __init__(self, message): super(PyrosServiceTimeout, self).__init__(message) # TODO : provide a test client ( similar to what werkzeug/flask does ) # The goal is to make it easy for users of pyros to test and validate their library only against the client, # without having to have all the ROS environment installed and setup, and running extra processing # just for unit testing... class PyrosClient(object): # TODO : improve ZMP to return the socket_bind address to point to the exact IPC/socket channel. # And pass it here, instead of assuming node name is unique... def __init__(self, node_name=None): # Link to only one Server self.node_name = node_name # Discover all Services. Wait for at least one, and make sure it s provided by our expected Server self.msg_build_svc = pyzmp.Service.discover('msg_build', 5) if self.msg_build_svc is None or ( self.node_name is not None and self.node_name not in [p[0] for p in self.msg_build_svc.providers] ): raise PyrosServiceNotFound('msg_build') self.setup_svc = pyzmp.Service.discover('setup', 5) if self.setup_svc is None or ( self.node_name is not None and self.node_name not in [p[0] for p in self.setup_svc.providers] ): raise PyrosServiceNotFound('setup') self.topic_svc = pyzmp.Service.discover('topic', 5) if self.topic_svc is None or ( self.node_name is not None and self.node_name not in [p[0] for p in self.topic_svc.providers] ): raise PyrosServiceNotFound('topic') self.service_svc = pyzmp.Service.discover('service', 5) if self.service_svc is None or ( self.node_name is not None and self.node_name not in [p[0] for p in self.service_svc.providers] ): raise PyrosServiceNotFound('service') self.param_svc = pyzmp.Service.discover('param', 5) if self.param_svc is None or ( self.node_name is not None and self.node_name not in [p[0] for p in self.param_svc.providers] ): raise PyrosServiceNotFound('param') self.topics_svc = pyzmp.Service.discover('topics', 5) if self.topics_svc is None or ( self.node_name is not None and self.node_name not in [p[0] for p in self.topics_svc.providers] ): raise PyrosServiceNotFound('topics') self.services_svc = pyzmp.Service.discover('services', 5) if self.services_svc is None or ( self.node_name is not None and self.node_name not in [p[0] for p in self.services_svc.providers] ): raise PyrosServiceNotFound('services') self.params_svc = pyzmp.Service.discover('params', 5) if self.params_svc is None or ( self.node_name is not None and self.node_name not in [p[0] for p in self.params_svc.providers] ): raise PyrosServiceNotFound('params') def buildMsg(self, connection_name, suffix=None): #changing unicode to string ( testing stability of multiprocess debugging ) if isinstance(connection_name, unicode): connection_name = unicodedata.normalize('NFKD', connection_name).encode('ascii', 'ignore') res = self.msg_build_svc.call(args=(connection_name,)) return res def topic_inject(self, topic_name, _msg_content=None, **kwargs): """ Injecting message into topic. if _msg_content, we inject it directly. if not, we use all extra kwargs :param topic_name: name of the topic :param _msg_content: optional message content :param kwargs: each extra kwarg will be put int he message is structure matches :return: """ #changing unicode to string ( testing stability of multiprocess debugging ) if isinstance(topic_name, unicode): topic_name = unicodedata.normalize('NFKD', topic_name).encode('ascii', 'ignore') if _msg_content is not None: # logging.warn("injecting {msg} into {topic}".format(msg=_msg_content, topic=topic_name)) res = self.topic_svc.call(args=(topic_name, _msg_content,)) else: # default kwargs is {} # logging.warn("injecting {msg} into {topic}".format(msg=kwargs, topic=topic_name)) res = self.topic_svc.call(args=(topic_name, kwargs,)) return res is None # check if message has been consumed def topic_extract(self, topic_name): #changing unicode to string ( testing stability of multiprocess debugging ) if isinstance(topic_name, unicode): topic_name = unicodedata.normalize('NFKD', topic_name).encode('ascii', 'ignore') try: res = self.topic_svc.call(args=(topic_name, None,)) except pyzmp.service.ServiceCallTimeout as exc: six.reraise(PyrosServiceTimeout("Pyros Service call timed out."), None, sys.exc_info()[2]) # TODO : if topic_name not exposed, we get None as res. # We should improve that behavior (display warning ? allow auto -dynamic- expose ?) return res def service_call(self, service_name, _msg_content=None, **kwargs): #changing unicode to string ( testing stability of multiprocess debugging ) if isinstance(service_name, unicode): service_name = unicodedata.normalize('NFKD', service_name).encode('ascii', 'ignore') try: if _msg_content is not None: res = self.service_svc.call(args=(service_name, _msg_content,)) else: # default kwargs is {} res = self.service_svc.call(args=(service_name, kwargs,)) except pyzmp.service.ServiceCallTimeout as exc: six.reraise(PyrosServiceTimeout("Pyros Service call timed out."), None, sys.exc_info()[2]) # A service that doesn't exist on the node will return res_content.resp_content None. # It should probably except... # TODO : improve error handling, maybe by checking the type of res ? return res def param_set(self, param_name, _value=None, **kwargs): """ Setting parameter. if _value, we inject it directly. if not, we use all extra kwargs :param topic_name: name of the topic :param _value: optional value :param kwargs: each extra kwarg will be put in the value if structure matches :return: """ #changing unicode to string ( testing stability of multiprocess debugging ) if isinstance(param_name, unicode): param_name = unicodedata.normalize('NFKD', param_name).encode('ascii', 'ignore') _value = _value or {} if kwargs: res = self.param_svc.call(args=(param_name, kwargs,)) elif _value is not None: res = self.param_svc.call(args=(param_name, _value,)) else: # if _msg_content is None the request is invalid. # just return something to mean False. res = 'WRONG SET' return res is None # check if message has been consumed def param_get(self, param_name): #changing unicode to string ( testing stability of multiprocess debugging ) if isinstance(param_name, unicode): param_name = unicodedata.normalize('NFKD', param_name).encode('ascii', 'ignore') res = self.param_svc.call(args=(param_name, None,)) return res def topics(self): try: res = self.topics_svc.call(send_timeout=5000, recv_timeout=10000) # Need to be generous on timeout in case we are starting up multiprocesses except pyzmp.service.ServiceCallTimeout as exc: six.reraise(PyrosServiceTimeout("Pyros Service call timed out."), None, sys.exc_info()[2]) return res def services(self): try: res = self.services_svc.call(send_timeout=5000, recv_timeout=10000) # Need to be generous on timeout in case we are starting up multiprocesses except pyzmp.service.ServiceCallTimeout as exc: six.reraise(PyrosServiceTimeout("Pyros Service call timed out."), None, sys.exc_info()[2]) return res def params(self): res = self.params_svc.call(send_timeout=5000, recv_timeout=10000) # Need to be generous on timeout in case we are starting up multiprocesses return res def setup(self, publishers=None, subscribers=None, services=None, params=None): #, enable_cache=False): res = self.setup_svc.call(kwargs={ 'publishers': publishers, 'subscribers': subscribers, 'services': services, 'params': params, #'enable_cache': enable_cache, # TODO : CAREFUL : check if we can actually enable the cache dynamically ? }, send_timeout=5000, recv_timeout=10000) # Need to be generous on timeout in case we are starting up multiprocesses return res #def listacts(self): # return {} # def namespaces(self): # res = self.namespaces_svc.call(args=({},)) # return res # def interactions(self): # res = self.interactions_svc.call(args=({},)) # return res # def interaction(self, name): # res = self.interaction_svc.call(args=("",)) # return res # def has_rocon(self): # res = self.has_rocon_svc.call(args=(False,)) # return res # TODO : test client with Rostful Node ( and detect ROS or not to confirm behvior )
#!/usr/bin/env python '''Event constants from /usr/include/linux/input.h ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' EV_SYN = 0x00 EV_KEY = 0x01 EV_REL = 0x02 EV_ABS = 0x03 EV_MSC = 0x04 EV_LED = 0x11 EV_SND = 0x12 EV_REP = 0x14 EV_FF = 0x15 EV_PWR = 0x16 EV_FF_STATUS = 0x17 EV_MAX = 0x1f # Synchronization events. SYN_REPORT = 0 SYN_CONFIG = 1 # Keys and buttons KEY_RESERVED = 0 KEY_ESC = 1 KEY_1 = 2 KEY_2 = 3 KEY_3 = 4 KEY_4 = 5 KEY_5 = 6 KEY_6 = 7 KEY_7 = 8 KEY_8 = 9 KEY_9 = 10 KEY_0 = 11 KEY_MINUS = 12 KEY_EQUAL = 13 KEY_BACKSPACE = 14 KEY_TAB = 15 KEY_Q = 16 KEY_W = 17 KEY_E = 18 KEY_R = 19 KEY_T = 20 KEY_Y = 21 KEY_U = 22 KEY_I = 23 KEY_O = 24 KEY_P = 25 KEY_LEFTBRACE = 26 KEY_RIGHTBRACE = 27 KEY_ENTER = 28 KEY_LEFTCTRL = 29 KEY_A = 30 KEY_S = 31 KEY_D = 32 KEY_F = 33 KEY_G = 34 KEY_H = 35 KEY_J = 36 KEY_K = 37 KEY_L = 38 KEY_SEMICOLON = 39 KEY_APOSTROPHE = 40 KEY_GRAVE = 41 KEY_LEFTSHIFT = 42 KEY_BACKSLASH = 43 KEY_Z = 44 KEY_X = 45 KEY_C = 46 KEY_V = 47 KEY_B = 48 KEY_N = 49 KEY_M = 50 KEY_COMMA = 51 KEY_DOT = 52 KEY_SLASH = 53 KEY_RIGHTSHIFT = 54 KEY_KPASTERISK = 55 KEY_LEFTALT = 56 KEY_SPACE = 57 KEY_CAPSLOCK = 58 KEY_F1 = 59 KEY_F2 = 60 KEY_F3 = 61 KEY_F4 = 62 KEY_F5 = 63 KEY_F6 = 64 KEY_F7 = 65 KEY_F8 = 66 KEY_F9 = 67 KEY_F10 = 68 KEY_NUMLOCK = 69 KEY_SCROLLLOCK = 70 KEY_KP7 = 71 KEY_KP8 = 72 KEY_KP9 = 73 KEY_KPMINUS = 74 KEY_KP4 = 75 KEY_KP5 = 76 KEY_KP6 = 77 KEY_KPPLUS = 78 KEY_KP1 = 79 KEY_KP2 = 80 KEY_KP3 = 81 KEY_KP0 = 82 KEY_KPDOT = 83 KEY_ZENKAKUHANKAKU = 85 KEY_102ND = 86 KEY_F11 = 87 KEY_F12 = 88 KEY_RO = 89 KEY_KATAKANA = 90 KEY_HIRAGANA = 91 KEY_HENKAN = 92 KEY_KATAKANAHIRAGANA = 93 KEY_MUHENKAN = 94 KEY_KPJPCOMMA = 95 KEY_KPENTER = 96 KEY_RIGHTCTRL = 97 KEY_KPSLASH = 98 KEY_SYSRQ = 99 KEY_RIGHTALT = 100 KEY_LINEFEED = 101 KEY_HOME = 102 KEY_UP = 103 KEY_PAGEUP = 104 KEY_LEFT = 105 KEY_RIGHT = 106 KEY_END = 107 KEY_DOWN = 108 KEY_PAGEDOWN = 109 KEY_INSERT = 110 KEY_DELETE = 111 KEY_MACRO = 112 KEY_MUTE = 113 KEY_VOLUMEDOWN = 114 KEY_VOLUMEUP = 115 KEY_POWER = 116 KEY_KPEQUAL = 117 KEY_KPPLUSMINUS = 118 KEY_PAUSE = 119 KEY_KPCOMMA = 121 KEY_HANGUEL = 122 KEY_HANJA = 123 KEY_YEN = 124 KEY_LEFTMETA = 125 KEY_RIGHTMETA = 126 KEY_COMPOSE = 127 KEY_STOP = 128 KEY_AGAIN = 129 KEY_PROPS = 130 KEY_UNDO = 131 KEY_FRONT = 132 KEY_COPY = 133 KEY_OPEN = 134 KEY_PASTE = 135 KEY_FIND = 136 KEY_CUT = 137 KEY_HELP = 138 KEY_MENU = 139 KEY_CALC = 140 KEY_SETUP = 141 KEY_SLEEP = 142 KEY_WAKEUP = 143 KEY_FILE = 144 KEY_SENDFILE = 145 KEY_DELETEFILE = 146 KEY_XFER = 147 KEY_PROG1 = 148 KEY_PROG2 = 149 KEY_WWW = 150 KEY_MSDOS = 151 KEY_COFFEE = 152 KEY_DIRECTION = 153 KEY_CYCLEWINDOWS = 154 KEY_MAIL = 155 KEY_BOOKMARKS = 156 KEY_COMPUTER = 157 KEY_BACK = 158 KEY_FORWARD = 159 KEY_CLOSECD = 160 KEY_EJECTCD = 161 KEY_EJECTCLOSECD = 162 KEY_NEXTSONG = 163 KEY_PLAYPAUSE = 164 KEY_PREVIOUSSONG = 165 KEY_STOPCD = 166 KEY_RECORD = 167 KEY_REWIND = 168 KEY_PHONE = 169 KEY_ISO = 170 KEY_CONFIG = 171 KEY_HOMEPAGE = 172 KEY_REFRESH = 173 KEY_EXIT = 174 KEY_MOVE = 175 KEY_EDIT = 176 KEY_SCROLLUP = 177 KEY_SCROLLDOWN = 178 KEY_KPLEFTPAREN = 179 KEY_KPRIGHTPAREN = 180 KEY_F13 = 183 KEY_F14 = 184 KEY_F15 = 185 KEY_F16 = 186 KEY_F17 = 187 KEY_F18 = 188 KEY_F19 = 189 KEY_F20 = 190 KEY_F21 = 191 KEY_F22 = 192 KEY_F23 = 193 KEY_F24 = 194 KEY_PLAYCD = 200 KEY_PAUSECD = 201 KEY_PROG3 = 202 KEY_PROG4 = 203 KEY_SUSPEND = 205 KEY_CLOSE = 206 KEY_PLAY = 207 KEY_FASTFORWARD = 208 KEY_BASSBOOST = 209 KEY_PRINT = 210 KEY_HP = 211 KEY_CAMERA = 212 KEY_SOUND = 213 KEY_QUESTION = 214 KEY_EMAIL = 215 KEY_CHAT = 216 KEY_SEARCH = 217 KEY_CONNECT = 218 KEY_FINANCE = 219 KEY_SPORT = 220 KEY_SHOP = 221 KEY_ALTERASE = 222 KEY_CANCEL = 223 KEY_BRIGHTNESSDOWN = 224 KEY_BRIGHTNESSUP = 225 KEY_MEDIA = 226 KEY_UNKNOWN = 240 BTN_MISC = 0x100 BTN_0 = 0x100 BTN_1 = 0x101 BTN_2 = 0x102 BTN_3 = 0x103 BTN_4 = 0x104 BTN_5 = 0x105 BTN_6 = 0x106 BTN_7 = 0x107 BTN_8 = 0x108 BTN_9 = 0x109 BTN_MOUSE = 0x110 BTN_LEFT = 0x110 BTN_RIGHT = 0x111 BTN_MIDDLE = 0x112 BTN_SIDE = 0x113 BTN_EXTRA = 0x114 BTN_FORWARD = 0x115 BTN_BACK = 0x116 BTN_TASK = 0x117 BTN_JOYSTICK = 0x120 BTN_TRIGGER = 0x120 BTN_THUMB = 0x121 BTN_THUMB2 = 0x122 BTN_TOP = 0x123 BTN_TOP2 = 0x124 BTN_PINKIE = 0x125 BTN_BASE = 0x126 BTN_BASE2 = 0x127 BTN_BASE3 = 0x128 BTN_BASE4 = 0x129 BTN_BASE5 = 0x12a BTN_BASE6 = 0x12b BTN_DEAD = 0x12f BTN_GAMEPAD = 0x130 BTN_A = 0x130 BTN_B = 0x131 BTN_C = 0x132 BTN_X = 0x133 BTN_Y = 0x134 BTN_Z = 0x135 BTN_TL = 0x136 BTN_TR = 0x137 BTN_TL2 = 0x138 BTN_TR2 = 0x139 BTN_SELECT = 0x13a BTN_START = 0x13b BTN_MODE = 0x13c BTN_THUMBL = 0x13d BTN_THUMBR = 0x13e BTN_DIGI = 0x140 BTN_TOOL_PEN = 0x140 BTN_TOOL_RUBBER = 0x141 BTN_TOOL_BRUSH = 0x142 BTN_TOOL_PENCIL = 0x143 BTN_TOOL_AIRBRUSH = 0x144 BTN_TOOL_FINGER = 0x145 BTN_TOOL_MOUSE = 0x146 BTN_TOOL_LENS = 0x147 BTN_TOUCH = 0x14a BTN_STYLUS = 0x14b BTN_STYLUS2 = 0x14c BTN_TOOL_DOUBLETAP = 0x14d BTN_TOOL_TRIPLETAP = 0x14e BTN_WHEEL = 0x150 BTN_GEAR_DOWN = 0x150 BTN_GEAR_UP = 0x151 KEY_OK = 0x160 KEY_SELECT = 0x161 KEY_GOTO = 0x162 KEY_CLEAR = 0x163 KEY_POWER2 = 0x164 KEY_OPTION = 0x165 KEY_INFO = 0x166 KEY_TIME = 0x167 KEY_VENDOR = 0x168 KEY_ARCHIVE = 0x169 KEY_PROGRAM = 0x16a KEY_CHANNEL = 0x16b KEY_FAVORITES = 0x16c KEY_EPG = 0x16d KEY_PVR = 0x16e KEY_MHP = 0x16f KEY_LANGUAGE = 0x170 KEY_TITLE = 0x171 KEY_SUBTITLE = 0x172 KEY_ANGLE = 0x173 KEY_ZOOM = 0x174 KEY_MODE = 0x175 KEY_KEYBOARD = 0x176 KEY_SCREEN = 0x177 KEY_PC = 0x178 KEY_TV = 0x179 KEY_TV2 = 0x17a KEY_VCR = 0x17b KEY_VCR2 = 0x17c KEY_SAT = 0x17d KEY_SAT2 = 0x17e KEY_CD = 0x17f KEY_TAPE = 0x180 KEY_RADIO = 0x181 KEY_TUNER = 0x182 KEY_PLAYER = 0x183 KEY_TEXT = 0x184 KEY_DVD = 0x185 KEY_AUX = 0x186 KEY_MP3 = 0x187 KEY_AUDIO = 0x188 KEY_VIDEO = 0x189 KEY_DIRECTORY = 0x18a KEY_LIST = 0x18b KEY_MEMO = 0x18c KEY_CALENDAR = 0x18d KEY_RED = 0x18e KEY_GREEN = 0x18f KEY_YELLOW = 0x190 KEY_BLUE = 0x191 KEY_CHANNELUP = 0x192 KEY_CHANNELDOWN = 0x193 KEY_FIRST = 0x194 KEY_LAST = 0x195 KEY_AB = 0x196 KEY_NEXT = 0x197 KEY_RESTART = 0x198 KEY_SLOW = 0x199 KEY_SHUFFLE = 0x19a KEY_BREAK = 0x19b KEY_PREVIOUS = 0x19c KEY_DIGITS = 0x19d KEY_TEEN = 0x19e KEY_TWEN = 0x19f KEY_DEL_EOL = 0x1c0 KEY_DEL_EOS = 0x1c1 KEY_INS_LINE = 0x1c2 KEY_DEL_LINE = 0x1c3 KEY_FN = 0x1d0 KEY_FN_ESC = 0x1d1 KEY_FN_F1 = 0x1d2 KEY_FN_F2 = 0x1d3 KEY_FN_F3 = 0x1d4 KEY_FN_F4 = 0x1d5 KEY_FN_F5 = 0x1d6 KEY_FN_F6 = 0x1d7 KEY_FN_F7 = 0x1d8 KEY_FN_F8 = 0x1d9 KEY_FN_F9 = 0x1da KEY_FN_F10 = 0x1db KEY_FN_F11 = 0x1dc KEY_FN_F12 = 0x1dd KEY_FN_1 = 0x1de KEY_FN_2 = 0x1df KEY_FN_D = 0x1e0 KEY_FN_E = 0x1e1 KEY_FN_F = 0x1e2 KEY_FN_S = 0x1e3 KEY_FN_B = 0x1e4 KEY_MAX = 0x1ff # Relative axes REL_X = 0x00 REL_Y = 0x01 REL_Z = 0x02 REL_RX = 0x03 REL_RY = 0x04 REL_RZ = 0x05 REL_HWHEEL = 0x06 REL_DIAL = 0x07 REL_WHEEL = 0x08 REL_MISC = 0x09 REL_MAX = 0x0f # Absolute axes ABS_X = 0x00 ABS_Y = 0x01 ABS_Z = 0x02 ABS_RX = 0x03 ABS_RY = 0x04 ABS_RZ = 0x05 ABS_THROTTLE = 0x06 ABS_RUDDER = 0x07 ABS_WHEEL = 0x08 ABS_GAS = 0x09 ABS_BRAKE = 0x0a ABS_HAT0X = 0x10 ABS_HAT0Y = 0x11 ABS_HAT1X = 0x12 ABS_HAT1Y = 0x13 ABS_HAT2X = 0x14 ABS_HAT2Y = 0x15 ABS_HAT3X = 0x16 ABS_HAT3Y = 0x17 ABS_PRESSURE = 0x18 ABS_DISTANCE = 0x19 ABS_TILT_X = 0x1a ABS_TILT_Y = 0x1b ABS_TOOL_WIDTH = 0x1c ABS_VOLUME = 0x20 ABS_MISC = 0x28 ABS_MAX = 0x3f # Misc events MSC_SERIAL = 0x00 MSC_PULSELED = 0x01 MSC_GESTURE = 0x02 MSC_RAW = 0x03 MSC_SCAN = 0x04 MSC_MAX = 0x07 # LEDs LED_NUML = 0x00 LED_CAPSL = 0x01 LED_SCROLLL = 0x02 LED_COMPOSE = 0x03 LED_KANA = 0x04 LED_SLEEP = 0x05 LED_SUSPEND = 0x06 LED_MUTE = 0x07 LED_MISC = 0x08 LED_MAIL = 0x09 LED_CHARGING = 0x0a LED_MAX = 0x0f # Autorepeat values REP_DELAY = 0x00 REP_PERIOD = 0x01 REP_MAX = 0x01 # Sounds SND_CLICK = 0x00 SND_BELL = 0x01 SND_TONE = 0x02 SND_MAX = 0x07 # IDs. ID_BUS = 0 ID_VENDOR = 1 ID_PRODUCT = 2 ID_VERSION = 3 BUS_PCI = 0x01 BUS_ISAPNP = 0x02 BUS_USB = 0x03 BUS_HIL = 0x04 BUS_BLUETOOTH = 0x05 BUS_ISA = 0x10 BUS_I8042 = 0x11 BUS_XTKBD = 0x12 BUS_RS232 = 0x13 BUS_GAMEPORT = 0x14 BUS_PARPORT = 0x15 BUS_AMIGA = 0x16 BUS_ADB = 0x17 BUS_I2C = 0x18 BUS_HOST = 0x19 # Values describing the status of an effect FF_STATUS_STOPPED = 0x00 FF_STATUS_PLAYING = 0x01 FF_STATUS_MAX = 0x01 _rel_raw_names = {} _abs_raw_names = {} _key_raw_names = {} for _name, _val in list(locals().copy().items()): if _name.startswith('REL_'): _rel_raw_names[_val] = _name elif _name.startswith('ABS_'): _abs_raw_names[_val] = _name elif _name.startswith('KEY_') or _name.startswith('BTN_'): _key_raw_names[_val] = _name
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """AutomaticControlDependencies and related functionality.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.eager import context from tensorflow.python.framework import dtypes as dtypes_module from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import control_flow_util from tensorflow.python.ops import tensor_array_ops from tensorflow.python.util import nest from tensorflow.python.util import tf_decorator # Op types that should not run in program order, e.g. because they need to run # asynchronously to avoid deadlock. ASYNC_STATEFUL_OPS = [ "CollectiveReduce", "CollectiveBcastSend", "CollectiveBcastRecv", "NcclAllReduce", ] class AutomaticControlDependencies(object): """Context manager to automatically add control dependencies. Code under this context manager will act as if a sensible set of control dependencies were present. More specifically: 1. All stateful ops in the scope will execute (with the exception of ops in ASYNC_STATEFUL_OPS) 2. Stateful ops which modify the same resource will execute in program order Note: creating variables in an automatic control dependencies context is not supported (the value of the variables will never change as they will keep getting reinitialized). NOT THREAD SAFE """ def __init__(self): self._returned_tensors = set() def mark_as_return(self, tensor): """Acts like identity but marks the `Tensor` as a return value. This will possibly return a copy of the `Tensor`. Usage: ``` with AutomaticControlDependencies() as a: ... t = a.mark_as_return(t) _ = ...(t...) # i.e. it's safe to use t here ``` Args: tensor: the `Tensor` to be marked Returns: a copy of the `Tensor`. """ if isinstance(tensor, ops.IndexedSlices): values = array_ops.identity(tensor.values) indices = array_ops.identity(tensor.indices) self._returned_tensors.add(indices) self._returned_tensors.add(values) return ops.IndexedSlices(values, indices, dense_shape=tensor.dense_shape) elif isinstance(tensor, sparse_tensor.SparseTensor): values = array_ops.identity(tensor.values) indices = array_ops.identity(tensor.indices) self._returned_tensors.add(indices) self._returned_tensors.add(values) return sparse_tensor.SparseTensor( indices, values, dense_shape=tensor.dense_shape) elif isinstance(tensor, tensor_array_ops.TensorArray): flow = array_ops.identity(tensor.flow) self._returned_tensors.add(flow) return tensor_array_ops.build_ta_with_new_flow(tensor, flow) # We want to make the return values depend on the stateful operations, but # we don't want to introduce a cycle, so we make the return value the result # of a new identity operation that the stateful operations definitely don't # depend on. tensor = array_ops.identity(tensor) self._returned_tensors.add(tensor) return tensor def __enter__(self): if context.executing_eagerly(): return self # This code assumes no other thread is adding ops to the graph while # we're adding ops to the graph. # TODO(apassos): Fix this by locking the graph or using a temporary # graph (but that would mess up devices and collections at least, # probably other things as well). self._graph = ops.get_default_graph() self._graph._add_control_dependencies = True # pylint: disable=protected-access self._n_operations = len(self._graph.get_operations()) return self def _process_switch(self, switch_op, ops_which_must_run, last_op_using_resource_tensor, merge_for_resource): """Processes a switch node for a resource input. When tensorflow creates a cond, it creates a control flow context for each branch of the cond. Each external tensor accessed by that branch is routed through a switch op, which gets created in the graph _after_ the op which uses that tensor get created. If the resource comes from another switch op we process that one first. _process_switch creates a corresponding merge node for the switch node. This merge node is added to the outer control flow context of the switch node. We also ensure that: 1. The switch node executes after the previous op which used the resource tensor 2. Any op which uses a resource output of the switch node executes before the merge for the switch node. 3. The next op which uses the input resource to the switch node (which might be another switch node for the other branch of the conditional) will execute after the merge node is done. 4. The merge node is marked as must_run so it will run even if no subsequent operation uses the resource. Args: switch_op: the switch op to be processed ops_which_must_run: the set of ops which must run last_op_using_resource_tensor: map from resource tensor to last op using it merge_for_resource: map from resource tensor to merge which must follow all usages of it. """ inp = switch_op.inputs[0] if inp.dtype == dtypes_module.resource and inp.op.type == "Switch": self._process_switch(inp.op, ops_which_must_run, last_op_using_resource_tensor, merge_for_resource) if switch_op.outputs[0] in merge_for_resource: return new_merge = control_flow_ops.merge(switch_op.outputs, name="artificial_merge") new_merge[0].op._control_flow_context = ( # pylint: disable=protected-access switch_op._control_flow_context.outer_context) # pylint: disable=protected-access # Ensures the merge always runs ops_which_must_run.add(new_merge[0].op) if inp in last_op_using_resource_tensor: # Ensures the switch executes after the previous op using the resource. switch_op._add_control_input(last_op_using_resource_tensor[inp]) # pylint: disable=protected-access # Ensure the next op outside the cond happens after the merge. last_op_using_resource_tensor[inp] = new_merge[0].op if inp in merge_for_resource: merge_for_resource[inp]._add_control_input(new_merge[0].op) # pylint: disable=protected-access for o in switch_op.outputs: # Ensures the merge will execute after all ops inside the cond merge_for_resource[o] = new_merge[0].op def __exit__(self, unused_type, unused_value, unused_traceback): if context.executing_eagerly(): return if self._graph is not ops.get_default_graph(): raise RuntimeError( "Graph changed while trying to add control dependencies.") # pylint: disable=protected-access if hasattr(self._graph, "outer_graph"): outer_val = self._graph.outer_graph._add_control_dependencies self._graph._add_control_dependencies = outer_val else: self._graph._add_control_dependencies = False # pylint: enable=protected-access # map from resource tensor to the last op which used it last_op_using_resource_tensor = {} # set of conditional and loop exits ops_which_must_run = set() # merge which must depend on ops which use this resource merge_for_resource = {} new_operations = self._graph.get_operations()[self._n_operations:] # Ensures that uses of resource tensors get serialized properly and all # execute. This is done by keeping a map from resource tensor to the last op # in graph-construction order which used it (last_op_using_resource_tensor). # # Conditionals are written in TensorFlow such that every external tensor # accessed in the conditional goes through a switch op and every return # tensor (it's guaranteed that there will be at least one) goes through a # merge op. # # To handle conditionals, switches are handled in a special way (see # comments for _process_switch). Merge nodes created by TF's conditional # logic (as opposed to by _process_switch) are forced to run and also get a # control dependency added to them to ensure all stateful ops inside their # control flow context run. # # We also ensure that if an op is using a resource output by a switch node # (that is, a resource tensor for which there's a value in # merge_for_resource) this op will run before the merge for that resource. # # We try to add control inputs to nodes respecting their control flow # contexts to avoid dead nodes propagating everywhere and leading to # "retval[0] doesn't have value" errors. If a node gets a control dependency # on a dead node (i.e. a note from an untaken control flow branch) that node # will be marked as dead unless it's a merge node. # # TODO(apassos): serialize non-resource-taking stateful ops as well, and # test that it works. Support while loops. Support init_scope escaping from # this. for op in new_operations: # TODO(apassos) make this code safely support while loops. if control_flow_util.IsInWhileLoop(op): continue control_inputs = set() # Ensure stateful ops run if (op.type not in self._graph._registered_ops # pylint: disable=protected-access or (self._graph._registered_ops[op.type].is_stateful # pylint: disable=protected-access and op.type not in ASYNC_STATEFUL_OPS)): ops_which_must_run.add(op) # Ignore switches (they're handled separately) if op.type == "Switch" and op.inputs[0].dtype == dtypes_module.resource: continue # Make merges trigger all other computation which must run if op.type == "Merge": for o in ops_which_must_run: op._add_control_input(o) # pylint: disable=protected-access for inp in o.inputs: if inp in last_op_using_resource_tensor: last_op_using_resource_tensor[inp] = op ops_which_must_run = set([op]) continue found_resource = False for inp in op.inputs: if inp.dtype == dtypes_module.resource: found_resource = True # Deal with switches, finally. if inp.op.type == "Switch": self._process_switch(inp.op, ops_which_must_run, last_op_using_resource_tensor, merge_for_resource) # Ensure uses of resources are serialized if inp in last_op_using_resource_tensor: if (last_op_using_resource_tensor[inp]._control_flow_context # pylint: disable=protected-access is op._control_flow_context): # pylint: disable=protected-access control_inputs.add(last_op_using_resource_tensor[inp]) # Ensure merges happen after the closing of a cond block if inp in merge_for_resource: merge_for_resource[inp]._add_control_input(op) # pylint: disable=protected-access last_op_using_resource_tensor[inp] = op if (op.op_def.is_stateful and op.type not in ASYNC_STATEFUL_OPS and not found_resource and op._control_flow_context is None): # pylint: disable=protected-access if None in last_op_using_resource_tensor: op._add_control_input(last_op_using_resource_tensor[None]) # pylint: disable=protected-access last_op_using_resource_tensor[None] = op control_inputs = [c for c in control_inputs if c._control_flow_context is op._control_flow_context] # pylint: disable=protected-access op._add_control_inputs(control_inputs) # pylint: disable=protected-access # Ensure all ops which must run do run for r in self._returned_tensors: if ops_which_must_run: r.op._add_control_inputs( # pylint: disable=protected-access [o for o in ops_which_must_run if o._control_flow_context is r.op._control_flow_context]) # pylint: disable=protected-access def automatic_control_dependencies(f): """Wraps f to automatically insert control dependencies. The inserted dependencies ensure that: 1. All stateful ops in f run when the result of f runs 2. Updates to the same resources happen in order. Args: f: the function to be wrapped. Returns: The wrapped function. """ def wrapper(*args, **kwargs): with AutomaticControlDependencies() as a: result = f(*args, **kwargs) result_flat = [a.mark_as_return(t) for t in nest.flatten(result)] return nest.pack_sequence_as(result, result_flat) return tf_decorator.make_decorator(f, wrapper)
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= """Tests for the functional saver.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from tensorflow.python.eager import context from tensorflow.python.eager import remote from tensorflow.python.eager import test from tensorflow.python.eager import wrap_function from tensorflow.python.framework import config from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.ops import resource_variable_ops from tensorflow.python.platform import gfile from tensorflow.python.training import server_lib from tensorflow.python.training.saving import checkpoint_options from tensorflow.python.training.saving import functional_saver from tensorflow.python.training.saving import saveable_hook from tensorflow.python.training.saving import saveable_object_util LOCALHOST = "/job:localhost/replica:0/task:0/device:CPU:0" class SaverTest(test.TestCase): def setUp(self): super(SaverTest, self).setUp() cpus = config.list_physical_devices("CPU") # Set 3 virtual CPUs config.set_logical_device_configuration(cpus[0], [ context.LogicalDeviceConfiguration(), context.LogicalDeviceConfiguration(), context.LogicalDeviceConfiguration() ]) self.local_options = checkpoint_options.CheckpointOptions( experimental_io_device=LOCALHOST) @test_util.run_in_graph_and_eager_modes def test_resource_variable(self): v1 = resource_variable_ops.ResourceVariable(2.) self.evaluate(v1.initializer) saver = functional_saver._SingleDeviceSaver( saveable_object_util.saveable_objects_for_op(v1, "x")) prefix = os.path.join(self.get_temp_dir(), "ckpt") self.evaluate(saver.save(constant_op.constant(prefix))) self.assertEqual(2, len(gfile.Glob(prefix + "*"))) self.evaluate(v1.assign(1.)) self.evaluate(saver.restore(prefix)) self.assertEqual(2., self.evaluate(v1)) v2 = resource_variable_ops.ResourceVariable(3.) self.evaluate(v2.initializer) second_saver = functional_saver._SingleDeviceSaver( saveable_object_util.saveable_objects_for_op(v2, "x")) self.evaluate(second_saver.restore(prefix)) self.assertEqual(2., self.evaluate(v2)) @test_util.run_in_graph_and_eager_modes def test_resource_variable_use_localhost(self): v1 = resource_variable_ops.ResourceVariable(2.) self.evaluate(v1.initializer) saver = functional_saver._SingleDeviceSaver( saveable_object_util.saveable_objects_for_op(v1, "x")) prefix = os.path.join(self.get_temp_dir(), "ckpt") self.evaluate(saver.save(constant_op.constant(prefix), self.local_options)) self.assertEqual(2, len(gfile.Glob(prefix + "*"))) self.evaluate(v1.assign(1.)) self.evaluate(saver.restore(prefix, self.local_options)) self.assertEqual(2., self.evaluate(v1)) v2 = resource_variable_ops.ResourceVariable(3.) self.evaluate(v2.initializer) second_saver = functional_saver._SingleDeviceSaver( saveable_object_util.saveable_objects_for_op(v2, "x")) self.evaluate(second_saver.restore(prefix, self.local_options)) self.assertEqual(2., self.evaluate(v2)) # In graph mode, verify that the save and restore ops were set to run on # localhost. if not context.executing_eagerly(): for op in ops.get_default_graph().get_operations(): if op.type in ("SaveV2", "RestoreV2"): self.assertEqual(LOCALHOST, op.device) def test_to_proto(self): v1 = resource_variable_ops.ResourceVariable(2.) saver = functional_saver.MultiDeviceSaver( saveable_object_util.saveable_objects_for_op(v1, "x")) prefix = os.path.join(self.get_temp_dir(), "ckpt") proto_accumulator = [] wrapped = wrap_function.wrap_function( lambda: proto_accumulator.append(saver.to_proto()), signature=()) self.assertEqual(1, len(proto_accumulator)) proto = proto_accumulator[0] save = wrapped.prune( feeds=wrapped.graph.get_tensor_by_name(proto.filename_tensor_name), fetches=wrapped.graph.get_tensor_by_name(proto.save_tensor_name)) restore = wrapped.prune( feeds=wrapped.graph.get_tensor_by_name(proto.filename_tensor_name), fetches=wrapped.graph.get_operation_by_name(proto.restore_op_name)) save_path = save(constant_op.constant(prefix)) v1.assign(1.) restore(constant_op.constant(save_path)) self.assertEqual(2., self.evaluate(v1)) v2 = resource_variable_ops.ResourceVariable(3.) second_saver = functional_saver.MultiDeviceSaver( saveable_object_util.saveable_objects_for_op(v2, "x")) second_saver.restore(save_path) self.assertEqual(2., self.evaluate(v2)) def test_checkpoint_is_sharded_by_task(self): servers = [server_lib.Server.create_local_server() for _ in range(3)] cluster_spec = server_lib.ClusterSpec({ "worker": [s.target[len("grpc://"):] for s in servers]}) remote.connect_to_cluster(cluster_spec) with ops.device("/job:worker/task:0/cpu:0"): v0 = resource_variable_ops.ResourceVariable(0.) with ops.device("/job:worker/task:1/cpu:0"): v1 = resource_variable_ops.ResourceVariable(1.) with ops.device("/job:worker/task:2/cpu:0"): v2 = resource_variable_ops.ResourceVariable(2.) self.evaluate([v0.initializer, v1.initializer, v2.initializer]) saver = functional_saver.MultiDeviceSaver( list(saveable_object_util.saveable_objects_for_op(v0, "v0")) + list(saveable_object_util.saveable_objects_for_op(v1, "v1")) + list(saveable_object_util.saveable_objects_for_op(v2, "v2"))) prefix = os.path.join(self.get_temp_dir(), "ckpt") self.evaluate(saver.save(constant_op.constant(prefix))) self.assertEqual(4, len(gfile.Glob(prefix + "*"))) self.evaluate(v0.assign(-1.)) self.evaluate(v1.assign(-1.)) self.evaluate(v2.assign(-1.)) self.evaluate(saver.restore(constant_op.constant(prefix))) self.assertEqual(0., self.evaluate(v0)) self.assertEqual(1., self.evaluate(v1)) self.assertEqual(2., self.evaluate(v2)) @test_util.run_in_graph_and_eager_modes def test_checkpoint_multi_device_using_localhost(self): with ops.device("cpu:0"): v0 = resource_variable_ops.ResourceVariable(0.) with ops.device("cpu:1"): v1 = resource_variable_ops.ResourceVariable(1.) with ops.device("cpu:2"): v2 = resource_variable_ops.ResourceVariable(2.) self.evaluate([v0.initializer, v1.initializer, v2.initializer]) saver = functional_saver.MultiDeviceSaver( list(saveable_object_util.saveable_objects_for_op(v0, "v0")) + list(saveable_object_util.saveable_objects_for_op(v1, "v1")) + list(saveable_object_util.saveable_objects_for_op(v2, "v2"))) prefix = os.path.join(self.get_temp_dir(), "ckpt") self.evaluate(saver.save(constant_op.constant(prefix), self.local_options)) self.assertEqual(2, len(gfile.Glob(prefix + "*"))) self.evaluate(v0.assign(-1.)) self.evaluate(v1.assign(-1.)) self.evaluate(v2.assign(-1.)) self.evaluate( saver.restore(constant_op.constant(prefix), self.local_options)) self.assertEqual(0., self.evaluate(v0)) self.assertEqual(1., self.evaluate(v1)) self.assertEqual(2., self.evaluate(v2)) # In graph mode, verify that the save and restore ops were set to run on # localhost. if not context.executing_eagerly(): for op in ops.get_default_graph().get_operations(): if op.type in ("SaveV2", "RestoreV2", "MergeV2Checkpoints"): self.assertEqual(LOCALHOST, op.device) def test_callbacks_run(self): # Use dict because an int would be shadowed inside callback. called = { "save": 0, "restore": 0, } class DummyHook(saveable_hook.SaveableHook): def before_save(self): called["save"] += 1 def after_restore(self): called["restore"] += 1 saveable = DummyHook(name="dummy") saver = functional_saver.MultiDeviceSaver([saveable]) prefix = os.path.join(self.get_temp_dir(), "ckpt") self.evaluate(saver.save(constant_op.constant(prefix))) self.assertEqual({"save": 1, "restore": 0}, called) self.evaluate(saver.restore(prefix)) self.assertEqual({"save": 1, "restore": 1}, called) if __name__ == "__main__": ops.enable_eager_execution() test.main()
# Copyright (C) 2019 Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ The junos_vlans class It is in this file where the current configuration (as dict) is compared to the provided configuration (as dict) and the command set necessary to bring the current configuration to it's desired end-state is created """ from __future__ import absolute_import, division, print_function __metaclass__ = type from ansible.module_utils.network.common.cfg.base import ConfigBase from ansible.module_utils.network.common.utils import to_list from ansible.module_utils.network.junos.facts.facts import Facts from ansible.module_utils.network.junos.junos import (locked_config, load_config, commit_configuration, discard_changes, tostring) from ansible.module_utils.network.common.netconf import (build_root_xml_node, build_child_xml_node) class Vlans(ConfigBase): """ The junos_vlans class """ gather_subset = [ '!all', '!min', ] gather_network_resources = [ 'vlans', ] def __init__(self, module): super(Vlans, self).__init__(module) def get_vlans_facts(self): """ Get the 'facts' (the current configuration) :rtype: A dictionary :returns: The current configuration as a dictionary """ facts, _warnings = Facts(self._module).get_facts( self.gather_subset, self.gather_network_resources) vlans_facts = facts['ansible_network_resources'].get('vlans') if not vlans_facts: return [] return vlans_facts def execute_module(self): """ Execute the module :rtype: A dictionary :returns: The result from module execution """ result = {'changed': False} warnings = list() existing_vlans_facts = self.get_vlans_facts() config_xmls = self.set_config(existing_vlans_facts) with locked_config(self._module): for config_xml in to_list(config_xmls): diff = load_config(self._module, config_xml, warnings) commit = not self._module.check_mode if diff: if commit: commit_configuration(self._module) else: discard_changes(self._module) result['changed'] = True if self._module._diff: result['diff'] = {'prepared': diff} result['commands'] = config_xmls changed_vlans_facts = self.get_vlans_facts() result['before'] = existing_vlans_facts if result['changed']: result['after'] = changed_vlans_facts result['warnings'] = warnings return result def set_config(self, existing_vlans_facts): """ Collect the configuration from the args passed to the module, collect the current configuration (as a dict from facts) :rtype: A list :returns: the commands necessary to migrate the current configuration to the desired configuration """ want = self._module.params['config'] have = existing_vlans_facts resp = self.set_state(want, have) return to_list(resp) def set_state(self, want, have): """ Select the appropriate function based on the state provided :param want: the desired configuration as a dictionary :param have: the current configuration as a dictionary :rtype: A list :returns: the commands necessary to migrate the current configuration to the desired configuration """ root = build_root_xml_node('vlans') state = self._module.params['state'] if state == 'overridden': config_xmls = self._state_overridden(want, have) elif state == 'deleted': config_xmls = self._state_deleted(want, have) elif state == 'merged': config_xmls = self._state_merged(want, have) elif state == 'replaced': config_xmls = self._state_replaced(want, have) for xml in config_xmls: root.append(xml) return tostring(root) def _state_replaced(self, want, have): """ The command generator when state is replaced :rtype: A list :returns: the xml necessary to migrate the current configuration to the desired configuration """ intf_xml = [] intf_xml.extend(self._state_deleted(want, have)) intf_xml.extend(self._state_merged(want, have)) return intf_xml def _state_overridden(self, want, have): """ The command generator when state is overridden :rtype: A list :returns: the xml necessary to migrate the current configuration to the desired configuration """ intf_xml = [] intf_xml.extend(self._state_deleted(have, have)) intf_xml.extend(self._state_merged(want, have)) return intf_xml def _state_merged(self, want, have): """ The command generator when state is merged :rtype: A list :returns: the xml necessary to merge the provided into the current configuration """ intf_xml = [] for config in want: vlan_name = str(config['name']) vlan_id = str(config['vlan_id']) vlan_description = config.get('description') vlan_root = build_root_xml_node('vlan') build_child_xml_node(vlan_root, 'name', vlan_name) build_child_xml_node(vlan_root, 'vlan-id', vlan_id) if vlan_description: build_child_xml_node(vlan_root, 'description', vlan_description) intf_xml.append(vlan_root) return intf_xml def _state_deleted(self, want, have): """ The command generator when state is deleted :rtype: A list :returns: the xml necessary to remove the current configuration of the provided objects """ intf_xml = [] if not want: want = have for config in want: vlan_name = config['name'] vlan_root = build_root_xml_node('vlan') vlan_root.attrib.update({'delete': 'delete'}) build_child_xml_node(vlan_root, 'name', vlan_name) intf_xml.append(vlan_root) return intf_xml
# -*- coding: utf-8 -*- import json import sys import traceback from django.conf import settings from django.core.files.storage import default_storage as storage from django.db import transaction import mock from nose.plugins.attrib import attr from nose.tools import eq_, ok_ from pyquery import PyQuery as pq import waffle import amo import amo.tests from addons.models import Addon from amo.tests import assert_no_validation_exceptions from amo.tests.test_helpers import get_image_path from amo.urlresolvers import reverse from applications.models import AppVersion from devhub.tasks import compatibility_check from files.helpers import copyfileobj from files.models import File, FileUpload, FileValidation from files.tests.test_models import UploadTest as BaseUploadTest from files.utils import parse_addon from users.models import UserProfile from zadmin.models import ValidationResult class TestUploadValidation(BaseUploadTest): fixtures = ['base/users', 'devhub/invalid-id-uploaded-xpi.json'] def setUp(self): super(TestUploadValidation, self).setUp() assert self.client.login(username='regular@mozilla.com', password='password') def test_no_html_in_messages(self): upload = FileUpload.objects.get(name='invalid-id-20101206.xpi') resp = self.client.get(reverse('devhub.upload_detail', args=[upload.uuid, 'json'])) eq_(resp.status_code, 200) data = json.loads(resp.content) msg = data['validation']['messages'][1] eq_(msg['message'], 'The value of &lt;em:id&gt; is invalid.') eq_(sorted(msg['context']), [[u'&lt;foo/&gt;'], u'&lt;em:description&gt;...']) def test_date_on_upload(self): upload = FileUpload.objects.get(name='invalid-id-20101206.xpi') resp = self.client.get(reverse('devhub.upload_detail', args=[upload.uuid])) eq_(resp.status_code, 200) doc = pq(resp.content) eq_(doc('td').text(), 'December 6, 2010') def test_upload_saves_escaped_validation(self): addon_file = open('apps/files/fixtures/files/validation-error.xpi') response = self.client.post(reverse('devhub.upload'), {'name': 'addon.xpi', 'upload': addon_file}) uuid = response.url.split('/')[-2] upload = FileUpload.objects.get(uuid=uuid) assert upload._escaped_validation, 'escaped validation not saved' eq_(json.loads(upload._escaped_validation)['errors'], 1) class TestUploadErrors(BaseUploadTest): fixtures = ('base/addon_3615', 'base/users') def setUp(self): super(TestUploadErrors, self).setUp() self.client.login(username='regular@mozilla.com', password='password') @mock.patch.object(waffle, 'flag_is_active') def test_dupe_uuid(self, flag_is_active): flag_is_active.return_value = True addon = Addon.objects.get(pk=3615) d = parse_addon(self.get_upload('extension.xpi')) addon.update(guid=d['guid']) dupe_xpi = self.get_upload('extension.xpi') res = self.client.get(reverse('devhub.upload_detail', args=[dupe_xpi.uuid, 'json'])) eq_(res.status_code, 400, res.content) data = json.loads(res.content) eq_(data['validation']['messages'], [{'tier': 1, 'message': 'Duplicate UUID found.', 'type': 'error', 'fatal': True}]) eq_(data['validation']['ending_tier'], 1) class TestFileValidation(amo.tests.TestCase): fixtures = ['base/users', 'devhub/addon-validation-1'] def setUp(self): super(TestFileValidation, self).setUp() assert self.client.login(username='del@icio.us', password='password') self.user = UserProfile.objects.get(email='del@icio.us') self.file_validation = FileValidation.objects.get(pk=1) self.file = self.file_validation.file with storage.open(self.file.file_path, 'w') as f: f.write('<pretend this is an xpi>\n') self.addon = self.file.version.addon args = [self.addon.slug, self.file.id] self.url = reverse('devhub.file_validation', args=args) self.json_url = reverse('devhub.json_file_validation', args=args) def test_version_list(self): r = self.client.get(self.addon.get_dev_url('versions')) eq_(r.status_code, 200) a = pq(r.content)('td.file-validation a') eq_(a.text(), '0 errors, 0 warnings') eq_(a.attr('href'), self.url) def test_results_page(self): r = self.client.get(self.url, follow=True) eq_(r.status_code, 200) eq_(r.context['addon'], self.addon) doc = pq(r.content) assert not doc('#site-nav').hasClass('app-nav'), ( 'Expected add-ons devhub nav') eq_(doc('header h2').text(), u'Validation Results for searchaddon11102010-20101217.xml') eq_(doc('#addon-validator-suite').attr('data-validateurl'), self.json_url) def test_only_dev_can_see_results(self): self.client.logout() assert self.client.login(username='regular@mozilla.com', password='password') eq_(self.client.head(self.url, follow=True).status_code, 403) def test_only_dev_can_see_json_results(self): self.client.logout() assert self.client.login(username='regular@mozilla.com', password='password') eq_(self.client.head(self.json_url, follow=True).status_code, 403) def test_editor_can_see_results(self): self.client.logout() assert self.client.login(username='editor@mozilla.com', password='password') eq_(self.client.head(self.url, follow=True).status_code, 200) def test_editor_can_see_json_results(self): self.client.logout() assert self.client.login(username='editor@mozilla.com', password='password') eq_(self.client.head(self.json_url, follow=True).status_code, 200) def test_no_html_in_messages(self): r = self.client.post(self.json_url, follow=True) eq_(r.status_code, 200) data = json.loads(r.content) msg = data['validation']['messages'][0] eq_(msg['message'], 'The value of &lt;em:id&gt; is invalid.') eq_(sorted(msg['context']), [[u'&lt;foo/&gt;'], u'&lt;em:description&gt;...']) @mock.patch('files.models.File.has_been_validated') def test_json_results_post(self, has_been_validated): has_been_validated.__nonzero__.return_value = False with transaction.atomic(): # The json_file_validation view will raise an IntegrityError when # trying to save a FileValidation, as it's already been created by # the fixture addon-validation-1. eq_(self.client.post(self.json_url).status_code, 200) has_been_validated.__nonzero__.return_value = True eq_(self.client.post(self.json_url).status_code, 200) @mock.patch('files.models.File.has_been_validated') def test_json_results_get(self, has_been_validated): has_been_validated.__nonzero__.return_value = True eq_(self.client.get(self.json_url).status_code, 200) has_been_validated.__nonzero__.return_value = False eq_(self.client.get(self.json_url).status_code, 405) class TestValidateAddon(amo.tests.TestCase): fixtures = ['base/users'] def setUp(self): super(TestValidateAddon, self).setUp() assert self.client.login(username='regular@mozilla.com', password='password') def test_login_required(self): self.client.logout() r = self.client.get(reverse('devhub.validate_addon')) eq_(r.status_code, 302) def test_context(self): self.create_flag('unlisted-addons') r = self.client.get(reverse('devhub.validate_addon')) eq_(r.status_code, 200) doc = pq(r.content) eq_(doc('#upload-addon').attr('data-upload-url'), reverse('devhub.standalone_upload')) eq_(doc('#upload-addon').attr('data-upload-url-listed'), reverse('devhub.standalone_upload')) eq_(doc('#upload-addon').attr('data-upload-url-unlisted'), reverse('devhub.standalone_upload_unlisted')) @mock.patch('validator.validate.validate') def test_upload_unlisted_addon(self, validate_mock): """Unlisted addons are validated as "self hosted" addons.""" validate_mock.return_value = '{}' self.url = reverse('devhub.upload_unlisted') data = open(get_image_path('animated.png'), 'rb') self.client.post(self.url, {'upload': data}) # Make sure it was called with listed=False. assert not validate_mock.call_args[1]['listed'] class TestValidateFile(BaseUploadTest): fixtures = ['base/users', 'base/addon_3615', 'devhub/addon-file-100456'] def setUp(self): super(TestValidateFile, self).setUp() assert self.client.login(username='del@icio.us', password='password') self.user = UserProfile.objects.get(email='del@icio.us') self.file = File.objects.get(pk=100456) # Move the file into place as if it were a real file with storage.open(self.file.file_path, 'w') as dest: copyfileobj(open(self.file_path('invalid-id-20101206.xpi')), dest) self.addon = self.file.version.addon def tearDown(self): if storage.exists(self.file.file_path): storage.delete(self.file.file_path) super(TestValidateFile, self).tearDown() @attr('validator') def test_lazy_validate(self): r = self.client.post(reverse('devhub.json_file_validation', args=[self.addon.slug, self.file.id]), follow=True) eq_(r.status_code, 200) data = json.loads(r.content) assert_no_validation_exceptions(data) msg = data['validation']['messages'][0] ok_('is invalid' in msg['message']) def test_time(self): r = self.client.post(reverse('devhub.file_validation', args=[self.addon.slug, self.file.id]), follow=True) doc = pq(r.content) assert doc('time').text() @mock.patch.object(settings, 'EXPOSE_VALIDATOR_TRACEBACKS', False) @mock.patch('devhub.tasks.run_validator') def test_validator_errors(self, v): v.side_effect = ValueError('catastrophic failure in amo-validator') r = self.client.post(reverse('devhub.json_file_validation', args=[self.addon.slug, self.file.id]), follow=True) eq_(r.status_code, 200) data = json.loads(r.content) eq_(data['validation'], '') eq_(data['error'].strip(), 'ValueError: catastrophic failure in amo-validator') @mock.patch('devhub.tasks.run_validator') def test_validator_sets_binary_flag_for_extensions(self, v): v.return_value = json.dumps({ "errors": 0, "success": True, "warnings": 0, "notices": 0, "message_tree": {}, "messages": [], "metadata": { "contains_binary_extension": True, "version": "1.0", "name": "gK0Bes Bot", "id": "gkobes@gkobes" } }) eq_(self.addon.binary, False) r = self.client.post(reverse('devhub.json_file_validation', args=[self.addon.slug, self.file.id]), follow=True) eq_(r.status_code, 200) data = json.loads(r.content) assert_no_validation_exceptions(data) addon = Addon.objects.get(pk=self.addon.id) eq_(addon.binary, True) @mock.patch('validator.validate.validate') def test_validator_sets_tier(self, v): self.client.post(reverse('devhub.json_file_validation', args=[self.addon.slug, self.file.id]), follow=True) assert not v.call_args[1].get('compat_test', True) @mock.patch('devhub.tasks.run_validator') def test_ending_tier_is_preserved(self, v): v.return_value = json.dumps({ "errors": 0, "success": True, "warnings": 0, "notices": 0, "message_tree": {}, "messages": [], "ending_tier": 5, "metadata": { "contains_binary_extension": True, "version": "1.0", "name": "gK0Bes Bot", "id": "gkobes@gkobes" } }) r = self.client.post(reverse('devhub.json_file_validation', args=[self.addon.slug, self.file.id]), follow=True) eq_(r.status_code, 200) data = json.loads(r.content) eq_(data['validation']['ending_tier'], 5) @mock.patch('devhub.tasks.run_validator') def test_validator_sets_binary_flag_for_content(self, v): v.return_value = json.dumps({ "errors": 0, "success": True, "warnings": 0, "notices": 0, "message_tree": {}, "messages": [], "metadata": { "contains_binary_content": True, "version": "1.0", "name": "gK0Bes Bot", "id": "gkobes@gkobes" } }) eq_(self.addon.binary, False) r = self.client.post(reverse('devhub.json_file_validation', args=[self.addon.slug, self.file.id]), follow=True) eq_(r.status_code, 200) data = json.loads(r.content) assert_no_validation_exceptions(data) addon = Addon.objects.get(pk=self.addon.id) eq_(addon.binary, True) @mock.patch('devhub.tasks.run_validator') def test_linkify_validation_messages(self, v): v.return_value = json.dumps({ "errors": 0, "success": True, "warnings": 1, "notices": 0, "message_tree": {}, "messages": [{ "context": ["<code>", None], "description": [ "Something something, see https://bugzilla.mozilla.org/"], "column": 0, "line": 1, "file": "chrome/content/down.html", "tier": 2, "message": "Some warning", "type": "warning", "id": [], "uid": "bb9948b604b111e09dfdc42c0301fe38" }], "metadata": {} }) r = self.client.post(reverse('devhub.json_file_validation', args=[self.addon.slug, self.file.id]), follow=True) eq_(r.status_code, 200) data = json.loads(r.content) assert_no_validation_exceptions(data) doc = pq(data['validation']['messages'][0]['description'][0]) eq_(doc('a').text(), 'https://bugzilla.mozilla.org/') @mock.patch.object(settings, 'EXPOSE_VALIDATOR_TRACEBACKS', False) @mock.patch('devhub.tasks.run_validator') def test_hide_validation_traceback(self, run_validator): run_validator.side_effect = RuntimeError('simulated task error') r = self.client.post(reverse('devhub.json_file_validation', args=[self.addon.slug, self.file.id]), follow=True) eq_(r.status_code, 200) data = json.loads(r.content) eq_(data['validation'], '') eq_(data['error'], 'RuntimeError: simulated task error') @mock.patch.object(waffle, 'flag_is_active') @mock.patch('devhub.tasks.run_validator') def test_rdf_parse_errors_are_ignored(self, run_validator, flag_is_active): run_validator.return_value = json.dumps({ "errors": 0, "success": True, "warnings": 0, "notices": 0, "message_tree": {}, "messages": [], "metadata": {} }) flag_is_active.return_value = True addon = Addon.objects.get(pk=3615) xpi = self.get_upload('extension.xpi') d = parse_addon(xpi.path) # Set up a duplicate upload: addon.update(guid=d['guid']) res = self.client.get(reverse('devhub.validate_addon')) doc = pq(res.content) upload_url = doc('#upload-addon').attr('data-upload-url') with storage.open(xpi.path, 'rb') as f: # Simulate JS file upload res = self.client.post(upload_url, {'upload': f}, follow=True) data = json.loads(res.content) # Simulate JS result polling: res = self.client.get(data['url']) data = json.loads(res.content) # Make sure we don't see a dupe UUID error: eq_(data['validation']['messages'], []) # Simulate JS result polling on detail page: res = self.client.get(data['full_report_url'], follow=True) res = self.client.get(res.context['validate_url'], follow=True) data = json.loads(res.content) # Again, make sure we don't see a dupe UUID error: eq_(data['validation']['messages'], []) @mock.patch('devhub.tasks.run_validator') def test_compatibility_check(self, run_validator): run_validator.return_value = json.dumps({ 'errors': 0, 'success': True, 'warnings': 0, 'notices': 0, 'message_tree': {}, 'messages': [], 'metadata': {} }) xpi = self.get_upload('extension.xpi') AppVersion.objects.create( application=amo.FIREFOX.id, version='10.0.*') compatibility_check(xpi, amo.FIREFOX.guid, '10.0.*') eq_(run_validator.call_args[1]['compat'], True) class TestCompatibilityResults(amo.tests.TestCase): fixtures = ['base/users', 'devhub/addon-compat-results'] def setUp(self): super(TestCompatibilityResults, self).setUp() assert self.client.login(username='editor@mozilla.com', password='password') self.addon = Addon.objects.get(slug='addon-compat-results') self.result = ValidationResult.objects.get( file__version__addon=self.addon) self.job = self.result.validation_job def validate(self, expected_status=200): r = self.client.post(reverse('devhub.json_bulk_compat_result', args=[self.addon.slug, self.result.id]), follow=True) eq_(r.status_code, expected_status) return json.loads(r.content) def test_login_protected(self): self.client.logout() r = self.client.get(reverse('devhub.bulk_compat_result', args=[self.addon.slug, self.result.id])) eq_(r.status_code, 302) r = self.client.post(reverse('devhub.json_bulk_compat_result', args=[self.addon.slug, self.result.id])) eq_(r.status_code, 302) def test_target_version(self): r = self.client.get(reverse('devhub.bulk_compat_result', args=[self.addon.slug, self.result.id])) eq_(r.status_code, 200) doc = pq(r.content) ver = json.loads(doc('.results').attr('data-target-version')) assert amo.FIREFOX.guid in ver, ('Unexpected: %s' % ver) eq_(ver[amo.FIREFOX.guid], self.job.target_version.version) def test_app_trans(self): r = self.client.get(reverse('devhub.bulk_compat_result', args=[self.addon.slug, self.result.id])) eq_(r.status_code, 200) doc = pq(r.content) trans = json.loads(doc('.results').attr('data-app-trans')) for app in amo.APPS.values(): eq_(trans[app.guid], app.pretty) def test_app_version_change_links(self): r = self.client.get(reverse('devhub.bulk_compat_result', args=[self.addon.slug, self.result.id])) eq_(r.status_code, 200) doc = pq(r.content) trans = json.loads(doc('.results').attr('data-version-change-links')) eq_(trans['%s 4.0.*' % amo.FIREFOX.guid], 'https://developer.mozilla.org/en/Firefox_4_for_developers') def test_validation_success(self): data = self.validate() eq_(data['validation']['messages'][3]['for_appversions'], {'{ec8030f7-c20a-464f-9b0e-13a3a9e97384}': ['4.0b3']}) def test_time(self): r = self.client.post(reverse('devhub.bulk_compat_result', args=[self.addon.slug, self.result.id]), follow=True) eq_(r.status_code, 200) doc = pq(r.content) assert doc('time').text() eq_(doc('table tr td:eq(1)').text(), 'Firefox 4.0.*') @mock.patch.object(settings, 'EXPOSE_VALIDATOR_TRACEBACKS', True) def test_validation_error(self): try: raise RuntimeError('simulated task error') except: error = ''.join(traceback.format_exception(*sys.exc_info())) self.result.update(validation='', task_error=error) data = self.validate() eq_(data['validation'], '') eq_(data['error'], error) @mock.patch.object(settings, 'EXPOSE_VALIDATOR_TRACEBACKS', False) def test_hide_validation_traceback(self): try: raise RuntimeError('simulated task error') except: error = ''.join(traceback.format_exception(*sys.exc_info())) self.result.update(validation='', task_error=error) data = self.validate() eq_(data['validation'], '') eq_(data['error'], 'RuntimeError: simulated task error') class TestUploadCompatCheck(BaseUploadTest): fixtures = ['base/appversion', 'base/addon_3615'] compatibility_result = json.dumps({ "errors": 0, "success": True, "warnings": 0, "notices": 0, "compatibility_summary": {"notices": 0, "errors": 0, "warnings": 1}, "message_tree": {}, "messages": [], "metadata": {} }) def setUp(self): super(TestUploadCompatCheck, self).setUp() assert self.client.login(username='del@icio.us', password='password') self.app = amo.FIREFOX self.appver = AppVersion.objects.get(application=self.app.id, version='3.7a1pre') self.upload_url = reverse('devhub.standalone_upload') def poll_upload_status_url(self, upload_uuid): return reverse('devhub.standalone_upload_detail', args=[upload_uuid]) def fake_xpi(self, filename=None): """Any useless file that has a name property (for Django).""" if not filename: return open(get_image_path('non-animated.gif'), 'rb') return storage.open(filename, 'rb') def upload(self, filename=None): with self.fake_xpi(filename=filename) as f: # Simulate how JS posts data w/ app/version from the form. res = self.client.post(self.upload_url, {'upload': f, 'app_id': self.app.id, 'version_id': self.appver.pk}, follow=True) return json.loads(res.content) def test_compat_form(self): res = self.client.get(reverse('devhub.check_addon_compatibility')) eq_(res.status_code, 200) doc = pq(res.content) options = doc('#id_application option') expected = [(str(a.id), unicode(a.pretty)) for a in amo.APP_USAGE] for idx, element in enumerate(options): e = pq(element) val, text = expected[idx] eq_(e.val(), val) eq_(e.text(), text) eq_(doc('#upload-addon').attr('data-upload-url'), self.upload_url) # TODO(Kumar) actually check the form here after bug 671587 @mock.patch('devhub.tasks.run_validator') def test_js_upload_validates_compatibility(self, run_validator): run_validator.return_value = '' # Empty to simulate unfinished task. data = self.upload() kw = run_validator.call_args[1] eq_(kw['for_appversions'], {self.app.guid: [self.appver.version]}) eq_(kw['overrides'], {'targetapp_minVersion': {self.app.guid: self.appver.version}, 'targetapp_maxVersion': {self.app.guid: self.appver.version}}) eq_(data['url'], self.poll_upload_status_url(data['upload'])) @mock.patch('devhub.tasks.run_validator') def test_js_poll_upload_status(self, run_validator): run_validator.return_value = self.compatibility_result data = self.upload() url = self.poll_upload_status_url(data['upload']) res = self.client.get(url) data = json.loads(res.content) if data['validation'] and data['validation']['messages']: raise AssertionError('Unexpected validation errors: %s' % data['validation']['messages']) @mock.patch('devhub.tasks.run_validator') def test_compat_result_report(self, run_validator): run_validator.return_value = self.compatibility_result data = self.upload() poll_url = self.poll_upload_status_url(data['upload']) res = self.client.get(poll_url) data = json.loads(res.content) res = self.client.get(data['full_report_url']) eq_(res.status_code, 200) eq_(res.context['result_type'], 'compat') doc = pq(res.content) # Shows app/version on the results page. eq_(doc('table tr td:eq(0)').text(), 'Firefox 3.7a1pre') eq_(res.context['validate_url'], poll_url) def test_compat_application_versions(self): res = self.client.get(reverse('devhub.check_addon_compatibility')) eq_(res.status_code, 200) doc = pq(res.content) data = {'application': amo.FIREFOX.id, 'csrfmiddlewaretoken': doc('input[name=csrfmiddlewaretoken]').val()} r = self.client.post(doc('#id_application').attr('data-url'), data) eq_(r.status_code, 200) data = json.loads(r.content) empty = True for id, ver in data['choices']: empty = False eq_(AppVersion.objects.get(pk=id).version, ver) assert not empty, "Unexpected: %r" % data @mock.patch.object(waffle, 'flag_is_active') @mock.patch('devhub.tasks.run_validator') def test_rdf_parse_errors_are_ignored(self, run_validator, flag_is_active): run_validator.return_value = self.compatibility_result flag_is_active.return_value = True addon = Addon.objects.get(pk=3615) dupe_xpi = self.get_upload('extension.xpi') d = parse_addon(dupe_xpi) # Set up a duplicate upload: addon.update(guid=d['guid']) data = self.upload(filename=dupe_xpi.path) # Make sure we don't see a dupe UUID error: eq_(data['validation']['messages'], []) @mock.patch('devhub.tasks.run_validator') def test_compat_summary_overrides(self, run_validator): run_validator.return_value = json.dumps({ "success": True, "errors": 0, "warnings": 0, "notices": 0, "compatibility_summary": {"notices": 1, "errors": 2, "warnings": 3}, "message_tree": {}, "messages": [], "metadata": {} }) data = self.upload() eq_(data['validation']['notices'], 1) eq_(data['validation']['errors'], 2) eq_(data['validation']['warnings'], 3) res = self.client.get(self.poll_upload_status_url(data['upload'])) data = json.loads(res.content) eq_(data['validation']['notices'], 1) eq_(data['validation']['errors'], 2) eq_(data['validation']['warnings'], 3) @mock.patch('devhub.tasks.run_validator') def test_compat_error_type_override(self, run_validator): run_validator.return_value = json.dumps({ "success": True, "errors": 0, "warnings": 0, "notices": 0, "compatibility_summary": {"notices": 0, "errors": 1, "warnings": 0}, "message_tree": {}, "messages": [{"type": "warning", "compatibility_type": "error", "tier": 1}, {"type": "warning", "compatibility_type": None, "tier": 1}], "metadata": {} }) data = self.upload() eq_(data['validation']['messages'][0]['type'], 'error') eq_(data['validation']['messages'][1]['type'], 'warning')
#!/usr/bin/env python # ___ ___ _ _ ___ ___ _ _____ ___ ___ # / __| __| \| | __| _ \ /_\_ _| __| \ # | (_ | _|| .` | _|| / / _ \| | | _|| |) | # \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____ # | \ / _ \ | \| |/ _ \_ _| | __| \_ _|_ _| # | |) | (_) | | .` | (_) || | | _|| |) | | | | # |___/ \___/ |_|\_|\___/ |_| |___|___/___| |_| ''' GcloudCLI class that wraps the oc commands in a subprocess ''' import atexit import json import os import random # Not all genearated modules use this. # pylint: disable=unused-import import re import shutil import string import subprocess import tempfile import yaml # Not all genearated modules use this. # pylint: disable=unused-import import copy # pylint: disable=import-error from apiclient.discovery import build # pylint: disable=import-error from oauth2client.client import GoogleCredentials from ansible.module_utils.basic import AnsibleModule class GcloudCLIError(Exception): '''Exception class for openshiftcli''' pass # pylint: disable=too-few-public-methods class GcloudCLI(object): ''' Class to wrap the command line tools ''' def __init__(self, credentials=None, project=None, verbose=False): ''' Constructor for GcloudCLI ''' self.scope = None self._project = project if not credentials: self.credentials = GoogleCredentials.get_application_default() else: tmp = tempfile.NamedTemporaryFile() tmp.write(json.dumps(credentials)) tmp.seek(0) self.credentials = GoogleCredentials.from_stream(tmp.name) tmp.close() self.scope = build('compute', 'beta', credentials=self.credentials) self.verbose = verbose @property def project(self): '''property for project''' return self._project def _create_image(self, image_name, image_info): '''create an image name''' cmd = ['compute', 'images', 'create', image_name] for key, val in image_info.items(): if val: cmd.extend(['--%s' % key, val]) return self.gcloud_cmd(cmd, output=True, output_type='raw') def _delete_image(self, image_name): '''delete image by name ''' cmd = ['compute', 'images', 'delete', image_name] if image_name: cmd.extend(['describe', image_name]) else: cmd.append('list') cmd.append('-q') return self.gcloud_cmd(cmd, output=True, output_type='raw') def _list_images(self, image_name=None): '''list images. if name is supplied perform a describe and return ''' cmd = ['compute', 'images'] if image_name: cmd.extend(['describe', image_name]) else: cmd.append('list') return self.gcloud_cmd(cmd, output=True, output_type='raw') def _list_deployments(self, simple=True): '''list deployments by name ''' cmd = ['deployment-manager', 'deployments', 'list'] if simple: cmd.append('--simple-list') return self.gcloud_cmd(cmd, output=True, output_type='raw') def _delete_deployment(self, dname): '''list deployments by name ''' cmd = ['deployment-manager', 'deployments', 'delete', dname, '-q'] return self.gcloud_cmd(cmd, output=True, output_type='raw') def _create_deployment(self, dname, config=None, opts=None): ''' create a deployment''' cmd = ['deployment-manager', 'deployments', 'create', dname] if config: if isinstance(config, dict): config = Utils.create_file(dname, config) if isinstance(config, str) and os.path.exists(config): cmd.extend(['--config=%s' % config]) if opts: for key, val in opts.items(): cmd.append('--%s=%s' % (key, val)) return self.gcloud_cmd(cmd, output=True, output_type='raw') def _update_deployment(self, dname, config=None, opts=None): ''' create a deployment''' cmd = ['deployment-manager', 'deployments', 'update', dname] if config: if isinstance(config, dict): config = Utils.create_file(dname, config) if isinstance(config, str) and os.path.exists(config): cmd.extend(['--config=%s' % config]) if opts: for key, val in opts.items(): cmd.append('--%s=%s' % (key, val)) return self.gcloud_cmd(cmd, output=True, output_type='raw') def _list_manifests(self, deployment, mname=None): ''' list manifests if a name is specified then perform a describe ''' cmd = ['deployment-manager', 'manifests', '--deployment', deployment] if mname: cmd.extend(['describe', mname]) else: cmd.append('list') cmd.extend(['--format', 'json']) return self.gcloud_cmd(cmd, output=True, output_type='json') def _delete_address(self, aname): ''' list addresses if a name is specified then perform a describe ''' cmd = ['compute', 'addresses', 'delete', aname, '-q'] return self.gcloud_cmd(cmd, output=True, output_type='raw') def _list_addresses(self, aname=None): ''' list addresses if a name is specified then perform a describe ''' cmd = ['compute', 'addresses'] if aname: cmd.extend(['describe', aname]) else: cmd.append('list') return self.gcloud_cmd(cmd, output=True, output_type='raw') def _create_address(self, address_name, address_info, address=None, isglobal=False): ''' create a deployment''' cmd = ['compute', 'addresses', 'create', address_name] if address: cmd.append(address) if isglobal: cmd.append('--global') for key, val in address_info.items(): if val: cmd.extend(['--%s' % key, val]) return self.gcloud_cmd(cmd, output=True, output_type='raw') def _list_metadata(self, resource_type, name=None, zone=None): ''' list metadata''' cmd = ['compute', resource_type, 'describe'] if name: cmd.extend([name]) if zone: cmd.extend(['--zone', zone]) return self.gcloud_cmd(cmd, output=True, output_type='raw') # pylint: disable=too-many-arguments def _delete_metadata(self, resource_type, keys, remove_all=False, name=None, zone=None): '''create metadata''' cmd = ['compute', resource_type, 'remove-metadata'] if name: cmd.extend([name]) if zone: cmd.extend(['--zone', zone]) if remove_all: cmd.append('--all') else: cmd.append('--keys') cmd.append(','.join(keys)) cmd.append('-q') return self.gcloud_cmd(cmd, output=True, output_type='raw') # pylint: disable=too-many-arguments def _create_metadata(self, resource_type, metadata=None, metadata_from_file=None, name=None, zone=None): '''create metadata''' cmd = ['compute', resource_type, 'add-metadata'] if name: cmd.extend([name]) if zone: cmd.extend(['--zone', zone]) data = None if metadata_from_file: cmd.append('--metadata-from-file') data = metadata_from_file else: cmd.append('--metadata') data = metadata cmd.append(','.join(['%s=%s' % (key, val) for key, val in data.items()])) return self.gcloud_cmd(cmd, output=True, output_type='raw') def _list_service_accounts(self, sa_name=None): '''return service accounts ''' cmd = ['iam', 'service-accounts'] if sa_name: cmd.extend(['describe', sa_name]) else: cmd.append('list') cmd.extend(['--format', 'json']) return self.gcloud_cmd(cmd, output=True, output_type='json') def _delete_service_account(self, sa_name): '''delete service account ''' cmd = ['iam', 'service-accounts', 'delete', sa_name, '-q'] cmd.extend(['--format', 'json']) return self.gcloud_cmd(cmd, output=True, output_type='json') def _create_service_account(self, sa_name, display_name=None): '''create service account ''' cmd = ['iam', 'service-accounts', 'create', sa_name] if display_name: cmd.extend(['--display-name', display_name]) cmd.extend(['--format', 'json']) return self.gcloud_cmd(cmd, output=True, output_type='json') def _update_service_account(self, sa_name, display_name=None): '''update service account ''' cmd = ['iam', 'service-accounts', 'update', sa_name] if display_name: cmd.extend(['--display-name', display_name]) cmd.extend(['--format', 'json']) return self.gcloud_cmd(cmd, output=True, output_type='json') def _delete_service_account_key(self, sa_name, key_id): '''delete service account key''' cmd = ['iam', 'service-accounts', 'keys', 'delete', key_id, '--iam-account', sa_name, '-q'] return self.gcloud_cmd(cmd, output=True, output_type='raw') def _list_service_account_keys(self, sa_name): '''return service account keys ''' cmd = ['iam', 'service-accounts', 'keys', 'list', '--iam-account', sa_name] cmd.extend(['--format', 'json']) return self.gcloud_cmd(cmd, output=True, output_type='json') def _create_service_account_key(self, sa_name, outputfile, key_format='p12'): '''create service account key ''' # Ensure we remove the key file atexit.register(Utils.cleanup, [outputfile]) cmd = ['iam', 'service-accounts', 'keys', 'create', outputfile, '--iam-account', sa_name, '--key-file-type', key_format] return self.gcloud_cmd(cmd, output=True, output_type='raw') def _list_project_policy(self, project): '''create service account key ''' cmd = ['projects', 'get-iam-policy', project] cmd.extend(['--format', 'json']) return self.gcloud_cmd(cmd, output=True, output_type='json') def _add_project_policy(self, project, member, role): '''create service account key ''' cmd = ['projects', 'add-iam-policy-binding', project, '--member', member, '--role', role] cmd.extend(['--format', 'json']) return self.gcloud_cmd(cmd, output=True, output_type='json') def _remove_project_policy(self, project, member, role): '''create service account key ''' cmd = ['projects', 'remove-iam-policy-binding', project, '--member', member, '--role', role] cmd.extend(['--format', 'json']) return self.gcloud_cmd(cmd, output=True, output_type='json') def _set_project_policy(self, project, policy_path): '''create service account key ''' cmd = ['projects', 'set-iam-policy', project, policy_path] cmd.extend(['--format', 'json']) return self.gcloud_cmd(cmd, output=True, output_type='json') def _list_zones(self): ''' list zones ''' cmd = ['compute', 'zones', 'list'] cmd.extend(['--format', 'json']) return self.gcloud_cmd(cmd, output=True, output_type='json') def _config_set(self, config_param, config_value, config_section): ''' set config params with gcloud config set ''' param = config_section + '/' + config_param cmd = ['config', 'set', param, config_value] cmd.extend(['--format', 'json']) return self.gcloud_cmd(cmd, output=True, output_type='json') def _list_config(self): '''return config ''' cmd = ['config', 'list'] cmd.extend(['--format', 'json']) return self.gcloud_cmd(cmd, output=True, output_type='json') def list_disks(self, zone=None, disk_name=None): '''return a list of disk objects in this project and zone''' cmd = ['beta', 'compute', 'disks'] if disk_name and zone: cmd.extend(['describe', disk_name, '--zone', zone]) else: cmd.append('list') cmd.extend(['--format', 'json']) return self.gcloud_cmd(cmd, output=True, output_type='json') # disabling too-many-arguments as these are all required for the disk labels # pylint: disable=too-many-arguments def _set_disk_labels(self, project, zone, dname, labels, finger_print): '''create service account key ''' if labels == None: labels = {} self.scope = build('compute', 'beta', credentials=self.credentials) body = {'labels': labels, 'labelFingerprint': finger_print} result = self.scope.disks().setLabels(project=project, zone=zone, resource=dname, body=body, ).execute() return result def gcloud_cmd(self, cmd, output=False, output_type='json'): '''Base command for gcloud ''' cmds = ['/usr/bin/gcloud'] if self.project: cmds.extend(['--project', self.project]) cmds.extend(cmd) rval = {} results = '' err = None if self.verbose: print ' '.join(cmds) proc = subprocess.Popen(cmds, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env={}) stdout, stderr = proc.communicate() rval = {"returncode": proc.returncode, "results": results, "cmd": ' '.join(cmds), } if proc.returncode == 0: if output: if output_type == 'json': try: rval['results'] = json.loads(stdout) except ValueError as err: if "No JSON object could be decoded" in err.message: err = err.message elif output_type == 'raw': rval['results'] = stdout if self.verbose: print stdout print stderr if err: rval.update({"err": err, "stderr": stderr, "stdout": stdout, "cmd": cmds }) else: rval.update({"stderr": stderr, "stdout": stdout, "results": {}, }) return rval ################################################################################ # utilities and helpers for generation ################################################################################ class Utils(object): ''' utilities for openshiftcli modules ''' COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/' @staticmethod def create_file(rname, data, ftype='yaml'): ''' create a file in tmp with name and contents''' path = os.path.join('/tmp', rname) with open(path, 'w') as fds: if ftype == 'yaml': fds.write(yaml.safe_dump(data, default_flow_style=False)) elif ftype == 'json': fds.write(json.dumps(data)) else: fds.write(data) # Register cleanup when module is done atexit.register(Utils.cleanup, [path]) return path @staticmethod def global_compute_url(project, collection, rname): '''build the global compute url for a resource''' return ''.join([Utils.COMPUTE_URL_BASE, 'projects/', project, '/global/', collection, '/', rname]) @staticmethod def zonal_compute_url(project, zone, collection, rname): '''build the zone compute url for a resource''' return ''.join([Utils.COMPUTE_URL_BASE, 'projects/', project, '/zones/', zone, '/', collection, '/', rname]) @staticmethod def generate_random_name(size): '''generate a random string of lowercase and digits the length of size''' return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(size)) @staticmethod def cleanup(files): '''Clean up on exit ''' for sfile in files: if os.path.exists(sfile): if os.path.isdir(sfile): shutil.rmtree(sfile) elif os.path.isfile(sfile): os.remove(sfile) # pylint: disable=too-many-instance-attributes class GcloudDeploymentManagerManifests(GcloudCLI): ''' Class to wrap the gcloud deployment manager ''' # pylint allows 5 # pylint: disable=too-many-arguments def __init__(self, deployment, mname=None, verbose=False): ''' Constructor for GcloudDeploymentManagerManifests ''' super(GcloudDeploymentManagerManifests, self).__init__(verbose=True) self.deployment = deployment self.name = mname self.verbose = verbose def list_manifests(self): '''return manifest''' results = self._list_manifests(self.deployment, self.name) #if results['returncode'] == 0: #results['results'] = yaml.load(results['results']) return results # vim: expandtab:tabstop=4:shiftwidth=4 #pylint: disable=too-many-branches def main(): ''' ansible module for gcloud deployment-manager manifests ''' module = AnsibleModule( argument_spec=dict( # credentials state=dict(default='list', type='str', choices=['list']), name=dict(default=None, type='str'), deployment=dict(required=True, default=None), ), supports_check_mode=True, ) gconfig = GcloudDeploymentManagerManifests(module.params['deployment'], module.params['name']) state = module.params['state'] api_rval = gconfig.list_manifests() ##### # Get ##### if state == 'list': module.exit_json(changed=False, results=api_rval['results'], state="list") module.exit_json(failed=True, changed=False, results='Unknown state passed. %s' % state, state="unknown") #if __name__ == '__main__': # gcloud = GcloudDeploymentManager('optestgcp') # print gcloud.list_deployments() # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled # import module snippets. This are required from ansible.module_utils.basic import * main()
# coding=utf-8 # Copyright 2022 The Edward2 Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 # pytype: disable=attribute-error """Benchmark script for the wheel bandit task. """ import os import pickle import time from absl import app from absl import flags from experimental.attentive_uncertainty import attention # local file import from experimental.attentive_uncertainty.contextual_bandits import offline_contextual_bandits # local file import from experimental.attentive_uncertainty.contextual_bandits import online_contextual_bandits # local file import import numpy as np import tensorflow.compat.v1 as tf from deep_contextual_bandits import contextual_bandit # local file import from deep_contextual_bandits import neural_linear_sampling # local file import from deep_contextual_bandits import posterior_bnn_sampling # local file import from deep_contextual_bandits import uniform_sampling # local file import from tensorflow.contrib import training as contrib_training gfile = tf.compat.v1.gfile tf.compat.v1.enable_eager_execution() FLAGS = flags.FLAGS FLAGS.set_default('alsologtostderr', True) flags.DEFINE_string( 'logdir', '/tmp/bandits/', 'Base directory to save output.') flags.DEFINE_integer( 'trial_idx', 0, 'Rerun idx of problem instance.') flags.DEFINE_float( 'delta', 0.5, 'delta parameter for wheel bandit instance.') flags.DEFINE_string( 'modeldir', '/tmp/wheel_bandit/models/multitask', 'Directory with pretrained models.') flags.DEFINE_string( 'savedir', '/tmp/wheel_bandit/results/', 'Directory with saved pkl files for full results.') flags.DEFINE_string( 'ckptdir', '/tmp/wheel_bandit/ckpts/', 'Directory with saved pkl files for full ckpts.') flags.DEFINE_string( 'datasetdir', '/tmp/wheel_bandit/data/', 'Directory with saved data instances.') flags.DEFINE_integer( 'exp_idx', 0, 'Experiment idx of full run.') flags.DEFINE_string( 'prefix', 'best_', 'Prefix of best model ckpts.') flags.DEFINE_string( 'suffix', '_mse.ckpt', 'Suffix of best model ckpts.') flags.DEFINE_list( 'algo_names', ['uniform', 'snp_posterior_gp_offline'], 'List of algorithms to benchmark.') context_dim = 2 num_actions = 5 def run_contextual_bandit(dataset, algos, save_once=False, pkl_file=None): """Run a contextual bandit problem on a set of algorithms. Args: dataset: Matrix where every row is a context + num_actions rewards. algos: List of algorithms to use in the contextual bandit instance. save_once: True if state has been saved once before pkl_file: pickle file for saving state. Returns: h_actions: Matrix with actions: size (num_context, num_algorithms). h_rewards: Matrix with rewards: size (num_context, num_algorithms). """ num_contexts = dataset.shape[0] # Create contextual bandit cmab = contextual_bandit.ContextualBandit(context_dim, num_actions) cmab.feed_data(dataset) if not save_once or pkl_file is None: h_actions = np.empty((0, len(algos)), float) h_rewards = np.empty((0, len(algos)), float) start_context = 0 else: with gfile.Open(pkl_file, 'rb') as infile: saved_state = pickle.load(infile) start_context = saved_state['start_context'] algos[0].data_h.replace_data( saved_state['contexts'], saved_state['actions'], saved_state['rewards']) h_actions = saved_state['h_actions'] h_rewards = saved_state['h_rewards'] # Run the contextual bandit process for i in range(start_context, num_contexts): context = cmab.context(i) actions = [a.action(context) for a in algos] rewards = [cmab.reward(i, action) for action in actions] for j, a in enumerate(algos): a.update(context, actions[j], rewards[j]) h_actions = np.vstack((h_actions, np.array(actions))) h_rewards = np.vstack((h_rewards, np.array(rewards))) if (i+1) % 500 == 0 and pkl_file is not None: savedict = {'h_rewards': h_rewards, 'h_actions': h_actions, 'contexts': algos[0].data_h.contexts, 'actions': algos[0].data_h.actions, 'rewards': algos[0].data_h.rewards, 'start_context': i+1} with gfile.Open(pkl_file, 'wb') as outfile: pickle.dump(savedict, outfile) return h_actions, h_rewards def run_trial(trial_idx, delta, algo_names): """Runs a trial of wheel bandit problem instance for a set of algorithms.""" all_algo_names = '_'.join(algo_names) runfile = str(delta) + '_' + str(trial_idx) + '_' + all_algo_names + '.pkl' savefile = os.path.join(FLAGS.savedir, runfile) if gfile.Exists(savefile): print('File exists...terminating') with gfile.Open(savefile, 'rb') as infile: saved_state = pickle.load(infile, encoding='latin-1') return saved_state['h_rewards'], saved_state['time'] filename = os.path.join( FLAGS.datasetdir, str(delta) + '_' + str(trial_idx) + '.npz') with gfile.GFile(filename, 'r') as f: sampled_vals = np.load(f) dataset = sampled_vals['dataset'] x_hidden_size = 100 x_encoder_sizes = [x_hidden_size]*2 algos = [] ckptfile = None save_once = False for algo_name in algo_names: if algo_name == 'uniform': hparams = contrib_training.HParams(num_actions=num_actions) algos.append(uniform_sampling.UniformSampling(algo_name, hparams)) elif algo_name == 'neurolinear': hparams = contrib_training.HParams( num_actions=num_actions, context_dim=context_dim, init_scale=0.3, activation=tf.nn.relu, output_activation=tf.nn.relu, layer_sizes=x_encoder_sizes, batch_size=512, activate_decay=True, initial_lr=0.1, max_grad_norm=5.0, show_training=False, freq_summary=1000, buffer_s=-1, initial_pulls=2, reset_lr=True, lr_decay_rate=0.5, training_freq=1, training_freq_network=20, training_epochs=50, a0=12, b0=30, lambda_prior=23) algos.append(neural_linear_sampling.NeuralLinearPosteriorSampling( algo_name, hparams)) elif algo_name == 'multitaskgp': hparams_gp = contrib_training.HParams( num_actions=num_actions, num_outputs=num_actions, context_dim=context_dim, reset_lr=False, learn_embeddings=True, max_num_points=1000, show_training=False, freq_summary=1000, batch_size=512, keep_fixed_after_max_obs=True, training_freq=20, initial_pulls=2, training_epochs=50, lr=0.01, buffer_s=-1, initial_lr=0.001, lr_decay_rate=0.0, optimizer='RMS', task_latent_dim=5, activate_decay=False) algos.append(posterior_bnn_sampling.PosteriorBNNSampling( algo_name, hparams_gp, 'GP')) elif algo_name[:3] == 'snp' or algo_name[:3] == 'anp': hidden_size = 64 latent_units = 32 global_latent_net_sizes = [hidden_size]*2 + [2*latent_units] if algo_name[:3] == 'snp': local_latent_net_sizes = [hidden_size]*3 + [2] else: local_latent_net_sizes = [hidden_size]*3 + [2*5] x_y_encoder_sizes = [hidden_size]*3 heteroskedastic_net_sizes = None mean_att_type = attention.laplace_attention scale_att_type_1 = attention.laplace_attention scale_att_type_2 = attention.laplace_attention att_type = 'multihead' att_heads = 8 data_uncertainty = False is_anp = True if algo_name[:3] == 'anp' else False hparams = contrib_training.HParams( num_actions=num_actions, context_dim=context_dim, init_scale=0.3, activation=tf.nn.relu, output_activation=tf.nn.relu, x_encoder_sizes=x_encoder_sizes, x_y_encoder_sizes=x_y_encoder_sizes, global_latent_net_sizes=global_latent_net_sizes, local_latent_net_sizes=local_latent_net_sizes, heteroskedastic_net_sizes=heteroskedastic_net_sizes, att_type=att_type, att_heads=att_heads, mean_att_type=mean_att_type, scale_att_type_1=scale_att_type_1, scale_att_type_2=scale_att_type_2, data_uncertainty=data_uncertainty, batch_size=512, activate_decay=True, initial_lr=0.1, max_grad_norm=5.0, show_training=False, freq_summary=1000, buffer_s=-1, initial_pulls=2, reset_lr=True, lr_decay_rate=0.5, training_freq=10, training_freq_network=20, training_epochs=50, uncertainty_type='attentive_freeform', local_variational=True, model_path=None, is_anp=is_anp) config = algo_name.split('_') if config[1] == 'prior': hparams.set_hparam('local_variational', False) if config[2] == 'gp': hparams.set_hparam('uncertainty_type', 'attentive_gp') if config[3] == 'warmstart' or config[3] == 'offline': mfile = FLAGS.prefix + config[1] + '_' + config[2] + FLAGS.suffix if algo_name[:3] == 'anp': mfile = 'anp_' + mfile mpath = os.path.join(FLAGS.modeldir, mfile) hparams.set_hparam('model_path', mpath) if config[3] == 'online' or config[3] == 'warmstart': algos.append(online_contextual_bandits.OnlineContextualBandits( algo_name, hparams)) else: algos.append(offline_contextual_bandits.OfflineContextualBandits( algo_name, hparams)) ckptfile = os.path.join(FLAGS.ckptdir, runfile) if gfile.Exists(ckptfile): save_once = True t_init = time.time() print('started') _, h_rewards = run_contextual_bandit( dataset, algos, save_once=save_once, pkl_file=ckptfile) t_final = time.time() savedict = {'h_rewards': h_rewards, 'time': t_final-t_init} with gfile.Open(savefile, 'wb') as outfile: pickle.dump(savedict, outfile) return h_rewards, t_final - t_init def main(_): run_trial(FLAGS.trial_idx, FLAGS.delta, FLAGS.algo_names) if __name__ == '__main__': app.run(main)
import os.path as _path import h5py import numpy as np import tracklets as _ts import track as _track def __loadDataset( filename, h5path): '''Load a dataset from a hdf5 file as a numpy array. filename: path to hdf5 file as a string h5path: location of the data inside the hdf5 file ''' f = h5py.File( filename, mode='r' ) data = f[h5path].value f.close() return data def __loadDatasets( filenames, h5path): '''Load the same dataset from different files. Works for a sequence of files or a single file. Returns just the dataset in the latter case. filenames: path to hdf5 file(s) as a string or a sequence of strings. h5path: location of the data inside the hdf5 file ''' if(isinstance(filenames, str)): return __loadDataset(filenames, h5path) else: def loader( filename ): return __loadDataset(filename, h5path) return map(loader, filenames) def loadRaw( filenames, h5path = "raw/volume"): '''Load raw data from hdf5 file(s) as a numpy array. filenames: path to hdf5 file(s) as a string or a sequence of strings. h5path: location of the data inside the hdf5 file ''' return __loadDatasets( filenames, h5path) def iterRaw( filenames, h5path = "raw/volume" ): '''Similar to loadRaw, but returns an interator instead.''' for filename in filenames: yield __loadDatasets( filename, h5path ) def loadSegmentation( filenames, h5path = "segmentation/volume"): '''Load segmentation results from hdf5 file(s) as a numpy array. filenames: path to hdf5 file(s) as a string or a sequence of strings. h5path: location of the data inside the hdf5 file ''' return __loadDatasets( filenames, h5path) def iterSegmentation( filenames, h5path = "raw/volume" ): '''Similar to loadSegmentation, but returns an interator instead.''' for filename in filenames: yield __loadDatasets( filename, h5path ) def filenames(path, range = xrange(1,11)): '''Generate a list of filenames from a template. path: a filename template; for instance "/data/file_%03d.h5" range: list of numbers ''' return map(lambda i: path % i, range) def write_visbricks_file( h5_filenames, out_dir, visbricks_fn = "visbricks_time-dependent-h5.txt"): visbricks_fn = _path.join(out_dir, visbricks_fn) with open( visbricks_fn, 'w') as f: f.write("0 " + str(len(h5_filenames)-1) + "\n") for fn in h5_filenames: f.write(_path.abspath(fn)+"\n") def tracklet_from_labelgroup( h5_labelgroup, timestep = None, position = 'mean', add_features_as_meta = True): '''Construct a Tracklet instance from a hdf5 group describing a featureset (a.k.a. "labelgroup"). The id will be set to the name of the hdf5 labelgroup (converted to int; make sure it is convertible). h5_labelgroup - a h5py.Group instance timestep - Tracklet t coordinate position - "mean" or "max" -> use either intensity weighted mean position or maximum intensity position of the connected component as the Tracklet coordinates. add_features_as_meta - If true, add all features as meta information to the Tracklet. ''' if position not in ['mean', 'max']: raise ValueError('tracklet_from_labelgroup: invalid position: ' + str(position)) pos_feat = 'com' if position == 'mean' else 'intmaxpos' if pos_feat not in h5_labelgroup.keys(): raise Exception(position + " feature not present in label group " + str(h5_labelgroup)) # read out coordinates if pos_feat == 'com': x,y,z = h5_labelgroup[pos_feat][0], h5_labelgroup[pos_feat][1], h5_labelgroup[pos_feat][2] else: x,y,z = h5_labelgroup[pos_feat][1], h5_labelgroup[pos_feat][2], h5_labelgroup[pos_feat][3] the_tracklet = _ts.Tracklet(x,y,z, timestep, int(_path.basename(h5_labelgroup.name))) # add features as meta if add_features_as_meta == True: def add_as_meta(name, obj): if isinstance(obj, h5py.Dataset): the_tracklet.meta[name] = obj.value h5_labelgroup.visititems(add_as_meta) return the_tracklet def ctracklet_from_labelgroup( h5_labelgroup ): the_tracklet = _track.cTracklet() # set tracklet id the_tracklet.ID = int(_path.basename(h5_labelgroup.name)) # add features def add_feature(name, obj): if isinstance(obj, h5py.Dataset): the_tracklet.add_feature_array(name, len(obj.value)) for i,v in enumerate(obj.value): the_tracklet.set_feature_value(name, i, float(v)) h5_labelgroup.visititems(add_feature) return the_tracklet class LineageH5( h5py.File ): mov_ds = "/tracking/Moves" mov_ener_ds = "/tracking/Moves-Energy" merg_ds = "/tracking/Mergers" merg_ener_ds = "tracking/Mergers-Energy" multi_ds = "/tracking/MultiFrameMoves" multi_ener_ds = "tracking/MultiFrameMoves-Energy" app_ds = "/tracking/Appearances" app_ener_ds = "/tracking/Appearances-Energy" dis_ds = "/tracking/Disappearances" dis_ener_ds = "/tracking/Disappearances-Energy" div_ds = "/tracking/Splits" div_ener_ds = "/tracking/Splits-Energy" feat_gn = "/features" track_gn = "/tracking/" @property def x_scale( self ): return self._x_scale @x_scale.setter def x_scale( self, scale ): self._x_scale = scale @property def y_scale( self ): return self._y_scale @y_scale.setter def y_scale( self, scale ): self._y_scale = scale @property def z_scale( self ): return self._z_scale @z_scale.setter def z_scale( self, scale ): self._z_scale = scale # timestep will be set in loaded traxels accordingly def __init__( self, *args, **kwargs): h5py.File.__init__(self, *args, **kwargs) if "timestep" in kwargs: self.timestep = kwargs["timestep"] else: self.timestep = 0 self._x_scale = 1.0 self._y_scale = 1.0 self._z_scale = 1.0 def init_tracking( self, div=np.empty(0), mov=np.empty(0), dis=np.empty(0), app=np.empty(0)): if "tracking" in self.keys(): del self["tracking"] self.create_group("tracking") def has_tracking( self ): if "tracking" in self.keys(): return True else: return False def add_move( self, from_id, to_id): n_moves = self[self.mov_ds].shape[0]; movs = self.get_moves() new = np.vstack([movs, (from_id, to_id)]) self.update_moves(new) def update_moves( self, mov_pairs ): if _path.basename(self.mov_ds) in self[self.track_gn].keys(): del self[self.mov_ds] if len(mov_pairs) > 0: self[self.track_gn].create_dataset("Moves", data=np.asarray( mov_pairs, dtype=np.int32)) def get_moves( self ): if self.has_tracking() and _path.basename(self.mov_ds) in self[self.track_gn].keys(): return self[self.mov_ds].value else: return np.empty(0) def get_mergers( self ): if self.has_tracking() and _path.basename(self.merg_ds) in self[self.track_gn].keys(): return self[self.merg_ds].value else: return np.empty(0) def get_multiFrameMoves( self ): if self.has_tracking() and _path.basename(self.multi_ds) in self[self.track_gn].keys(): return self[self.multi_ds].value else: return np.empty(0) def get_move_energies( self ): if _path.basename(self.mov_ener_ds) in self[self.track_gn].keys(): e = self[self.mov_ener_ds].value if isinstance(e, np.ndarray): return e else: return np.array([e]) else: return np.empty(0) def get_divisions( self ): if self.has_tracking() and _path.basename(self.div_ds) in self[self.track_gn].keys(): return self[self.div_ds].value else: return np.empty(0) def update_divisions( self, div_triples ): if _path.basename(self.div_ds) in self[self.track_gn].keys(): del self[self.div_ds] if len(div_triples) > 0: self[self.track_gn].create_dataset("Splits", data=np.asarray( div_triples, dtype=np.int32)) def get_division_energies( self ): if _path.basename(self.div_ener_ds) in self[self.track_gn].keys(): e = self[self.div_ener_ds].value if isinstance(e, np.ndarray): return e else: return np.array([e]) else: return np.empty(0) def get_disappearances( self ): if self.has_tracking() and _path.basename(self.dis_ds) in self[self.track_gn].keys(): dis = self[self.dis_ds].value if isinstance(dis, np.ndarray): return dis else: return np.array([dis]) else: return np.empty(0) def update_disappearances( self, dis_singlets ): if _path.basename(self.dis_ds) in self[self.track_gn].keys(): del self[self.dis_ds] if len(dis_singlets) > 0: self[self.track_gn].create_dataset("Disappearances", data=np.asarray( dis_singlets, dtype=np.int32)) def get_disappearance_energies( self ): if _path.basename(self.dis_ener_ds) in self[self.track_gn].keys(): e = self[self.dis_ener_ds].value if isinstance(e, np.ndarray): return e else: return np.array([e]) else: return np.empty(0) def get_appearances( self ): if self.has_tracking() and _path.basename(self.app_ds) in self[self.track_gn].keys(): app = self[self.app_ds].value if isinstance(app, np.ndarray): return app else: return np.array([app]) else: return np.empty(0) def update_appearances( self, app_singlets ): if _path.basename(self.app_ds) in self[self.track_gn].keys(): del self[self.app_ds] if len(app_singlets) > 0: self[self.track_gn].create_dataset("Appearances", data=np.asarray( app_singlets, dtype=np.int32)) def get_appearance_energies( self ): if _path.basename(self.app_ener_ds) in self[self.track_gn].keys(): e = self[self.app_ener_ds].value if isinstance(e, np.ndarray): return e else: return np.array([e]) else: return np.empty(0) def rm_appearance( self, id ): apps = self.get_appearances() if not id in apps: raise Exception("LineageH5::rm_appearance(): id %d not an appearance" % id) filtered = apps[apps!=id] b = np.empty(dtype=apps.dtype, shape=(filtered.shape[0], 1)) b[:,0] = filtered[:] self.update_appearances( b ) def rm_disappearance( self, id ): diss = self.get_disappearances() if not id in diss: raise Exception("LineageH5::rm_disappearance(): id %d not an disappearance" % id) filtered = diss[diss!=id] b = np.empty(dtype=diss.dtype, shape=(filtered.shape[0], 1)) b[:,0] = filtered[:] self.update_disappearances( b ) def get_ids( self ): features_group = self[self.feat_gn] labelcontent = features_group["labelcontent"].value valid_labels = (np.arange(len(labelcontent))+1)[labelcontent==1] return valid_labels def Tracklets( self , timestep=None, position='mean', add_features_as_meta=True): valid_labels = self.get_ids() features_group = self[self.feat_gn] tracklets = _ts.Tracklets([tracklet_from_labelgroup( features_group[str(label)], timestep=timestep, add_features_as_meta = add_features_as_meta, position=position ) for label in valid_labels]) return tracklets def Traxels( self , timestep=None, position='mean', add_features_as_meta=True): return self.Tracklets( timestep, position, add_features_as_meta ) def cTraxels( self, as_python_list=False, prediction_threshold=None ): if prediction_threshold: print "LineageH5::cTraxels: predicition threshold %f" % prediction_threshold # probe for objects group (higher io performance than features group) if 'objects' in self.keys(): return self._cTraxels_from_objects_group( as_python_list, prediction_threshold ) # use old 'features' format for traxels else: raise Exception("objects group not found") #if as_python_list or prediction_threshold: # raise Exception("LineageH5::cTraxels: old format: requested options not implemented") #return self._cTraxels_from_features_group() def _cTraxels_from_objects_group( self , as_python_list = False, prediction_threshold=None): objects_g = self["objects"] features_g = self["objects/features"] ids = objects_g["meta/id"].value valid = objects_g["meta/valid"].value prediction = None if "prediction" in objects_g["meta"]: prediction = objects_g["meta/prediction"] elif prediction_threshold: raise Exception("prediction_threshold set, but no prediction dataset found") features = {} for name in features_g.keys(): features[name] = features_g[name].value if as_python_list: ts = list() else: ts = _track.cTraxels() for idx, is_valid in enumerate(valid): if prediction_threshold: if prediction[idx] < prediction_threshold: is_valid = False if is_valid: tr = _track.cTraxel() #tr.set_intmaxpos_locator() tr.set_x_scale(self._x_scale) tr.set_y_scale(self._y_scale) tr.set_z_scale(self._z_scale) tr.Id = int(ids[idx]) tr.Timestep = self.timestep for name_value in features.items(): tr.add_feature_array(str(name_value[0]), len(name_value[1][idx])) for i,v in enumerate(name_value[1][idx]): tr.set_feature_value(str(name_value[0]), i, float(v)) if as_python_list: ts.append(tr) else: ts.add_traxel(tr) return ts def _cTraxels_from_features_group( self ): features_group = self[self.feat_gn] labelcontent = features_group["labelcontent"].value invalid_labels = (np.arange(len(labelcontent))+1)[labelcontent==0] # note, that we used the ctracklet_from_labelgroup() here before, but had # to replace it by the following code due to bad performance ts = _track.cTraxels() # state machine for parsing features group class Harvester( object ): def __init__( self, invalid_labels=[], timestep=0): self.current_ctracklet = None self.timestep = timestep self.invalid_labels = map(int, invalid_labels ) def __call__(self, name, obj): # name is the full path inside feature group # entering a new label group... if name.isdigit(): # store away the last cTraxel if self.current_ctracklet != None: ts.add_traxel(self.current_ctracklet) if int(name) in self.invalid_labels: self.current_ctracklet = None print "invalid!" else: self.current_ctracklet = _track.cTraxel() self.current_ctracklet.Id = int(name) self.current_ctracklet.Timestep = self.timestep elif name == 'featurecontent' or name == 'labelcontent' or name == 'labelcount': pass else: feature_name = _path.basename(name) self.current_ctracklet.add_feature_array(str(feature_name), len(obj.value)) for i,v in enumerate(obj.value): self.current_ctracklet.set_feature_value(str(feature_name), i, float(v)) harvest = Harvester(invalid_labels, self.timestep) features_group.visititems(harvest) return ts import unittest as ut import numpy as np two_labels_fn = "test_data/io/two_labels.h5" class Test_LineageH5( ut.TestCase ): def test_Tracklets( self ): with LineageH5( two_labels_fn, 'r' ) as f: trs = f.Tracklets() self.assertEqual( len(trs.the) , 2 ) def test_cTraxels( self ): with LineageH5( two_labels_fn, 'r' ) as f: trs = f.cTraxels() self.assertEqual( len(trs) , 2 ) class Test_tracklet_from_labelgroup( ut.TestCase ): def setUp( self ): self.f = h5py.File( two_labels_fn ) self.labelgroup_23 = self.f['/features/23'] self.labelgroup_41 = self.f['/features/41'] def test_default( self ): tr = tracklet_from_labelgroup( self.labelgroup_23 ) self.assertAlmostEqual(tr.x, 480.346, places = 3) self.assertAlmostEqual(tr.y, 594.464, places = 3) self.assertAlmostEqual(tr.z, 80.469, places = 3) self.assertEqual( (tr.t, tr.id), (None, 23) ) self.assertEqual( len(tr.meta), 16 ) # some spot tests self.assertTrue( tr.meta.has_key("com") ) self.assertTrue( tr.meta.has_key("intmaxpos") ) self.assertTrue( np.all(tr.meta['intmaxpos'] == np.asarray([767.0, 480.0, 591.0, 79.0]))) def test_max_position( self ): tr = tracklet_from_labelgroup( self.labelgroup_23, timestep=44, position='max' ) self.assertEqual(tr.x, 480.0) self.assertEqual(tr.y, 591.0) self.assertEqual(tr.z, 79.0) self.assertEqual( (tr.t, tr.id), (44, 23) ) self.assertEqual( len(tr.meta), 16 ) def test_no_meta( self ): tr = tracklet_from_labelgroup( self.labelgroup_23, add_features_as_meta=False ) self.assertEqual( len(tr.meta), 0 ) def tearDown( self ): del self.labelgroup_23 del self.labelgroup_41 self.f.close() del self.f if __name__=='__main__': ut.main()
from __init__ import app from flask import request, json from models import * from grumpy import generate_token, verify_token from datetime import datetime from counters import increment_counter, decrement_counter, get_counter from front_end import Data from sklearn.linear_model import LogisticRegression import pickle @app.route("/") def hello(): return "Guard Dog API v0.2.0" @app.route("/sign_up", methods=["POST"]) def sign_up(): obj = request.get_json(force=True) if obj and obj.get("username") and obj.get("phone_number") and obj.get("password"): if not User.get_from_db(obj["username"]): new_user = User() new_user.username = obj["username"] new_user.phone_number = obj["phone_number"] new_user.set_password(obj["password"]) new_user.write_to_db() increment_counter('users-count') dump = {"token": generate_token(new_user.username, new_user.secret_key, datetime.now())} return json.dumps(dump) else: return "You are already a registered user", 401 else: return "Malformed request", 401 @app.route("/log_in", methods=["POST"]) def log_in(): if request.method == "POST": obj = request.get_json(force=True) if obj and obj.get("username") and obj.get("password"): user = User.get_from_db(obj["username"]) if user and user.verify_password(obj["password"]): dump = {"token": generate_token(user.username, user.secret_key, datetime.now())} return json.dumps(dump) else: return "Invalid username/password combo", 401 else: return "Malformed request", 401 @app.route("/log_out", methods=["POST"]) def logout(): if request.method == "POST": obj = request.get_json(force=True) if obj and obj.get("token"): token_elements = obj.get("token").split(":") user = User.get_from_db(token_elements[0]) if user and verify_token(user, obj["token"]): user.deauthenticate() user.write_to_db() return "Great success" else: return "Malformed request", 401 else: print "Malformed request", 401 @app.route("/modify_emergency_contact", methods=["POST"]) def add_emergency_contact(): obj = request.get_json(force=True) if obj and obj.get("token") and obj.get("phone_number"): token_elements = obj.get("token").split(":") user = User.get_from_db(token_elements[0]) if user and verify_token(user, obj["token"]): user.emergency_contact = obj["emergency_contact"] user.write_to_db() return json.dumps(user.emergency_contact) else: return "Could not verify user", 401 else: return "Malformed request", 401 @app.route("/add_contact", methods=["POST"]) def add_contact(): obj = request.get_json(force=True) if obj and obj.get("token") and obj.get("phone_number"): token_elements = obj.get("token").split(":") user = User.get_from_db(token_elements[0]) if user and verify_token(user, obj["token"]): user.contacts.add(obj["phone_number"]) user.write_to_db() increment_counter('contacts-count') return json.dumps(list(user.contacts)) else: return "Could not verify user", 401 else: return "Malformed request", 401 @app.route("/remove_contact", methods=["POST"]) def remove_contact(): obj = request.get_json(force=True) if obj and obj.get("token") and obj.get("phone_number"): token_elements = obj.get("token").split(":") user = User.get_from_db(token_elements[0]) if user and verify_token(user, obj["token"]): if obj["phone_number"] in user.contacts: user.contacts.remove(obj["phone_number"]) user.write_to_db() decrement_counter('contacts-count') return json.dumps(list(user.contacts)) else: return "Could not verify user", 401 else: return "Malformed request", 401 @app.route("/classify", methods=["POST"]) def classify(): obj = request.get_json(force=True) if obj and obj.get("token") and obj.get("batch-phone") and obj.get("batch-pebble"): token_elements = obj.get("token").split(":") user = User.get_from_db(token_elements[0]) if user and verify_token(user, obj["token"]): batch_phone = obj["batch-phone"] batch_pebble = obj["batch-pebble"] data = Data(batch_phone, batch_pebble).data_array() past_data = redis_db.get(user.username + ":ml") if past_data: regression_engine = pickle.loads(past_data) else: regression_engine = LogisticRegression() d = regression_engine.predict(data) print d guess = bool(d) response_dict = {"guess": guess, "content": obj} return json.dumps(response_dict) else: return "Could not verify user", 401 else: return "Malformed request", 401 @app.route("/correct", methods=["POST"]) def correct(): obj = request.get_json(force=True) if obj and obj.get("token") and obj.get("batch-phone") and obj.get("batch-pebble") and obj.get("answer"): token_elements = obj.get("token").split(":") user = User.get_from_db(token_elements[0]) if user and verify_token(user, obj["token"]): batch_phone = obj["batch-phone"] batch_pebble = obj["batch-pebble"] data = Data(batch_phone, batch_pebble).data_array() past_data = redis_db.get(user.username + ":ml") if past_data: regression_engine = pickle.loads(past_data) else: regression_engine = LogisticRegression() answer = int(obj["answer"]) regression_engine.fit(data, [answer]) redis_db.set(user.username + ":ml", pickle.dumps(regression_engine)) return "Great success" else: return "Malformed request", 401 else: return "Malformed request", 401 @app.route("/train", methods=["POST"]) def train(): obj = request.get_json(force=True) print obj.get("batch-phone") + " " + obj.get("batch-pebble") + " " + obj.get("answer") if obj and obj.get("batch-phone") and obj.get("batch-pebble") and obj.get("answer"): batch_phone = obj["batch-phone"] batch_pebble = obj["batch-pebble"] data = Data(batch_phone, batch_pebble).data_array() past_data = redis_db.get("learning-data") if past_data: regression_engine = pickle.loads(past_data) else: regression_engine = LogisticRegression() answer = int(obj["answer"]) regression_engine.fit(data, [answer]) redis_db.set("learning-data") return "Great success" else: return "Malformed request", 401 @app.route("/stats", methods=["GET"]) def stats(): public_stats = ['users-count', 'contacts-count'] res_data = {} for stat_name in public_stats: res_data[stat_name] = get_counter(stat_name) return json.dumps(res_data), 200
"""Tests for get_kf_testing_cluster.""" import json import os import unittest from googleapiclient.http import HttpMockSequence from kubeflow.testing import get_kf_testing_cluster # pylint: disable=no-name-in-module TEST_PROJECT = "kubeflow-ci-foo" TEST_LABEL = "kf-foo-label" class Deployment: """Simple data carrier for a deployment.""" def __init__(self, name, insert_time, zone="us-west1-b"): self.name = name self.insert_time = insert_time self.zone = zone def create_mock_list_resp(deployments): """Given a list of Deployment, transforms into a list of dictionaries as API response""" data = [] for d in deployments: data.append({ "name": d.name, "labels": [ { "purpose": TEST_LABEL, }, ], "insertTime": d.insert_time, }) return data def create_mock_resource_resp(dm): """Given an instance of Deployment, transforms into resource info as API response.""" return { "name": dm.name, "insertTime": dm.insert_time, "properties": "zone: " + dm.zone, } def create_expected_list_resp(deployments): """Helper method to create expected responses from get_kf_testing_cluster.list_deployments""" data = [] for d in deployments: data.append({ "name": d.name, "endpoint": get_kf_testing_cluster.get_deployment_endpoint(TEST_PROJECT, d.name), "insertTime": d.insert_time, "zone": d.zone, }) return data class GetKfTestingClusterTest(unittest.TestCase): def setUp(self): with open(os.path.join(os.path.dirname(__file__), "test-data", "deploymentmanager-v2.json")) as f: self.dm_api = f.read() def test_list_deployments(self): deployments = [ Deployment("kf-vfoo-n00", "2019-04-01T23:59:59+00:00"), Deployment("kf-vfoo-n01", "2019-04-02T23:59:59+00:00"), Deployment("kf-vfoo-n02", "2019-04-03T23:59:59+00:00"), ] list_resp = { "deployments": create_mock_list_resp(deployments), } http = HttpMockSequence([ ({'status': '200'}, self.dm_api), ({'status': '200'}, json.dumps(list_resp)), ({"status": "200"}, json.dumps(create_mock_resource_resp(deployments[0]))), ({"status": "200"}, json.dumps(create_mock_resource_resp(deployments[1]))), ({"status": "200"}, json.dumps(create_mock_resource_resp(deployments[2]))), ]) actual = get_kf_testing_cluster.list_deployments(TEST_PROJECT, "kf-vfoo", TEST_LABEL, http=http) expected = sorted(create_expected_list_resp(deployments), key=lambda entry: entry["insertTime"], reverse=True) self.assertListEqual(actual, expected) def test_list_deployments_name_filter(self): deployments = [ Deployment("kf-vfoo-n00", "2019-04-01T23:59:59+00:00"), Deployment("kf-vfoo-n01", "2019-04-02T23:59:59+00:00"), Deployment("kf-vfoo-n02-storage", "2019-04-03T23:59:59+00:00"), ] list_resp = { "deployments": create_mock_list_resp(deployments), } http = HttpMockSequence([ ({'status': '200'}, self.dm_api), ({'status': '200'}, json.dumps(list_resp)), ({"status": "200"}, json.dumps(create_mock_resource_resp(deployments[0]))), ({"status": "200"}, json.dumps(create_mock_resource_resp(deployments[1]))), ]) actual = get_kf_testing_cluster.list_deployments(TEST_PROJECT, "kf-vfoo", TEST_LABEL, http=http) expected = sorted(create_expected_list_resp(deployments[0:2]), key=lambda entry: entry["insertTime"], reverse=True) self.assertListEqual(actual, expected) def test_list_deployments_default_insertime(self): """Verify behavior when one of the deployments is missing a timestamp.""" deployments = [ Deployment("kf-vfoo-00", "2019-04-01T23:59:59+00:00"), Deployment("kf-vfoo-01", "2019-04-02T23:59:59+00:00"), Deployment("kf-vfoo-02", "2019-04-03T23:59:59+00:00"), ] list_resp = { "deployments": create_mock_list_resp(deployments), } # Remove insertTime for the method to attach default timestamp. list_resp["deployments"][-1].pop("insertTime", None) http = HttpMockSequence([ ({'status': '200'}, self.dm_api), ({'status': '200'}, json.dumps(list_resp)), ({"status": "200"}, json.dumps(create_mock_resource_resp(deployments[0]))), ({"status": "200"}, json.dumps(create_mock_resource_resp(deployments[1]))), ({"status": "200"}, json.dumps(create_mock_resource_resp(deployments[2]))), ]) actual = get_kf_testing_cluster.list_deployments(TEST_PROJECT, "kf-vfoo-??", TEST_LABEL, http=http) expected = create_expected_list_resp(deployments) # Since the last deployment doesn't have an insertTime it will be ignored expected = expected[0:2] expected.sort(key=lambda entry: entry["insertTime"], reverse=True) self.assertListEqual(actual, expected) def test_list_deployments_multi_pages(self): deployments = [ Deployment("kf-vfoo-n00", "2019-04-01T23:59:59+00:00"), Deployment("kf-vfoo-n01", "2019-04-02T23:59:59+00:00"), Deployment("kf-vfoo-n02", "2019-04-03T23:59:59+00:00"), ] list_resp1 = { "deployments": create_mock_list_resp(deployments[:1]), "nextPageToken": "bar", } list_resp2 = { "deployments": create_mock_list_resp(deployments[1:]), } http = HttpMockSequence([ ({'status': '200'}, self.dm_api), ({'status': '200'}, json.dumps(list_resp1)), ({"status": "200"}, json.dumps(create_mock_resource_resp(deployments[0]))), ({"status": "200"}, json.dumps(list_resp2)), ({"status": "200"}, json.dumps(create_mock_resource_resp(deployments[1]))), ({"status": "200"}, json.dumps(create_mock_resource_resp(deployments[2]))), ]) actual = get_kf_testing_cluster.list_deployments(TEST_PROJECT, "kf-vfoo", TEST_LABEL, http=http) expected = sorted(create_expected_list_resp(deployments), key=lambda entry: entry["insertTime"], reverse=True) self.assertListEqual(actual, expected) def test_get_deployment(self): deployments = [ Deployment("kf-vfoo-n00", "2019-04-01T23:59:59+00:00"), Deployment("kf-vfoo-n01", "2019-04-02T23:59:59+00:00"), Deployment("kf-vfoo-n02", "2019-04-03T23:59:59+00:00"), ] list_resp = { "deployments": create_mock_list_resp(deployments), } http = HttpMockSequence([ ({'status': '200'}, self.dm_api), ({'status': '200'}, json.dumps(list_resp)), ({"status": "200"}, json.dumps(create_mock_resource_resp(deployments[0]))), ({"status": "200"}, json.dumps(create_mock_resource_resp(deployments[1]))), ({"status": "200"}, json.dumps(create_mock_resource_resp(deployments[2]))), ({'status': '200'}, self.dm_api), ({'status': '200'}, json.dumps(list_resp)), ({"status": "200"}, json.dumps(create_mock_resource_resp(deployments[0]))), ({"status": "200"}, json.dumps(create_mock_resource_resp(deployments[1]))), ({"status": "200"}, json.dumps(create_mock_resource_resp(deployments[2]))), ]) # get latest deployment. self.assertEqual(get_kf_testing_cluster.get_deployment( TEST_PROJECT, "kf-vfoo", TEST_LABEL, http=http), get_kf_testing_cluster.get_deployment_endpoint(TEST_PROJECT, "kf-vfoo-n02")) # get oldest deployment. self.assertEqual(get_kf_testing_cluster.get_deployment( TEST_PROJECT, "kf-vfoo", TEST_LABEL, http=http, desc_ordered=False), get_kf_testing_cluster.get_deployment_endpoint(TEST_PROJECT, "kf-vfoo-n00")) def test_get_latest(self): deployments = [ Deployment("kf-vfoo-00", "2019-04-01T23:59:59+00:00"), Deployment("kf-vfoo-01", "2019-04-02T23:59:59+00:00"), Deployment("kf-vfoo-02", "2019-04-03T23:59:59+00:00"), ] list_resp = { "deployments": create_mock_list_resp(deployments), } http = HttpMockSequence([ ({'status': '200'}, self.dm_api), ({'status': '200'}, json.dumps(list_resp)), ({"status": "200"}, json.dumps(create_mock_resource_resp(deployments[0]))), ({"status": "200"}, json.dumps(create_mock_resource_resp(deployments[1]))), ({"status": "200"}, json.dumps(create_mock_resource_resp(deployments[2]))), ]) self.assertEqual(get_kf_testing_cluster.get_latest( project=TEST_PROJECT, base_name="kf-vfoo-??", http=http), get_kf_testing_cluster.get_deployment_endpoint(TEST_PROJECT, "kf-vfoo-02")) if __name__ == '__main__': unittest.main()
# Licensed under a 3-clause BSD style license - see LICENSE.rst # TEST_UNICODE_LITERALS import itertools import copy import pytest import numpy as np from .. import Time from ...utils.compat.numpy import broadcast_to as np_broadcast_to class TestManipulation(): """Manipulation of Time objects, ensuring attributes are done correctly.""" def setup(self): mjd = np.arange(50000, 50010) frac = np.arange(0., 0.999, 0.2) self.t0 = Time(mjd[:, np.newaxis] + frac, format='mjd', scale='utc') self.t1 = Time(mjd[:, np.newaxis] + frac, format='mjd', scale='utc', location=('45d', '50d')) self.t2 = Time(mjd[:, np.newaxis] + frac, format='mjd', scale='utc', location=(np.arange(len(frac)), np.arange(len(frac)))) # Note: location is along last axis only. self.t2 = Time(mjd[:, np.newaxis] + frac, format='mjd', scale='utc', location=(np.arange(len(frac)), np.arange(len(frac)))) def test_ravel(self): t0_ravel = self.t0.ravel() assert t0_ravel.shape == (self.t0.size,) assert np.all(t0_ravel.jd1 == self.t0.jd1.ravel()) assert np.may_share_memory(t0_ravel.jd1, self.t0.jd1) assert t0_ravel.location is None t1_ravel = self.t1.ravel() assert t1_ravel.shape == (self.t1.size,) assert np.all(t1_ravel.jd1 == self.t1.jd1.ravel()) assert np.may_share_memory(t1_ravel.jd1, self.t1.jd1) assert t1_ravel.location is self.t1.location t2_ravel = self.t2.ravel() assert t2_ravel.shape == (self.t2.size,) assert np.all(t2_ravel.jd1 == self.t2.jd1.ravel()) assert np.may_share_memory(t2_ravel.jd1, self.t2.jd1) assert t2_ravel.location.shape == t2_ravel.shape # Broadcasting and ravelling cannot be done without a copy. assert not np.may_share_memory(t2_ravel.location, self.t2.location) def test_flatten(self): t0_flatten = self.t0.flatten() assert t0_flatten.shape == (self.t0.size,) assert t0_flatten.location is None # Flatten always makes a copy. assert not np.may_share_memory(t0_flatten.jd1, self.t0.jd1) t1_flatten = self.t1.flatten() assert t1_flatten.shape == (self.t1.size,) assert not np.may_share_memory(t1_flatten.jd1, self.t1.jd1) assert t1_flatten.location is not self.t1.location assert t1_flatten.location == self.t1.location t2_flatten = self.t2.flatten() assert t2_flatten.shape == (self.t2.size,) assert not np.may_share_memory(t2_flatten.jd1, self.t2.jd1) assert t2_flatten.location.shape == t2_flatten.shape assert not np.may_share_memory(t2_flatten.location, self.t2.location) def test_transpose(self): t0_transpose = self.t0.transpose() assert t0_transpose.shape == (5, 10) assert np.all(t0_transpose.jd1 == self.t0.jd1.transpose()) assert np.may_share_memory(t0_transpose.jd1, self.t0.jd1) assert t0_transpose.location is None t1_transpose = self.t1.transpose() assert t1_transpose.shape == (5, 10) assert np.all(t1_transpose.jd1 == self.t1.jd1.transpose()) assert np.may_share_memory(t1_transpose.jd1, self.t1.jd1) assert t1_transpose.location is self.t1.location t2_transpose = self.t2.transpose() assert t2_transpose.shape == (5, 10) assert np.all(t2_transpose.jd1 == self.t2.jd1.transpose()) assert np.may_share_memory(t2_transpose.jd1, self.t2.jd1) assert t2_transpose.location.shape == t2_transpose.shape assert np.may_share_memory(t2_transpose.location, self.t2.location) # Only one check on T, since it just calls transpose anyway. t2_T = self.t2.T assert t2_T.shape == (5, 10) assert np.all(t2_T.jd1 == self.t2.jd1.T) assert np.may_share_memory(t2_T.jd1, self.t2.jd1) assert t2_T.location.shape == t2_T.location.shape assert np.may_share_memory(t2_T.location, self.t2.location) def test_diagonal(self): t0_diagonal = self.t0.diagonal() assert t0_diagonal.shape == (5,) assert np.all(t0_diagonal.jd1 == self.t0.jd1.diagonal()) assert t0_diagonal.location is None assert np.may_share_memory(t0_diagonal.jd1, self.t0.jd1) t1_diagonal = self.t1.diagonal() assert t1_diagonal.shape == (5,) assert np.all(t1_diagonal.jd1 == self.t1.jd1.diagonal()) assert t1_diagonal.location is self.t1.location assert np.may_share_memory(t1_diagonal.jd1, self.t1.jd1) t2_diagonal = self.t2.diagonal() assert t2_diagonal.shape == (5,) assert np.all(t2_diagonal.jd1 == self.t2.jd1.diagonal()) assert t2_diagonal.location.shape == t2_diagonal.shape assert np.may_share_memory(t2_diagonal.jd1, self.t2.jd1) assert np.may_share_memory(t2_diagonal.location, self.t2.location) def test_swapaxes(self): t0_swapaxes = self.t0.swapaxes(0, 1) assert t0_swapaxes.shape == (5, 10) assert np.all(t0_swapaxes.jd1 == self.t0.jd1.swapaxes(0, 1)) assert np.may_share_memory(t0_swapaxes.jd1, self.t0.jd1) assert t0_swapaxes.location is None t1_swapaxes = self.t1.swapaxes(0, 1) assert t1_swapaxes.shape == (5, 10) assert np.all(t1_swapaxes.jd1 == self.t1.jd1.swapaxes(0, 1)) assert np.may_share_memory(t1_swapaxes.jd1, self.t1.jd1) assert t1_swapaxes.location is self.t1.location t2_swapaxes = self.t2.swapaxes(0, 1) assert t2_swapaxes.shape == (5, 10) assert np.all(t2_swapaxes.jd1 == self.t2.jd1.swapaxes(0, 1)) assert np.may_share_memory(t2_swapaxes.jd1, self.t2.jd1) assert t2_swapaxes.location.shape == t2_swapaxes.shape assert np.may_share_memory(t2_swapaxes.location, self.t2.location) def test_reshape(self): t0_reshape = self.t0.reshape(5, 2, 5) assert t0_reshape.shape == (5, 2, 5) assert np.all(t0_reshape.jd1 == self.t0._time.jd1.reshape(5, 2, 5)) assert np.all(t0_reshape.jd2 == self.t0._time.jd2.reshape(5, 2, 5)) assert np.may_share_memory(t0_reshape.jd1, self.t0.jd1) assert np.may_share_memory(t0_reshape.jd2, self.t0.jd2) assert t0_reshape.location is None t1_reshape = self.t1.reshape(2, 5, 5) assert t1_reshape.shape == (2, 5, 5) assert np.all(t1_reshape.jd1 == self.t1.jd1.reshape(2, 5, 5)) assert np.may_share_memory(t1_reshape.jd1, self.t1.jd1) assert t1_reshape.location is self.t1.location # For reshape(5, 2, 5), the location array can remain the same. t2_reshape = self.t2.reshape(5, 2, 5) assert t2_reshape.shape == (5, 2, 5) assert np.all(t2_reshape.jd1 == self.t2.jd1.reshape(5, 2, 5)) assert np.may_share_memory(t2_reshape.jd1, self.t2.jd1) assert t2_reshape.location.shape == t2_reshape.shape assert np.may_share_memory(t2_reshape.location, self.t2.location) # But for reshape(5, 5, 2), location has to be broadcast and copied. t2_reshape2 = self.t2.reshape(5, 5, 2) assert t2_reshape2.shape == (5, 5, 2) assert np.all(t2_reshape2.jd1 == self.t2.jd1.reshape(5, 5, 2)) assert np.may_share_memory(t2_reshape2.jd1, self.t2.jd1) assert t2_reshape2.location.shape == t2_reshape2.shape assert not np.may_share_memory(t2_reshape2.location, self.t2.location) t2_reshape_t = self.t2.reshape(10, 5).T assert t2_reshape_t.shape == (5, 10) assert np.may_share_memory(t2_reshape_t.jd1, self.t2.jd1) assert t2_reshape_t.location.shape == t2_reshape_t.shape assert np.may_share_memory(t2_reshape_t.location, self.t2.location) # Finally, reshape in a way that cannot be a view. t2_reshape_t_reshape = t2_reshape_t.reshape(10, 5) assert t2_reshape_t_reshape.shape == (10, 5) assert not np.may_share_memory(t2_reshape_t_reshape.jd1, self.t2.jd1) assert (t2_reshape_t_reshape.location.shape == t2_reshape_t_reshape.shape) assert not np.may_share_memory(t2_reshape_t_reshape.location, t2_reshape_t.location) def test_shape_setting(self): t0_reshape = self.t0.copy() t0_reshape.shape = (5, 2, 5) assert t0_reshape.shape == (5, 2, 5) assert np.all(t0_reshape.jd1 == self.t0._time.jd1.reshape(5, 2, 5)) assert np.all(t0_reshape.jd2 == self.t0._time.jd2.reshape(5, 2, 5)) assert t0_reshape.location is None # But if the shape doesn't work, one should get an error. t0_reshape_t = t0_reshape.T with pytest.raises(AttributeError): t0_reshape_t.shape = (10, 5) # check no shape was changed. assert t0_reshape_t.shape == t0_reshape.T.shape assert t0_reshape_t.jd1.shape == t0_reshape.T.shape assert t0_reshape_t.jd2.shape == t0_reshape.T.shape t1_reshape = self.t1.copy() t1_reshape.shape = (2, 5, 5) assert t1_reshape.shape == (2, 5, 5) assert np.all(t1_reshape.jd1 == self.t1.jd1.reshape(2, 5, 5)) # location is a single element, so its shape should not change. assert t1_reshape.location.shape == () # For reshape(5, 2, 5), the location array can remain the same. # Note that we need to work directly on self.t2 here, since any # copy would cause location to have the full shape. self.t2.shape = (5, 2, 5) assert self.t2.shape == (5, 2, 5) assert self.t2.jd1.shape == (5, 2, 5) assert self.t2.jd2.shape == (5, 2, 5) assert self.t2.location.shape == (5, 2, 5) assert self.t2.location.strides == (0, 0, 24) # But for reshape(50), location would need to be copied, so this # should fail. oldshape = self.t2.shape with pytest.raises(AttributeError): self.t2.shape = (50,) # check no shape was changed. assert self.t2.jd1.shape == oldshape assert self.t2.jd2.shape == oldshape assert self.t2.location.shape == oldshape # reset t2 to its original. self.setup() def test_squeeze(self): t0_squeeze = self.t0.reshape(5, 1, 2, 1, 5).squeeze() assert t0_squeeze.shape == (5, 2, 5) assert np.all(t0_squeeze.jd1 == self.t0.jd1.reshape(5, 2, 5)) assert np.may_share_memory(t0_squeeze.jd1, self.t0.jd1) assert t0_squeeze.location is None t1_squeeze = self.t1.reshape(1, 5, 1, 2, 5).squeeze() assert t1_squeeze.shape == (5, 2, 5) assert np.all(t1_squeeze.jd1 == self.t1.jd1.reshape(5, 2, 5)) assert np.may_share_memory(t1_squeeze.jd1, self.t1.jd1) assert t1_squeeze.location is self.t1.location t2_squeeze = self.t2.reshape(1, 1, 5, 2, 5, 1, 1).squeeze() assert t2_squeeze.shape == (5, 2, 5) assert np.all(t2_squeeze.jd1 == self.t2.jd1.reshape(5, 2, 5)) assert np.may_share_memory(t2_squeeze.jd1, self.t2.jd1) assert t2_squeeze.location.shape == t2_squeeze.shape assert np.may_share_memory(t2_squeeze.location, self.t2.location) def test_add_dimension(self): t0_adddim = self.t0[:, np.newaxis, :] assert t0_adddim.shape == (10, 1, 5) assert np.all(t0_adddim.jd1 == self.t0.jd1[:, np.newaxis, :]) assert np.may_share_memory(t0_adddim.jd1, self.t0.jd1) assert t0_adddim.location is None t1_adddim = self.t1[:, :, np.newaxis] assert t1_adddim.shape == (10, 5, 1) assert np.all(t1_adddim.jd1 == self.t1.jd1[:, :, np.newaxis]) assert np.may_share_memory(t1_adddim.jd1, self.t1.jd1) assert t1_adddim.location is self.t1.location t2_adddim = self.t2[:, :, np.newaxis] assert t2_adddim.shape == (10, 5, 1) assert np.all(t2_adddim.jd1 == self.t2.jd1[:, :, np.newaxis]) assert np.may_share_memory(t2_adddim.jd1, self.t2.jd1) assert t2_adddim.location.shape == t2_adddim.shape assert np.may_share_memory(t2_adddim.location, self.t2.location) def test_take(self): t0_take = self.t0.take((5, 2)) assert t0_take.shape == (2,) assert np.all(t0_take.jd1 == self.t0._time.jd1.take((5, 2))) assert t0_take.location is None t1_take = self.t1.take((2, 4), axis=1) assert t1_take.shape == (10, 2) assert np.all(t1_take.jd1 == self.t1.jd1.take((2, 4), axis=1)) assert t1_take.location is self.t1.location t2_take = self.t2.take((1, 3, 7), axis=0) assert t2_take.shape == (3, 5) assert np.all(t2_take.jd1 == self.t2.jd1.take((1, 3, 7), axis=0)) assert t2_take.location.shape == t2_take.shape t2_take2 = self.t2.take((5, 15)) assert t2_take2.shape == (2,) assert np.all(t2_take2.jd1 == self.t2.jd1.take((5, 15))) assert t2_take2.location.shape == t2_take2.shape def test_broadcast(self): """Test using a callable method.""" t0_broadcast = self.t0._apply(np_broadcast_to, shape=(3, 10, 5)) assert t0_broadcast.shape == (3, 10, 5) assert np.all(t0_broadcast.jd1 == self.t0.jd1) assert np.may_share_memory(t0_broadcast.jd1, self.t0.jd1) assert t0_broadcast.location is None t1_broadcast = self.t1._apply(np_broadcast_to, shape=(3, 10, 5)) assert t1_broadcast.shape == (3, 10, 5) assert np.all(t1_broadcast.jd1 == self.t1.jd1) assert np.may_share_memory(t1_broadcast.jd1, self.t1.jd1) assert t1_broadcast.location is self.t1.location t2_broadcast = self.t2._apply(np_broadcast_to, shape=(3, 10, 5)) assert t2_broadcast.shape == (3, 10, 5) assert np.all(t2_broadcast.jd1 == self.t2.jd1) assert np.may_share_memory(t2_broadcast.jd1, self.t2.jd1) assert t2_broadcast.location.shape == t2_broadcast.shape assert np.may_share_memory(t2_broadcast.location, self.t2.location) class TestArithmetic(): """Arithmetic on Time objects, using both doubles.""" kwargs = ({}, {'axis': None}, {'axis': 0}, {'axis': 1}, {'axis': 2}) functions = ('min', 'max', 'sort') def setup(self): mjd = np.arange(50000, 50100, 10).reshape(2, 5, 1) frac = np.array([0.1, 0.1+1.e-15, 0.1-1.e-15, 0.9+2.e-16, 0.9]) self.t0 = Time(mjd, frac, format='mjd', scale='utc') # Define arrays with same ordinal properties frac = np.array([1, 2, 0, 4, 3]) self.t1 = Time(mjd + frac, format='mjd', scale='utc') self.jd = mjd + frac @pytest.mark.parametrize('kw, func', itertools.product(kwargs, functions)) def test_argfuncs(self, kw, func): """ Test that np.argfunc(jd, **kw) is the same as t0.argfunc(**kw) where jd is a similarly shaped array with the same ordinal properties but all integer values. Also test the same for t1 which has the same integral values as jd. """ t0v = getattr(self.t0, 'arg' + func)(**kw) t1v = getattr(self.t1, 'arg' + func)(**kw) jdv = getattr(np, 'arg' + func)(self.jd, **kw) assert np.all(t0v == jdv) assert np.all(t1v == jdv) assert t0v.shape == jdv.shape assert t1v.shape == jdv.shape @pytest.mark.parametrize('kw, func', itertools.product(kwargs, functions)) def test_funcs(self, kw, func): """ Test that np.func(jd, **kw) is the same as t1.func(**kw) where jd is a similarly shaped array and the same integral values. """ t1v = getattr(self.t1, func)(**kw) jdv = getattr(np, func)(self.jd, **kw) assert np.all(t1v.value == jdv) assert t1v.shape == jdv.shape def test_argmin(self): assert self.t0.argmin() == 2 assert np.all(self.t0.argmin(axis=0) == 0) assert np.all(self.t0.argmin(axis=1) == 0) assert np.all(self.t0.argmin(axis=2) == 2) def test_argmax(self): assert self.t0.argmax() == self.t0.size - 2 assert np.all(self.t0.argmax(axis=0) == 1) assert np.all(self.t0.argmax(axis=1) == 4) assert np.all(self.t0.argmax(axis=2) == 3) def test_argsort(self): assert np.all(self.t0.argsort() == np.array([2, 0, 1, 4, 3])) assert np.all(self.t0.argsort(axis=0) == np.arange(2).reshape(2, 1, 1)) assert np.all(self.t0.argsort(axis=1) == np.arange(5).reshape(5, 1)) assert np.all(self.t0.argsort(axis=2) == np.array([2, 0, 1, 4, 3])) assert np.all(self.t0.argsort(axis=None) == np.arange(50).reshape(-1, 5)[:, (2, 0, 1, 4, 3)].ravel()) def test_min(self): assert self.t0.min() == self.t0[0, 0, 2] assert np.all(self.t0.min(0) == self.t0[0]) assert np.all(self.t0.min(1) == self.t0[:, 0]) assert np.all(self.t0.min(2) == self.t0[:, :, 2]) assert self.t0.min(0).shape == (5, 5) assert self.t0.min(0, keepdims=True).shape == (1, 5, 5) assert self.t0.min(1).shape == (2, 5) assert self.t0.min(1, keepdims=True).shape == (2, 1, 5) assert self.t0.min(2).shape == (2, 5) assert self.t0.min(2, keepdims=True).shape == (2, 5, 1) def test_max(self): assert self.t0.max() == self.t0[-1, -1, -2] assert np.all(self.t0.max(0) == self.t0[1]) assert np.all(self.t0.max(1) == self.t0[:, 4]) assert np.all(self.t0.max(2) == self.t0[:, :, 3]) assert self.t0.max(0).shape == (5, 5) assert self.t0.max(0, keepdims=True).shape == (1, 5, 5) def test_ptp(self): assert self.t0.ptp() == self.t0.max() - self.t0.min() assert np.all(self.t0.ptp(0) == self.t0.max(0) - self.t0.min(0)) assert self.t0.ptp(0).shape == (5, 5) assert self.t0.ptp(0, keepdims=True).shape == (1, 5, 5) def test_sort(self): assert np.all(self.t0.sort() == self.t0[:, :, (2, 0, 1, 4, 3)]) assert np.all(self.t0.sort(0) == self.t0) assert np.all(self.t0.sort(1) == self.t0) assert np.all(self.t0.sort(2) == self.t0[:, :, (2, 0, 1, 4, 3)]) assert np.all(self.t0.sort(None) == self.t0[:, :, (2, 0, 1, 4, 3)].ravel()) # Bit superfluous, but good to check. assert np.all(self.t0.sort(-1)[:, :, 0] == self.t0.min(-1)) assert np.all(self.t0.sort(-1)[:, :, -1] == self.t0.max(-1)) def test_regression(): # For #5225, where a time with a single-element delta_ut1_utc could not # be copied, flattened, or ravelled. (For copy, it is in test_basic.) t = Time(49580.0, scale='tai', format='mjd') t_ut1 = t.ut1 t_ut1_copy = copy.deepcopy(t_ut1) assert type(t_ut1_copy.delta_ut1_utc) is np.ndarray t_ut1_flatten = t_ut1.flatten() assert type(t_ut1_flatten.delta_ut1_utc) is np.ndarray t_ut1_ravel = t_ut1.ravel() assert type(t_ut1_ravel.delta_ut1_utc) is np.ndarray assert t_ut1_copy.delta_ut1_utc == t_ut1.delta_ut1_utc
from copy import copy import inspect import itertools as it import os import warnings import sqlalchemy as sa from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy_continuum import ( ClassNotVersioned, version_class, make_versioned, versioning_manager, remove_versioning ) from sqlalchemy_continuum.transaction import TransactionFactory from sqlalchemy_continuum.plugins import ( TransactionMetaPlugin, TransactionChangesPlugin ) warnings.simplefilter('error', sa.exc.SAWarning) class QueryPool(object): queries = [] @sa.event.listens_for(sa.engine.Engine, 'before_cursor_execute') def log_sql( conn, cursor, statement, parameters, context, executemany ): QueryPool.queries.append(statement) def get_dns_from_driver(driver): if driver == 'postgres': return 'postgres://postgres@localhost/sqlalchemy_continuum_test' elif driver == 'mysql': return 'mysql+pymysql://travis@localhost/sqlalchemy_continuum_test' elif driver == 'sqlite': return 'sqlite:///:memory:' else: raise Exception('Unknown driver given: %r' % driver) def get_driver_name(driver): return driver[0:-len('-native')] if driver.endswith('-native') else driver def uses_native_versioning(): return os.environ.get('DB', 'sqlite').endswith('-native') class TestCase(object): versioning_strategy = 'subquery' transaction_column_name = 'transaction_id' end_transaction_column_name = 'end_transaction_id' composite_pk = False plugins = [TransactionChangesPlugin(), TransactionMetaPlugin()] transaction_cls = TransactionFactory() user_cls = None should_create_models = True @property def options(self): return { 'create_models': self.should_create_models, 'native_versioning': uses_native_versioning(), 'base_classes': (self.Model, ), 'strategy': self.versioning_strategy, 'transaction_column_name': self.transaction_column_name, 'end_transaction_column_name': self.end_transaction_column_name, } def setup_method(self, method): self.Model = declarative_base() make_versioned(options=self.options) driver = os.environ.get('DB', 'sqlite') self.driver = get_driver_name(driver) versioning_manager.plugins = self.plugins versioning_manager.transaction_cls = self.transaction_cls versioning_manager.user_cls = self.user_cls self.engine = create_engine(get_dns_from_driver(self.driver)) # self.engine.echo = True self.create_models() sa.orm.configure_mappers() self.connection = self.engine.connect() if hasattr(self, 'Article'): try: self.ArticleVersion = version_class(self.Article) except ClassNotVersioned: pass if hasattr(self, 'Tag'): try: self.TagVersion = version_class(self.Tag) except ClassNotVersioned: pass self.create_tables() Session = sessionmaker(bind=self.connection) self.session = Session(autoflush=False) if driver == 'postgres-native': self.session.execute('CREATE EXTENSION IF NOT EXISTS hstore') def create_tables(self): self.Model.metadata.create_all(self.connection) def drop_tables(self): self.Model.metadata.drop_all(self.connection) def teardown_method(self, method): remove_versioning() QueryPool.queries = [] versioning_manager.reset() self.session.close_all() self.session.expunge_all() self.drop_tables() self.engine.dispose() self.connection.close() def create_models(self): class Article(self.Model): __tablename__ = 'article' __versioned__ = copy(self.options) id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) name = sa.Column(sa.Unicode(255), nullable=False) content = sa.Column(sa.UnicodeText) description = sa.Column(sa.UnicodeText) class Tag(self.Model): __tablename__ = 'tag' __versioned__ = copy(self.options) id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) name = sa.Column(sa.Unicode(255)) article_id = sa.Column(sa.Integer, sa.ForeignKey(Article.id)) article = sa.orm.relationship(Article, backref='tags') self.Article = Article self.Tag = Tag setting_variants = { 'versioning_strategy': [ 'subquery', 'validity', ], 'transaction_column_name': [ 'transaction_id', 'tx_id' ], 'end_transaction_column_name': [ 'end_transaction_id', 'end_tx_id' ] } def create_test_cases(base_class, setting_variants=setting_variants): """ Function for creating bunch of test case classes for given base class and setting variants. Number of test cases created is the number of linear combinations with setting variants. :param base_class: Base test case class, should be in format 'xxxTestCase' :param setting_variants: A dictionary with keys as versioned configuration option keys and values as list of possible option values. """ names = sorted(setting_variants) combinations = [ dict(zip(names, prod)) for prod in it.product(*(setting_variants[name] for name in names)) ] # Get the module where this function was called in. frm = inspect.stack()[1] module = inspect.getmodule(frm[0]) class_suffix = base_class.__name__[0:-len('TestCase')] for index, combination in enumerate(combinations): class_name = 'Test%s%i' % (class_suffix, index) # Assign a new test case class for current module. setattr( module, class_name, type( class_name, (base_class, ), combination ) )
""" Color scales from the cmocean project Learn more at https://matplotlib.org/cmocean/ cmocean is made available under an MIT license: https://github.com/matplotlib/cmocean/blob/master/LICENSE.txt """ from ._swatches import _swatches def swatches(template=None): return _swatches(__name__, globals(), template) swatches.__doc__ = _swatches.__doc__ turbid = [ "rgb(232, 245, 171)", "rgb(220, 219, 137)", "rgb(209, 193, 107)", "rgb(199, 168, 83)", "rgb(186, 143, 66)", "rgb(170, 121, 60)", "rgb(151, 103, 58)", "rgb(129, 87, 56)", "rgb(104, 72, 53)", "rgb(80, 59, 46)", "rgb(57, 45, 37)", "rgb(34, 30, 27)", ] thermal = [ "rgb(3, 35, 51)", "rgb(13, 48, 100)", "rgb(53, 50, 155)", "rgb(93, 62, 153)", "rgb(126, 77, 143)", "rgb(158, 89, 135)", "rgb(193, 100, 121)", "rgb(225, 113, 97)", "rgb(246, 139, 69)", "rgb(251, 173, 60)", "rgb(246, 211, 70)", "rgb(231, 250, 90)", ] haline = [ "rgb(41, 24, 107)", "rgb(42, 35, 160)", "rgb(15, 71, 153)", "rgb(18, 95, 142)", "rgb(38, 116, 137)", "rgb(53, 136, 136)", "rgb(65, 157, 133)", "rgb(81, 178, 124)", "rgb(111, 198, 107)", "rgb(160, 214, 91)", "rgb(212, 225, 112)", "rgb(253, 238, 153)", ] solar = [ "rgb(51, 19, 23)", "rgb(79, 28, 33)", "rgb(108, 36, 36)", "rgb(135, 47, 32)", "rgb(157, 66, 25)", "rgb(174, 88, 20)", "rgb(188, 111, 19)", "rgb(199, 137, 22)", "rgb(209, 164, 32)", "rgb(217, 192, 44)", "rgb(222, 222, 59)", "rgb(224, 253, 74)", ] ice = [ "rgb(3, 5, 18)", "rgb(25, 25, 51)", "rgb(44, 42, 87)", "rgb(58, 60, 125)", "rgb(62, 83, 160)", "rgb(62, 109, 178)", "rgb(72, 134, 187)", "rgb(89, 159, 196)", "rgb(114, 184, 205)", "rgb(149, 207, 216)", "rgb(192, 229, 232)", "rgb(234, 252, 253)", ] gray = [ "rgb(0, 0, 0)", "rgb(16, 16, 16)", "rgb(38, 38, 38)", "rgb(59, 59, 59)", "rgb(81, 80, 80)", "rgb(102, 101, 101)", "rgb(124, 123, 122)", "rgb(146, 146, 145)", "rgb(171, 171, 170)", "rgb(197, 197, 195)", "rgb(224, 224, 223)", "rgb(254, 254, 253)", ] oxy = [ "rgb(63, 5, 5)", "rgb(101, 6, 13)", "rgb(138, 17, 9)", "rgb(96, 95, 95)", "rgb(119, 118, 118)", "rgb(142, 141, 141)", "rgb(166, 166, 165)", "rgb(193, 192, 191)", "rgb(222, 222, 220)", "rgb(239, 248, 90)", "rgb(230, 210, 41)", "rgb(220, 174, 25)", ] deep = [ "rgb(253, 253, 204)", "rgb(206, 236, 179)", "rgb(156, 219, 165)", "rgb(111, 201, 163)", "rgb(86, 177, 163)", "rgb(76, 153, 160)", "rgb(68, 130, 155)", "rgb(62, 108, 150)", "rgb(62, 82, 143)", "rgb(64, 60, 115)", "rgb(54, 43, 77)", "rgb(39, 26, 44)", ] dense = [ "rgb(230, 240, 240)", "rgb(191, 221, 229)", "rgb(156, 201, 226)", "rgb(129, 180, 227)", "rgb(115, 154, 228)", "rgb(117, 127, 221)", "rgb(120, 100, 202)", "rgb(119, 74, 175)", "rgb(113, 50, 141)", "rgb(100, 31, 104)", "rgb(80, 20, 66)", "rgb(54, 14, 36)", ] algae = [ "rgb(214, 249, 207)", "rgb(186, 228, 174)", "rgb(156, 209, 143)", "rgb(124, 191, 115)", "rgb(85, 174, 91)", "rgb(37, 157, 81)", "rgb(7, 138, 78)", "rgb(13, 117, 71)", "rgb(23, 95, 61)", "rgb(25, 75, 49)", "rgb(23, 55, 35)", "rgb(17, 36, 20)", ] matter = [ "rgb(253, 237, 176)", "rgb(250, 205, 145)", "rgb(246, 173, 119)", "rgb(240, 142, 98)", "rgb(231, 109, 84)", "rgb(216, 80, 83)", "rgb(195, 56, 90)", "rgb(168, 40, 96)", "rgb(138, 29, 99)", "rgb(107, 24, 93)", "rgb(76, 21, 80)", "rgb(47, 15, 61)", ] speed = [ "rgb(254, 252, 205)", "rgb(239, 225, 156)", "rgb(221, 201, 106)", "rgb(194, 182, 59)", "rgb(157, 167, 21)", "rgb(116, 153, 5)", "rgb(75, 138, 20)", "rgb(35, 121, 36)", "rgb(11, 100, 44)", "rgb(18, 78, 43)", "rgb(25, 56, 34)", "rgb(23, 35, 18)", ] amp = [ "rgb(241, 236, 236)", "rgb(230, 209, 203)", "rgb(221, 182, 170)", "rgb(213, 156, 137)", "rgb(205, 129, 103)", "rgb(196, 102, 73)", "rgb(186, 74, 47)", "rgb(172, 44, 36)", "rgb(149, 19, 39)", "rgb(120, 14, 40)", "rgb(89, 13, 31)", "rgb(60, 9, 17)", ] tempo = [ "rgb(254, 245, 244)", "rgb(222, 224, 210)", "rgb(189, 206, 181)", "rgb(153, 189, 156)", "rgb(110, 173, 138)", "rgb(65, 157, 129)", "rgb(25, 137, 125)", "rgb(18, 116, 117)", "rgb(25, 94, 106)", "rgb(28, 72, 93)", "rgb(25, 51, 80)", "rgb(20, 29, 67)", ] phase = [ "rgb(167, 119, 12)", "rgb(197, 96, 51)", "rgb(217, 67, 96)", "rgb(221, 38, 163)", "rgb(196, 59, 224)", "rgb(153, 97, 244)", "rgb(95, 127, 228)", "rgb(40, 144, 183)", "rgb(15, 151, 136)", "rgb(39, 153, 79)", "rgb(119, 141, 17)", "rgb(167, 119, 12)", ] balance = [ "rgb(23, 28, 66)", "rgb(41, 58, 143)", "rgb(11, 102, 189)", "rgb(69, 144, 185)", "rgb(142, 181, 194)", "rgb(210, 216, 219)", "rgb(230, 210, 204)", "rgb(213, 157, 137)", "rgb(196, 101, 72)", "rgb(172, 43, 36)", "rgb(120, 14, 40)", "rgb(60, 9, 17)", ] delta = [ "rgb(16, 31, 63)", "rgb(38, 62, 144)", "rgb(30, 110, 161)", "rgb(60, 154, 171)", "rgb(140, 193, 186)", "rgb(217, 229, 218)", "rgb(239, 226, 156)", "rgb(195, 182, 59)", "rgb(115, 152, 5)", "rgb(34, 120, 36)", "rgb(18, 78, 43)", "rgb(23, 35, 18)", ] curl = [ "rgb(20, 29, 67)", "rgb(28, 72, 93)", "rgb(18, 115, 117)", "rgb(63, 156, 129)", "rgb(153, 189, 156)", "rgb(223, 225, 211)", "rgb(241, 218, 206)", "rgb(224, 160, 137)", "rgb(203, 101, 99)", "rgb(164, 54, 96)", "rgb(111, 23, 91)", "rgb(51, 13, 53)", ] # Prefix variable names with _ so that they will not be added to the swatches _contents = dict(globals()) for _k, _cols in _contents.items(): if _k.startswith("_") or _k == "swatches" or _k.endswith("_r"): continue globals()[_k + "_r"] = _cols[::-1]
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2017, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ---------------------------------------------------------------------------- import json import numbers import re import collections.abc from qiime2.core.type.grammar import TypeExpression, CompositeType, Predicate import qiime2.metadata as metadata def is_primitive_type(type_): return isinstance(type_, _PrimitiveBase) class _PrimitiveBase(TypeExpression): def _validate_union_(self, other, handshake=False): # It is possible we may want this someday: `Int | Str`, but order of # encode/decode dispatch wouldn't be straight-forward. # Order of the declaration could indicate "MRO", but then equality # must consider Int | Str != Str | Int, which feels weird. raise TypeError("Cannot union primitive types.") def _validate_intersection_(self, other, handshake=False): # This literally makes no sense for primitives. Even less sense than # C's Union type (which is actually an intersection type...) raise TypeError("Cannot intersect primitive types.") class _Primitive(_PrimitiveBase): def _validate_predicate_(self, predicate): super()._validate_predicate_(predicate) # _valid_predicates will be on the class obj of the primitives to # make defining them easy if not isinstance(predicate, tuple(self._valid_predicates)): raise TypeError("Cannot supply %r as a predicate to %r type," " permitted predicates: %r" % (predicate, self, {p.__name__ for p in self._valid_predicates})) for bound in predicate.iter_boundaries(): if not self._is_element_(bound): raise TypeError("%r has the wrong types for %r." % (predicate, self)) def to_ast(self): ast = super().to_ast() ast['type'] = 'primitive' return ast class _Collection(CompositeType): def _validate_field_(self, name, value): if not isinstance(value, _Primitive): if isinstance(value, _CollectionPrimitive): raise TypeError("Cannot nest collection types.") else: raise TypeError("Collection type (%r) must be provided" " primitives as arguments to its fields," " not %r" % (self, value)) super()._validate_field_(name, value) def _apply_fields_(self, fields): return _CollectionPrimitive(self._is_element_.__func__, self.encode.__func__, self.decode.__func__, self.name, fields=fields) class _CollectionPrimitive(_PrimitiveBase): def __init__(self, is_element, encode, decode, *args, **kwargs): # TODO: This is a nasty hack self._encode = encode self._decode = decode self._is_element = is_element super().__init__(*args, **kwargs) super().__init__(*args, **kwargs) def encode(self, value): return self._encode(self, value) def decode(self, string): return self._decode(self, string) def _is_element_(self, value): return self._is_element(self, value) def _validate_predicate_(self, predicate): raise TypeError("Predicates cannot be applied directly to collection" " types.") def _apply_fields_(self, fields): return _CollectionPrimitive(self._is_element, self._encode, self._decode, self.name, fields=fields) def to_ast(self): ast = super().to_ast() ast['type'] = 'collection' return ast _RANGE_DEFAULT_START = None _RANGE_DEFAULT_END = None _RANGE_DEFAULT_INCLUSIVE_START = True _RANGE_DEFAULT_INCLUSIVE_END = False class Range(Predicate): def __init__(self, *args, inclusive_start=_RANGE_DEFAULT_INCLUSIVE_START, inclusive_end=_RANGE_DEFAULT_INCLUSIVE_END): if len(args) == 2: self.start, self.end = args elif len(args) == 1: self.start = _RANGE_DEFAULT_START self.end, = args elif len(args) == 0: self.start = _RANGE_DEFAULT_START self.end = _RANGE_DEFAULT_END else: raise ValueError("") self.inclusive_start = inclusive_start self.inclusive_end = inclusive_end super().__init__(args) def __hash__(self): return (hash(type(self)) ^ hash(self.start) ^ hash(self.end) ^ hash(self.inclusive_start) ^ hash(self.inclusive_end)) def __eq__(self, other): return (type(self) is type(other) and self.start == other.start and self.end == other.end and self.inclusive_start == other.inclusive_start and self.inclusive_end == other.inclusive_end) def __repr__(self): args = [] if self.start is not _RANGE_DEFAULT_START: args.append(repr(self.start)) if self.end is not _RANGE_DEFAULT_END: args.append(repr(self.end)) if self.inclusive_start is not _RANGE_DEFAULT_INCLUSIVE_START: args.append('inclusive_start=%r' % self.inclusive_start) if self.inclusive_end is not _RANGE_DEFAULT_INCLUSIVE_END: args.append('inclusive_end=%r' % self.inclusive_end) return "%s(%s)" % (self.__class__.__name__, ', '.join(args)) def _is_element_(self, value): if self.start is not None: if self.inclusive_start: if value < self.start: return False elif value <= self.start: return False if self.end is not None: if self.inclusive_end: if value > self.end: return False elif value >= self.end: return False return True def iter_boundaries(self): if self.start is not None: yield self.start if self.end is not None: yield self.end def to_ast(self): ast = super().to_ast() ast['start'] = self.start ast['end'] = self.end ast['inclusive-start'] = self.inclusive_start ast['inclusive-end'] = self.inclusive_end return ast class Choices(Predicate): def __init__(self, choices): self.choices = set(choices) super().__init__(choices) def __hash__(self): return hash(type(self)) ^ hash(frozenset(self.choices)) def __eq__(self, other): return type(self) == type(other) and self.choices == other.choices def __repr__(self): return "%s({%s})" % (self.__class__.__name__, repr(sorted(self.choices))[1:-1]) def _is_element_(self, value): return value in self.choices def iter_boundaries(self): yield from self.choices def to_ast(self): ast = super().to_ast() ast['choices'] = list(self.choices) return ast class Arguments(Predicate): def __init__(self, parameter): self.parameter = parameter super().__init__(parameter) def __hash__(self): return hash(type(self)) ^ hash(self.parameter) def __eq__(self, other): return type(self) == type(other) and self.parameter == other.parameter def __repr__(self): return "%s(%r)" % (self.__class__.__name__, self.parameter) def _is_element_(self, value): raise NotImplementedError("Membership cannot be determined by this" " predicate directly.") def iter_boundaries(self): yield from [] def to_ast(self): ast = super().to_ast() ast['parameter'] = self.parameter return ast class _Dict(_Collection): def _is_element_(self, value): if not isinstance(value, collections.abc.Mapping): return False key_type, value_type = self.fields for k, v in value.items(): if k not in key_type or v not in value_type: return False return True def decode(self, string): return json.loads(string) def encode(self, value): return json.dumps(value) Dict = _Dict('Dict', field_names=['keys', 'values']) class _List(_Collection): def _is_element_(self, value): if not isinstance(value, collections.abc.Sequence): return False element_type, = self.fields for v in value: if v not in element_type: return False return True def decode(self, string): return json.loads(string) def encode(self, value): return json.dumps(value) List = _List('List', field_names=['elements']) class _Set(_Collection): def _is_element_(self, value): if not isinstance(value, collections.abc.Set): return False element_type, = self.fields for v in value: if v not in element_type: return False return True def decode(self, string): return set(json.loads(string)) def encode(self, value): return json.dumps(list(value)) Set = _Set('Set', field_names=['elements']) class _Int(_Primitive): _valid_predicates = {Range, Arguments} def _is_element_(self, value): # Works with numpy just fine. return isinstance(value, numbers.Integral) def _is_subtype_(self, other): if (isinstance(other, type(Float)) and self.predicate <= other.predicate): return True return super()._is_subtype_(other) def decode(self, string): return int(string) def encode(self, value): return str(value) Int = _Int('Int') class _Str(_Primitive): _valid_predicates = {Choices, Arguments} decode = encode = lambda self, arg: arg def _is_element_(self, value): # No reason for excluding bytes other than extreme prejudice. return isinstance(value, str) Str = _Str('Str') class _Float(_Primitive): _valid_predicates = {Range, Arguments} def _is_element_(self, value): # Works with numpy just fine. return isinstance(value, numbers.Real) def decode(self, string): return float(string) def encode(self, value): return str(value) Float = _Float('Float') class _Bool(_Primitive): _valid_predicates = {Arguments, } def _is_element_(self, value): return isinstance(value, bool) def decode(self, string): if string not in ('false', 'true'): raise TypeError("%s is neither 'true' or 'false'" % string) return string == 'true' def encode(self, value): if value: return 'true' else: return 'false' Bool = _Bool('Bool') class _Color(type(Str)): def _is_element_(self, value): # Regex from: http://stackoverflow.com/a/1636354/579416 return bool(re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', value)) Color = Colour = _Color('Color') class _Metadata(_Primitive): _valid_predicates = set() def _is_element_(self, value): return isinstance(value, metadata.Metadata) def decode(self, metadata): # This interface should have already retrieved this object. if not self._is_element_(metadata): raise TypeError("`Metadata` must be provided by the interface" " directly.") return metadata def encode(self, value): # TODO: Should this be the provenance representation? Does that affect # decode? return value Metadata = _Metadata('Metadata') class _MetadataCategory(_Primitive): _valid_predicates = set() def _is_element_(self, value): return isinstance(value, metadata.MetadataCategory) def decode(self, metadata_category): # This interface should have already retrieved this object. if not self._is_element_(metadata_category): raise TypeError("`MetadataCategory` must be provided by the" " interface directly.") return metadata_category def encode(self, value): # TODO: Should this be the provenance representation? Does that affect # decode? return value MetadataCategory = _MetadataCategory('MetadataCategory')
import os, sys from PyQt4 import QtGui from Orange.widgets import widget, gui from Orange.widgets.settings import Setting from Orange.data.table import Table, get_sample_datasets_dir from Orange.data import StringVariable, DiscreteVariable, ContinuousVariable from Orange.data.io import FileFormats def add_origin(examples, filename): """Adds attribute with file location to each variable""" vars = examples.domain.variables + examples.domain.metas strings = [var for var in vars if isinstance(var, StringVariable)] dir_name, basename = os.path.split(filename) for var in strings: if "type" in var.attributes and "origin" not in var.attributes: var.attributes["origin"] = dir_name class OWFile(widget.OWWidget): name = "File" id = "orange.widgets.data.file" description = """ Read a data table from a supported file format on the the file system and send it to the the output.""" icon = "icons/File.svg" author = "Janez Demsar" maintainer_email = "janez.demsar(@at@)fri.uni-lj.si" priority = 10 category = "Data" keywords = ["data", "file", "load", "read"] outputs = [{"name": "Data", "type": Table, "doc": "Attribute-valued data set read from the input file."}] want_main_area = False recent_files = Setting(["(none)"]) new_variables = Setting(False) dlgFormats = ( "All readable files ({})\n".format( " ".join("*" + c for c in FileFormats.readers)) + "\n".join("{} (*{})".format(FileFormats.names[ext], ext) for ext in FileFormats.readers)) def __init__(self): super().__init__() self.domain = None self.recent_files = [fn for fn in self.recent_files if os.path.exists(fn)] self.loaded_file = "" vbox = gui.widgetBox(self.controlArea, "Data File", addSpace=True) box = gui.widgetBox(vbox, orientation=0) self.file_combo = QtGui.QComboBox(box) self.file_combo.setMinimumWidth(300) box.layout().addWidget(self.file_combo) self.file_combo.activated[int].connect(self.select_file) button = gui.button(box, self, '...', callback=self.browse_file) button.setIcon(self.style().standardIcon(QtGui.QStyle.SP_DirOpenIcon)) button.setSizePolicy( QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Fixed) button = gui.button(box, self, "Reload", callback=self.reload, default=True) button.setIcon( self.style().standardIcon(QtGui.QStyle.SP_BrowserReload)) button.setSizePolicy( QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) gui.checkBox(vbox, self, "new_variables", "Columns with same name in different files " + "represent different variables") box = gui.widgetBox(self.controlArea, "Info", addSpace=True) self.infoa = gui.widgetLabel(box, 'No data loaded.') self.infob = gui.widgetLabel(box, ' ') self.warnings = gui.widgetLabel(box, ' ') #Set word wrap, so long warnings won't expand the widget self.warnings.setWordWrap(True) self.warnings.setSizePolicy( QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.MinimumExpanding) self.set_file_list() if len(self.recent_files) > 0: self.open_file(self.recent_files[0]) def set_file_list(self): self.file_combo.clear() if not self.recent_files: self.file_combo.addItem("(none)") for file in self.recent_files: if file == "(none)": self.file_combo.addItem("(none)") else: self.file_combo.addItem(os.path.split(file)[1]) self.file_combo.addItem("Browse documentation data sets...") def reload(self): if self.recent_files: return self.open_file(self.recent_files[0]) def select_file(self, n): if n < len(self.recent_files) : name = self.recent_files[n] del self.recent_files[n] self.recent_files.insert(0, name) elif n: self.browse_file(True) if len(self.recent_files) > 0: self.set_file_list() self.open_file(self.recent_files[0]) def browse_file(self, in_demos=0): if in_demos: try: start_file = get_sample_datasets_dir() except AttributeError: start_file = "" if not start_file or not os.path.exists(start_file): widgets_dir = os.path.dirname(gui.__file__) orange_dir = os.path.dirname(widgets_dir) start_file = os.path.join(orange_dir, "doc", "datasets") if not start_file or not os.path.exists(start_file): d = os.getcwd() if os.path.basename(d) == "canvas": d = os.path.dirname(d) start_file = os.path.join(os.path.dirname(d), "doc", "datasets") if not os.path.exists(start_file): QtGui.QMessageBox.information( None, "File", "Cannot find the directory with example data sets") return else: if self.recent_files and self.recent_files[0] != "(none)": start_file = self.recent_files[0] else: start_file = os.path.expanduser("~/") filename = QtGui.QFileDialog.getOpenFileName( self, 'Open Orange Data File', start_file, self.dlgFormats) if not filename: return if filename in self.recent_files: self.recent_files.remove(filename) self.recent_files.insert(0, filename) self.set_file_list() self.open_file(self.recent_files[0]) # Open a file, create data from it and send it over the data channel def open_file(self, fn): self.error() self.warning() self.information() if not os.path.exists(fn): dir_name, basename = os.path.split(fn) if os.path.exists(os.path.join(".", basename)): fn = os.path.join(".", basename) self.information("Loading '{}' from the current directory." .format(basename)) if fn == "(none)": self.send("Data", None) self.infoa.setText("No data loaded") self.infob.setText("") self.warnings.setText("") return self.loaded_file = "" data = None err_value = None try: # TODO handle self.new_variables data = Table(fn) self.loaded_file = fn except Exception as exc: err_value = str(exc) if "is being loaded as" in str(err_value): try: data = Table(fn) self.loaded_file = fn self.warning(0, err_value) except: data = None if err_value is not None: self.error(err_value) self.infoa.setText('Data was not loaded due to an error.') self.infob.setText('Error:') self.warnings.setText(err_value) if data is None: self.dataReport = None else: domain = data.domain self.infoa.setText( "{} instance(s), {} feature(s), {} meta attributes" .format(len(data), len(domain.attributes), len(domain.metas))) if isinstance(domain.class_var, ContinuousVariable): self.infob.setText("Regression; numerical class.") elif isinstance(domain.class_var, DiscreteVariable): self.infob.setText("Classification; " + "discrete class with {} values." .format(len(domain.class_var.values))) elif data.domain.class_vars: self.infob.setText("Multi-target; {} target variables." .format(len(data.domain.class_vars))) else: self.infob.setText("Data has no target variable.") self.warnings.setText("") add_origin(data, fn) # make new data and send it file_name = os.path.split(fn)[1] if "." in file_name: data.name = file_name[:file_name.rfind('.')] else: data.name = file_name self.dataReport = self.prepareDataReport(data) self.send("Data", data) def sendReport(self): dataReport = getattr(self, "dataReport", None) if dataReport: self.reportSettings( "File", [("File name", self.loaded_file), ("Format", self.formats.get(os.path.splitext( self.loaded_file)[1], "unknown format"))]) self.reportData(self.dataReport) if __name__ == "__main__": a = QtGui.QApplication(sys.argv) ow = OWFile() ow.show() a.exec_() ow.saveSettings()
from __future__ import absolute_import import sys from django import forms from django.core.exceptions import PermissionDenied from django.core.urlresolvers import get_resolver from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response, render from django.template import Context, RequestContext, TemplateDoesNotExist from django.views.debug import technical_500_response, SafeExceptionReporterFilter from django.views.decorators.debug import (sensitive_post_parameters, sensitive_variables) from django.utils.log import getLogger from . import BrokenException, except_args from .models import Article def index_page(request): """Dummy index page""" return HttpResponse('<html><body>Dummy page</body></html>') def custom_create(request): """ Calls create_object generic view with a custom form class. """ class SlugChangingArticleForm(forms.ModelForm): """Custom form class to overwrite the slug.""" class Meta: model = Article def save(self, *args, **kwargs): self.instance.slug = 'some-other-slug' return super(SlugChangingArticleForm, self).save(*args, **kwargs) from django.views.generic.create_update import create_object return create_object(request, post_save_redirect='/create_update/view/article/%(slug)s/', form_class=SlugChangingArticleForm) def raises(request): # Make sure that a callable that raises an exception in the stack frame's # local vars won't hijack the technical 500 response. See: # http://code.djangoproject.com/ticket/15025 def callable(): raise Exception try: raise Exception except Exception: return technical_500_response(request, *sys.exc_info()) def raises404(request): resolver = get_resolver(None) resolver.resolve('') def raises403(request): raise PermissionDenied def redirect(request): """ Forces an HTTP redirect. """ return HttpResponseRedirect("target/") def view_exception(request, n): raise BrokenException(except_args[int(n)]) def template_exception(request, n): return render_to_response('debug/template_exception.html', {'arg': except_args[int(n)]}) # Some views to exercise the shortcuts def render_to_response_view(request): return render_to_response('debug/render_test.html', { 'foo': 'FOO', 'bar': 'BAR', }) def render_to_response_view_with_request_context(request): return render_to_response('debug/render_test.html', { 'foo': 'FOO', 'bar': 'BAR', }, context_instance=RequestContext(request)) def render_to_response_view_with_mimetype(request): return render_to_response('debug/render_test.html', { 'foo': 'FOO', 'bar': 'BAR', }, mimetype='application/x-rendertest') def render_view(request): return render(request, 'debug/render_test.html', { 'foo': 'FOO', 'bar': 'BAR', }) def render_view_with_base_context(request): return render(request, 'debug/render_test.html', { 'foo': 'FOO', 'bar': 'BAR', }, context_instance=Context()) def render_view_with_content_type(request): return render(request, 'debug/render_test.html', { 'foo': 'FOO', 'bar': 'BAR', }, content_type='application/x-rendertest') def render_view_with_status(request): return render(request, 'debug/render_test.html', { 'foo': 'FOO', 'bar': 'BAR', }, status=403) def render_view_with_current_app(request): return render(request, 'debug/render_test.html', { 'foo': 'FOO', 'bar': 'BAR', }, current_app="foobar_app") def render_view_with_current_app_conflict(request): # This should fail because we don't passing both a current_app and # context_instance: return render(request, 'debug/render_test.html', { 'foo': 'FOO', 'bar': 'BAR', }, current_app="foobar_app", context_instance=RequestContext(request)) def raises_template_does_not_exist(request): # We need to inspect the HTML generated by the fancy 500 debug view but # the test client ignores it, so we send it explicitly. try: return render_to_response('i_dont_exist.html') except TemplateDoesNotExist: return technical_500_response(request, *sys.exc_info()) def send_log(request, exc_info): logger = getLogger('django.request') # The default logging config has a logging filter to ensure admin emails are # only sent with DEBUG=False, but since someone might choose to remove that # filter, we still want to be able to test the behavior of error emails # with DEBUG=True. So we need to remove the filter temporarily. admin_email_handler = [ h for h in logger.handlers if h.__class__.__name__ == "AdminEmailHandler" ][0] orig_filters = admin_email_handler.filters admin_email_handler.filters = [] logger.error('Internal Server Error: %s' % request.path, exc_info=exc_info, extra={ 'status_code': 500, 'request': request } ) admin_email_handler.filters = orig_filters def non_sensitive_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables('sauce') @sensitive_post_parameters('bacon-key', 'sausage-key') def sensitive_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables() @sensitive_post_parameters() def paranoid_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) class UnsafeExceptionReporterFilter(SafeExceptionReporterFilter): """ Ignores all the filtering done by its parent class. """ def get_post_parameters(self, request): return request.POST def get_traceback_frame_variables(self, request, tb_frame): return tb_frame.f_locals.items() @sensitive_variables() @sensitive_post_parameters() def custom_exception_reporter_filter_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) request.exception_reporter_filter = UnsafeExceptionReporterFilter() try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info)
import sys import math import re from graph import * from xml.dom import minidom import shapely.ops from shapely.geometry import LineString import kdtree from multiprocessing import Process, Queue try: import silhouette units = silhouette.units except ImportError: msg = "Warning: no silhouette module available" print msg units.define("pixel = inch / 72 = px") def to_steps(thing): if type(thing) in (tuple, list) and len(thing) == 2 and type(thing[0]) in (int, float): # reverse x and y (y, x) = thing x *= units["pixel"] y *= units["pixel"] # flip x #x = (12 * units["inch"]) - x x = x.to("steps").magnitude y = y.to("steps").magnitude return (x, y) return map(to_steps, thing) def draw_rect(cutter, **kw): x = float(kw["x"]) y = float(kw["y"]) width = float(kw["width"]) height = float(kw["height"]) move = (x, y) draw = [(x + width, y), (x + width, y + height), (x, y + height), (x, y)] cutter.position = to_steps(move) cutter.draw(to_steps(draw)) def parse_path(path): commands = set("MZLHVCSQTA") wsp = set(" \t\r\n") wsp_comma = wsp.union(set(",")) signs = wsp.union(set("+-")) command = None arguments = [] arg = '' for ch in path: if ch.upper() in commands: if arg: arguments.append(float(arg)) if command: yield (command, tuple(arguments)) command = ch arguments = [] arg = '' elif ch in wsp_comma: if arg: arguments.append(float(arg)) arg = '' elif ch in signs: if arg: arguments.append(float(arg)) arg = ch else: arg += ch def extract_lines(path): commands = parse_path(path) moves = 0 points = 0 for (command, args) in commands: if command == 'M': moves += 1 cursor = args elif command == 'L': line = (cursor, args) points += 2 yield line cursor = args def walk_graph(graph, node): stack = [node] reverse = [] path = [node] while stack: node = stack[-1] children = [nnode for nnode in graph[node] if not graph[node][nnode]["visited"]] if children: child = children[0] graph[node][child]["visited"] = True if reverse: path += reverse reverse = [] path.append(child) stack.append(child) continue # no children stack.pop() if stack: reverse.append(stack[-1]) return path def build_path_commands(tree, graph): cursor = (0, 0) next_node = tree.search_nn(cursor) nodes = [] culled = set() while next_node: (next_point, distance) = next_node next_point = next_point.data distance = math.sqrt(distance) tree = tree.remove(next_point) culled.add(next_point) if nodes and distance > 16: yield nodes nodes = [] nodes += walk_graph(graph, next_point) for node in nodes: if node in culled: continue tree = tree.remove(node) or tree culled.add(node) next_node = tree.search_nn(nodes[-1]) if nodes: yield nodes def graph_lines(lines): graph = BidirectedGraph() if isinstance(lines, LineString): lines = [lines] for line in lines: last_coord = None for coord in line.coords: if coord not in graph: graph.add_node(coord) if last_coord: val = {"visited": False} graph.connect(coord, last_coord, val) last_coord = coord return graph def simplify_path(path): #lines = list(extract_lines(path)) lines = to_steps(extract_lines(path)) result = shapely.ops.linemerge(lines) print "building graph" graph = graph_lines(result) print "building kdtree" tree = kdtree.create(graph.keys()) return build_path_commands(tree, graph) def produce_paths(svgfn, path_queue): fh = open(svgfn) doc = minidom.parse(fh) paths = doc.getElementsByTagName("path") for path in paths: points = path.getAttribute('d') paths = simplify_path(points) for path in paths: path_queue.put(path) rects = doc.getElementsByTagName("rect") for rect in rects: path_queue.put(dict(rect.attributes.items())) path_queue.put("done") def draw_svg(worker, path_queue): cutter = connect() try: while 1: thing = path_queue.get() if thing == "done": break if type(thing) == dict: for rpt in range(3): draw_rect(cutter, **thing) else: cutter.position = thing[0] cutter.draw(thing) worker.join() finally: cutter.home() def connect(): cutter = silhouette.Silhouette() cutter.connect() print "speed" cutter.speed = 8 print "pressure" cutter.pressure = 4 print "media" cutter.media = 113 print "offset" cutter.offset = 0 return cutter if __name__ == "__main__": path_queue = Queue() svgfn = sys.argv[1] worker = Process(target=produce_paths, args=(svgfn, path_queue)) worker.start() draw_svg(worker, path_queue)
#!/usr/bin/env python """Administrative flows for managing the clients state.""" import shlex import threading import time import urllib import logging # pylint: disable=unused-import from grr.gui import django_lib # pylint: enable=unused-import from grr.lib import access_control from grr.lib import aff4 from grr.lib import config_lib from grr.lib import data_store from grr.lib import email_alerts from grr.lib import flow from grr.lib import rdfvalue from grr.lib import registry from grr.lib import rendering from grr.lib import stats from grr.lib import utils from grr.lib.aff4_objects import collections from grr.lib.aff4_objects import reports from grr.proto import flows_pb2 class AdministrativeInit(registry.InitHook): """Initialize the Django environment.""" pre = ["StatsInit"] def RunOnce(self): stats.STATS.RegisterCounterMetric("grr_client_crashes") class ClientCrashEventListener(flow.EventListener): """EventListener with additional helper methods to save crash details.""" def _AppendCrashDetails(self, path, crash_details): collection = aff4.FACTORY.Create( path, "PackedVersionedCollection", mode="rw", token=self.token) collection.Add(crash_details) collection.Close(sync=False) def WriteAllCrashDetails(self, client_id, crash_details, flow_session_id=None, hunt_session_id=None): # Update last crash attribute of the client. client_obj = aff4.FACTORY.Create(client_id, "VFSGRRClient", token=self.token) client_obj.Set(client_obj.Schema.LAST_CRASH(crash_details)) client_obj.Close(sync=False) # Duplicate the crash information in a number of places so we can find it # easily. self._AppendCrashDetails(client_id.Add("crashes"), crash_details) self._AppendCrashDetails(aff4.ROOT_URN.Add("crashes"), crash_details) if flow_session_id: aff4_flow = aff4.FACTORY.Open(flow_session_id, "GRRFlow", mode="rw", age=aff4.NEWEST_TIME, token=self.token) aff4_flow.Set(aff4_flow.Schema.CLIENT_CRASH(crash_details)) aff4_flow.Close(sync=False) hunt_str, hunt_id, _ = flow_session_id.Split(3) if hunt_str == "hunts": hunt_session_id = aff4.ROOT_URN.Add("hunts").Add(hunt_id) if hunt_session_id != flow_session_id: self._AppendCrashDetails( hunt_session_id.Add("crashes"), crash_details) class GetClientStatsProcessResponseMixin(object): """Mixin defining ProcessReponse() that writes client stats to datastore.""" def ProcessResponse(self, client_id, response): """Actually processes the contents of the response.""" urn = client_id.Add("stats") with aff4.FACTORY.Create(urn, "ClientStats", token=self.token, mode="w") as stats_fd: # Only keep the average of all values that fall within one minute. stats_fd.AddAttribute(stats_fd.Schema.STATS(response.DownSample())) class GetClientStats(flow.GRRFlow, GetClientStatsProcessResponseMixin): """This flow retrieves information about the GRR client process.""" category = "/Administrative/" @flow.StateHandler(next_state=["StoreResults"]) def Start(self): self.CallClient("GetClientStats", next_state="StoreResults") @flow.StateHandler() def StoreResults(self, responses): """Stores the responses.""" if not responses.success: self.Error("Failed to retrieve client stats.") return for response in responses: self.ProcessResponse(self.client_id, response) class GetClientStatsAuto(flow.WellKnownFlow, GetClientStatsProcessResponseMixin): """This action pushes client stats to the server automatically.""" category = None well_known_session_id = rdfvalue.SessionID("aff4:/flows/W:Stats") def ProcessMessage(self, message): """Processes a stats response from the client.""" client_stats = rdfvalue.ClientStats(message.args) self.ProcessResponse(message.source, client_stats) class DeleteGRRTempFilesArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.DeleteGRRTempFilesArgs class DeleteGRRTempFiles(flow.GRRFlow): """Delete all the GRR temp files in path. If path is a directory, look in the top level for filenames beginning with Client.tempfile_prefix, and delete them. If path is a regular file and starts with Client.tempfile_prefix, delete it. """ category = "/Administrative/" args_type = DeleteGRRTempFilesArgs @flow.StateHandler(next_state="Done") def Start(self): """Issue a request to delete tempfiles in directory.""" self.CallClient("DeleteGRRTempFiles", self.args.pathspec, next_state="Done") @flow.StateHandler() def Done(self, responses): if not responses.success: raise flow.FlowError(str(responses.status)) for response in responses: self.Log(response.data) class UninstallArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.UninstallArgs class Uninstall(flow.GRRFlow): """Removes the persistence mechanism which the client uses at boot. For Windows and OSX, this will disable the service, and then stop the service. For Linux this flow will fail as we haven't implemented it yet :) """ category = "/Administrative/" args_type = UninstallArgs @flow.StateHandler(next_state=["Kill"]) def Start(self): """Start the flow and determine OS support.""" client = aff4.FACTORY.Open(self.client_id, token=self.token) system = client.Get(client.Schema.SYSTEM) if system == "Darwin" or system == "Windows": self.CallClient("Uninstall", next_state="Kill") else: self.Log("Unsupported platform for Uninstall") @flow.StateHandler(next_state="Confirmation") def Kill(self, responses): """Call the kill function on the client.""" if not responses.success: self.Log("Failed to uninstall client.") elif self.args.kill: self.CallClient("Kill", next_state="Confirmation") @flow.StateHandler(next_state="End") def Confirmation(self, responses): """Confirmation of kill.""" if not responses.success: self.Log("Kill failed on the client.") class Kill(flow.GRRFlow): """Terminate a running client (does not disable, just kill).""" category = "/Administrative/" @flow.StateHandler(next_state=["Confirmation"]) def Start(self): """Call the kill function on the client.""" self.CallClient("Kill", next_state="Confirmation") @flow.StateHandler(next_state="End") def Confirmation(self, responses): """Confirmation of kill.""" if not responses.success: self.Log("Kill failed on the client.") class UpdateConfigurationArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.UpdateConfigurationArgs class UpdateConfiguration(flow.GRRFlow): """Update the configuration of the client. Note: This flow is somewhat dangerous, so we don't expose it in the UI. """ # Still accessible (e.g. via ajax but not visible in the UI.) category = None args_type = rdfvalue.UpdateConfigurationArgs @flow.StateHandler(next_state=["Confirmation"]) def Start(self): """Call the UpdateConfiguration function on the client.""" self.CallClient("UpdateConfiguration", request=self.args.config, next_state="Confirmation") @flow.StateHandler(next_state="End") def Confirmation(self, responses): """Confirmation.""" if not responses.success: raise flow.FlowError("Failed to write config. Err: {0}".format( responses.status)) class ExecutePythonHackArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.ExecutePythonHackArgs class ExecutePythonHack(flow.GRRFlow): """Execute a signed python hack on a client.""" category = "/Administrative/" args_type = ExecutePythonHackArgs @flow.StateHandler(next_state=["Done"]) def Start(self): python_hack_root_urn = config_lib.CONFIG.Get("Config.python_hack_root") fd = aff4.FACTORY.Open(python_hack_root_urn.Add(self.args.hack_name), token=self.token) if not isinstance(fd, aff4.GRRSignedBlob): raise RuntimeError("Python hack %s not found." % self.args.hack_name) # TODO(user): This will break if someone wants to execute lots of Python. for python_blob in fd: self.CallClient("ExecutePython", python_code=python_blob, py_args=self.args.py_args, next_state="Done") @flow.StateHandler() def Done(self, responses): response = responses.First() if not responses.success: raise flow.FlowError("Execute Python hack failed: %s" % responses.status) if response: result = utils.SmartStr(response.return_val) # Send reply with full data, but only log the first 200 bytes. str_result = result[0:200] if len(result) >= 200: str_result += "...[truncated]" self.Log("Result: %s" % str_result) self.SendReply(rdfvalue.RDFBytes(utils.SmartStr(response.return_val))) class ExecuteCommandArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.ExecuteCommandArgs class ExecuteCommand(flow.GRRFlow): """Execute a predefined command on the client.""" args_type = ExecuteCommandArgs @flow.StateHandler(next_state=["Confirmation"]) def Start(self): """Call the execute function on the client.""" self.CallClient("ExecuteCommand", cmd=self.args.cmd, args=shlex.split(self.args.command_line), time_limit=self.args.time_limit, next_state="Confirmation") @flow.StateHandler(next_state="End") def Confirmation(self, responses): """Confirmation.""" if responses.success: response = responses.First() self.Log(("Execution of %s %s (return value %d, " "ran for %f seconds):"), response.request.cmd, " ".join(response.request.command_line), response.exit_status, # time_used is returned in microseconds. response.time_used / 1e6) try: # We don't want to overflow the log so we just save 100 bytes each. logout = response.stdout[:100] if len(response.stdout) > 100: logout += "..." logerr = response.stderr[:100] if len(response.stderr) > 100: logerr += "..." self.Log("Output: %s, %s", logout, logerr) except ValueError: # The received byte buffer does not convert to unicode. self.Log("Received output not convertible to unicode.") else: self.Log("Execute failed.") class Foreman(flow.WellKnownFlow): """The foreman assigns new flows to clients based on their type. Clients periodically call the foreman flow to ask for new flows that might be scheduled for them based on their types. This allows the server to schedule flows for entire classes of machines based on certain criteria. """ well_known_session_id = rdfvalue.SessionID("aff4:/flows/W:Foreman") foreman_cache = None # How often we refresh the rule set from the data store. cache_refresh_time = 60 lock = threading.Lock() def ProcessMessage(self, message): """Run the foreman on the client.""" # Only accept authenticated messages if (message.auth_state != rdfvalue.GrrMessage.AuthorizationState.AUTHENTICATED): return now = time.time() # Maintain a cache of the foreman with self.lock: if (self.foreman_cache is None or now > self.foreman_cache.age + self.cache_refresh_time): self.foreman_cache = aff4.FACTORY.Open("aff4:/foreman", mode="rw", token=self.token) self.foreman_cache.age = now if message.source: self.foreman_cache.AssignTasksToClient(message.source) class OnlineNotificationArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.OnlineNotificationArgs class OnlineNotification(flow.GRRFlow): """Notifies by email when a client comes online in GRR.""" category = "/Administrative/" behaviours = flow.GRRFlow.behaviours + "BASIC" template = """ <html><body><h1>GRR Client Online Notification.</h1> <p> Client %(client_id)s (%(hostname)s) just came online. Click <a href='%(admin_ui)s/#%(urn)s'> here </a> to access this machine. <br />This notification was created by %(creator)s. </p> <p>Thanks,</p> <p>%(signature)s</p> </body></html>""" args_type = OnlineNotificationArgs @classmethod def GetDefaultArgs(cls, token=None): return cls.args_type(email="%s@%s" % ( token.username, config_lib.CONFIG.Get("Logging.domain"))) @flow.StateHandler(next_state="SendMail") def Start(self): """Starts processing.""" if self.args.email is None: self.args.email = self.token.username self.CallClient("Echo", data="Ping", next_state="SendMail") @flow.StateHandler() def SendMail(self, responses): """Sends a mail when the client has responded.""" if responses.success: client = aff4.FACTORY.Open(self.client_id, token=self.token) hostname = client.Get(client.Schema.HOSTNAME) url = urllib.urlencode((("c", self.client_id), ("main", "HostInformation"))) subject = "GRR Client on %s became available." % hostname email_alerts.SendEmail( self.args.email, "grr-noreply", subject, self.template % dict( client_id=self.client_id, admin_ui=config_lib.CONFIG["AdminUI.url"], hostname=hostname, urn=url, creator=self.token.username, signature=config_lib.CONFIG["Email.signature"]), is_html=True) else: flow.FlowError("Error while pinging client.") class UpdateClientArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.UpdateClientArgs class UpdateClient(flow.GRRFlow): """Updates the GRR client to a new version replacing the current client. This will execute the specified installer on the client and then run an Interrogate flow. The new installer needs to be loaded into the database, generally in /config/executables/<platform>/installers and must be signed using the exec signing key. Signing and upload of the file is done with config_updater. """ category = "/Administrative/" AUTHORIZED_LABELS = ["admin"] system_platform_mapping = { "Darwin": "darwin", "Linux": "linux", "Windows": "windows"} args_type = UpdateClientArgs @flow.StateHandler(next_state="Interrogate") def Start(self): """Start.""" blob_path = self.args.blob_path if not blob_path: # No explicit path was given, we guess a reasonable default here. client = aff4.FACTORY.Open(self.client_id, token=self.token) client_platform = client.Get(client.Schema.SYSTEM) if not client_platform: raise RuntimeError("Can't determine client platform, please specify.") blob_urn = "aff4:/config/executables/%s/agentupdates" % ( self.system_platform_mapping[client_platform]) blob_dir = aff4.FACTORY.Open(blob_urn, token=self.token) updates = sorted(list(blob_dir.ListChildren())) if not updates: raise RuntimeError( "No matching updates found, please specify one manually.") blob_path = updates[-1] if not ("windows" in utils.SmartStr(self.args.blob_path) or "darwin" in utils.SmartStr(self.args.blob_path) or "linux" in utils.SmartStr(self.args.blob_path)): raise RuntimeError("Update not supported for this urn, use aff4:/config" "/executables/<platform>/agentupdates/<version>") aff4_blobs = aff4.FACTORY.Open(blob_path, token=self.token) offset = 0 write_path = "%d" % time.time() for i, blob in enumerate(aff4_blobs): self.CallClient( "UpdateAgent", executable=blob, more_data=i < aff4_blobs.chunks-1, offset=offset, write_path=write_path, next_state="Interrogate") offset += len(blob.data) @flow.StateHandler(next_state="Done") def Interrogate(self, responses): if not responses.success: self.Log("Installer reported an error: %s" % responses.status) else: self.Log("Installer completed.") self.CallFlow("Interrogate", next_state="Done") @flow.StateHandler() def Done(self): client = aff4.FACTORY.Open(self.client_id, token=self.token) info = client.Get(client.Schema.CLIENT_INFO) self.Log("Client update completed, new version: %s" % info.client_version) class NannyMessageHandler(ClientCrashEventListener): """A listener for nanny messages.""" EVENTS = ["NannyMessage"] well_known_session_id = rdfvalue.SessionID("aff4:/flows/W:NannyMessage") mail_template = """ <html><body><h1>GRR nanny message received.</h1> The nanny for client %(client_id)s (%(hostname)s) just sent a message:<br> <br> %(message)s <br> Click <a href='%(admin_ui)s/#%(urn)s'> here </a> to access this machine. <p>%(signature)s</p> </body></html>""" subject = "GRR nanny message received from %s." logline = "Nanny for client %s sent: %s" @flow.EventHandler(allow_client_access=True) def ProcessMessage(self, message=None, event=None): """Processes this event.""" _ = event client_id = message.source message = rdfvalue.DataBlob(message.args).string logging.info(self.logline, client_id, message) # Write crash data to AFF4. client = aff4.FACTORY.Open(client_id, token=self.token) client_info = client.Get(client.Schema.CLIENT_INFO) crash_details = rdfvalue.ClientCrash( client_id=client_id, client_info=client_info, crash_message=message, timestamp=long(time.time() * 1e6), crash_type=self.well_known_session_id) self.WriteAllCrashDetails(client_id, crash_details) # Also send email. if config_lib.CONFIG["Monitoring.alert_email"]: client = aff4.FACTORY.Open(client_id, token=self.token) hostname = client.Get(client.Schema.HOSTNAME) url = urllib.urlencode((("c", client_id), ("main", "HostInformation"))) email_alerts.SendEmail( config_lib.CONFIG["Monitoring.alert_email"], "GRR server", self.subject % client_id, self.mail_template % dict( client_id=client_id, admin_ui=config_lib.CONFIG["AdminUI.url"], hostname=hostname, signature=config_lib.CONFIG["Email.signature"], urn=url, message=message), is_html=True) class ClientAlertHandler(NannyMessageHandler): """A listener for client messages.""" EVENTS = ["ClientAlert"] well_known_session_id = rdfvalue.SessionID("aff4:/flows/W:ClientAlert") mail_template = """ <html><body><h1>GRR client message received.</h1> The client %(client_id)s (%(hostname)s) just sent a message:<br> <br> %(message)s <br> Click <a href='%(admin_ui)s/#%(urn)s'> here </a> to access this machine. <p>%(signature)s</p> </body></html>""" subject = "GRR client message received from %s." logline = "Client message from %s: %s" class ClientCrashHandler(ClientCrashEventListener): """A listener for client crashes.""" EVENTS = ["ClientCrash"] well_known_session_id = rdfvalue.SessionID("aff4:/flows/W:CrashHandler") mail_template = """ <html><body><h1>GRR client crash report.</h1> Client %(client_id)s (%(hostname)s) just crashed while executing an action. Click <a href='%(admin_ui)s/#%(urn)s'> here </a> to access this machine. <p>Thanks,</p> <p>%(signature)s</p> <p> P.S. The state of the failing flow was: %(state)s %(nanny_msg)s </body></html>""" @flow.EventHandler(allow_client_access=True) def ProcessMessage(self, message=None, event=None): """Processes this event.""" _ = event client_id = message.source nanny_msg = "" flow_obj = aff4.FACTORY.Open(message.session_id, token=self.token) # Log. logging.info("Client crash reported, client %s.", client_id) # Export. stats.STATS.IncrementCounter("grr_client_crashes") # Write crash data to AFF4. client = aff4.FACTORY.Open(client_id, token=self.token) client_info = client.Get(client.Schema.CLIENT_INFO) status = rdfvalue.GrrStatus(message.args) crash_details = rdfvalue.ClientCrash( client_id=client_id, session_id=message.session_id, client_info=client_info, crash_message=status.error_message, timestamp=rdfvalue.RDFDatetime().Now(), crash_type=self.well_known_session_id) self.WriteAllCrashDetails(client_id, crash_details, flow_session_id=message.session_id) # Also send email. if config_lib.CONFIG["Monitoring.alert_email"]: if status.nanny_status: nanny_msg = "Nanny status: %s" % status.nanny_status client = aff4.FACTORY.Open(client_id, token=self.token) hostname = client.Get(client.Schema.HOSTNAME) url = urllib.urlencode((("c", client_id), ("main", "HostInformation"))) renderer = rendering.FindRendererForObject(flow_obj.state) email_alerts.SendEmail( config_lib.CONFIG["Monitoring.alert_email"], "GRR server", "Client %s reported a crash." % client_id, self.mail_template % dict( client_id=client_id, admin_ui=config_lib.CONFIG["AdminUI.url"], hostname=hostname, state=renderer.RawHTML(), urn=url, nanny_msg=nanny_msg, signature=config_lib.CONFIG["Email.signature"] ), is_html=True) if nanny_msg: msg = "Client crashed, " + nanny_msg else: msg = "Client crashed." # Now terminate the flow. flow.GRRFlow.TerminateFlow(message.session_id, reason=msg, token=self.token, force=True) class ClientStartupHandler(flow.EventListener): well_known_session_id = rdfvalue.SessionID("aff4:/flows/W:Startup") @flow.EventHandler(allow_client_access=True, auth_required=False) def ProcessMessage(self, message=None, event=None): """Handle a startup event.""" _ = event # We accept unauthenticated messages so there are no errors but we don't # store the results. if (message.auth_state != rdfvalue.GrrMessage.AuthorizationState.AUTHENTICATED): return client_id = message.source client = aff4.FACTORY.Create(client_id, "VFSGRRClient", mode="rw", token=self.token) old_info = client.Get(client.Schema.CLIENT_INFO) old_boot = client.Get(client.Schema.LAST_BOOT_TIME, 0) startup_info = rdfvalue.StartupInfo(message.args) info = startup_info.client_info # Only write to the datastore if we have new information. new_data = (info.client_name, info.client_version, info.revision, info.build_time, info.client_description) old_data = (old_info.client_name, old_info.client_version, old_info.revision, old_info.build_time, old_info.client_description) if new_data != old_data: client.Set(client.Schema.CLIENT_INFO(info)) client.AddLabels(*info.labels, owner="GRR") # Allow for some drift in the boot times (5 minutes). if abs(int(old_boot) - int(startup_info.boot_time)) > 300 * 1e6: client.Set(client.Schema.LAST_BOOT_TIME(startup_info.boot_time)) client.Close() flow.Events.PublishEventInline("ClientStartup", message, token=self.token) class IgnoreResponses(flow.WellKnownFlow): """This flow exists so other well known flows can delegate their responses.""" category = None well_known_session_id = rdfvalue.SessionID("aff4:/flows/W:DevNull") def ProcessMessage(self, message): pass class KeepAliveArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.KeepAliveArgs class KeepAlive(flow.GRRFlow): """Requests that the clients stays alive for a period of time.""" # We already want to run this flow while waiting for a client approval. # Note that this can potentially be abused to launch a DDOS attack against # the frontend server(s) by putting all clients into fastpoll mode. The load # of idle polling messages is not that high though and this can only be done # by users that have a GRR account already so the risk is acceptable. ACL_ENFORCED = False category = "/Administrative/" behaviours = flow.GRRFlow.behaviours + "BASIC" sleep_time = 60 args_type = KeepAliveArgs @flow.StateHandler(next_state="SendMessage") def Start(self): self.state.Register("end_time", self.args.duration.Expiry()) self.CallState(next_state="SendMessage") @flow.StateHandler(next_state="Sleep") def SendMessage(self, responses): if not responses.success: self.Log(responses.status.error_message) raise flow.FlowError(responses.status.error_message) self.CallClient("Echo", data="Wake up!", next_state="Sleep") @flow.StateHandler(next_state="SendMessage") def Sleep(self, responses): if not responses.success: self.Log(responses.status.error_message) raise flow.FlowError(responses.status.error_message) if rdfvalue.RDFDatetime().Now() < self.state.end_time - self.sleep_time: start_time = rdfvalue.RDFDatetime().Now() + self.sleep_time self.CallState(next_state="SendMessage", start_time=start_time) class TerminateFlowArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.TerminateFlowArgs class TerminateFlow(flow.GRRFlow): """Terminate a flow with a given URN.""" # This flow can run on any client without ACL enforcement (an SUID flow). ACL_ENFORCED = False args_type = TerminateFlowArgs @flow.StateHandler() def Start(self): """Terminate a flow. User has to have access to the flow.""" # We have to create special token here, because within the flow # token has supervisor access. check_token = access_control.ACLToken(username=self.token.username, reason=self.token.reason) # If we can read the flow, we're allowed to terminate it. data_store.DB.security_manager.CheckDataStoreAccess( check_token, [self.args.flow_urn], "r") flow.GRRFlow.TerminateFlow(self.args.flow_urn, reason=self.args.reason, token=self.token, force=True) class LaunchBinaryArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.LaunchBinaryArgs class LaunchBinary(flow.GRRFlow): """Launch a signed binary on a client.""" category = "/Administrative/" AUTHORIZED_LABELS = ["admin"] args_type = LaunchBinaryArgs @flow.StateHandler(next_state=["End"]) def Start(self): fd = aff4.FACTORY.Open(self.args.binary, token=self.token) if not isinstance(fd, collections.GRRSignedBlob): raise RuntimeError("Executable binary %s not found." % self.args.binary) offset = 0 write_path = "%d" % time.time() for i, blob in enumerate(fd): self.CallClient( "ExecuteBinaryCommand", executable=blob, more_data=i < fd.chunks-1, args=shlex.split(self.args.command_line), offset=offset, write_path=write_path, next_state="End") offset += len(blob.data) def _TruncateResult(self, data): if len(data) > 2000: result = data[:2000] + "... [truncated]" else: result = data return result @flow.StateHandler() def End(self, responses): if not responses.success: raise IOError(responses.status) response = responses.First() if response: self.Log("Stdout: %s" % self._TruncateResult(response.stdout)) self.Log("Stderr: %s" % self._TruncateResult(response.stderr)) self.SendReply(response) class RunReportFlowArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.RunReportFlowArgs class RunReport(flow.GRRGlobalFlow): """Run a report and send the result via email.""" category = "/Reporting/" args_type = RunReportFlowArgs behaviours = flow.GRRGlobalFlow.behaviours + "BASIC" ACL_ENFORCED = False # Only admins are allows to run reports. AUTHORIZED_LABELS = ["admin"] @flow.StateHandler(next_state="RunReport") def Start(self): if self.state.args.report_name not in reports.Report.classes: raise flow.FlowError("No such report %s" % self.state.args.report_name) else: self.CallState(next_state="RunReport") @flow.StateHandler(next_state="EmailReport") def RunReport(self): """Run the report.""" report_cls = reports.Report.GetPlugin(self.state.args.report_name) report_obj = report_cls(token=self.token) report_obj.Run() report_obj.MailReport(self.state.args.email) class ApplyLabelsToClientsFlowArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.ApplyLabelsToClientsFlowArgs class ApplyLabelsToClientsFlow(flow.GRRGlobalFlow): args_type = ApplyLabelsToClientsFlowArgs ACL_ENFORCED = False @flow.StateHandler() def Start(self): audit_description = ",".join([self.token.username + "." + name for name in self.args.labels]) audit_events = [] try: client_objs = aff4.FACTORY.MultiOpen( self.args.clients, aff4_type="VFSGRRClient", mode="rw", token=self.token) for client_obj in client_objs: client_obj.AddLabels(*self.args.labels) client_obj.Close() audit_events.append( rdfvalue.AuditEvent(user=self.token.username, action="CLIENT_ADD_LABEL", flow_name="ApplyLabelsToClientsFlow", client=client_obj.urn, description=audit_description)) finally: flow.Events.PublishMultipleEvents({"Audit": audit_events}, token=self.token)
# # Copyright (c) 2019, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # import logging import sys from operator import attrgetter from typing import Optional, Callable, Tuple from pktverify import consts, errors from pktverify.addrs import EthAddr, ExtAddr, Ipv6Addr from pktverify.packet import Packet from pktverify.utils import make_filter_func WPAN, ETH = 0, 1 class _SavedIndex(object): __slots__ = ('_pkts', '_saved_index') def __init__(self, pkts): self._pkts = pkts self._saved_index = pkts.index def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): self._pkts.index = self._saved_index def _always_true(p): return True class PacketFilter(object): """ Represents a range of packets that are filtered by given filter """ def __init__(self, pkts, start=(0, 0), stop=None, *, index=None, filter_func: Optional[Callable] = None, parent: Optional['PacketFilter'] = None): if stop is None: stop = (len(pkts), len(pkts)) self._pkts = pkts self._start_index = start self._stop_index = stop self._index = index if index is not None else self._start_index self._last_index = -1 self._filter_func = filter_func or _always_true self._parent = parent self._check_type_ok() def _check_type_ok(self): assert self._last_index == -1 or 0 <= self._last_index < len(self._pkts) assert isinstance(self._start_index, tuple) and len(self._start_index) == 2, self._start_index assert isinstance(self._stop_index, tuple) and len(self._stop_index) == 2, self._stop_index assert isinstance(self._index, tuple) and len(self._index) == 2, self._index self._check_idx_range_ok((0, 0), self._start_index) self._check_idx_range_ok(self._start_index, self._index) self._check_idx_range_ok(self._index, self._stop_index) self._check_idx_range_ok(self._stop_index, (len(self._pkts), len(self._pkts))) def _check_idx_range_ok(self, start, stop): assert start[0] <= stop[0], (start, stop) assert start[1] <= stop[1], (start, stop) @property def index(self) -> Tuple[int, int]: """ :return: the current index (which is a tuple) """ return self._index @index.setter def index(self, index: Tuple[int, int]): """ Set the current index :param index: the index tuple to set """ assert isinstance(index, tuple) and len(index) == 2, index self._check_type_ok() self._index = index self._check_type_ok() def __len__(self): """ :return: length of packets """ return len(self._pkts) def save_index(self): """ Save the current index to be restored. :return: a context that saves the current index when entering, and restores when exiting """ return _SavedIndex(self) @property def start_index(self) -> Tuple[int, int]: """ :return: the start index tuple """ return self._start_index @property def stop_index(self) -> Tuple[int, int]: """ :return: the stop index tuple """ return self._stop_index def filter(self, func, cascade=True, **vars) -> 'PacketFilter': """ Create a new PacketFilter based on this packet filter with given filter func :param func: a callable that returns a bool (e.x. lambda p: xxx) or a filter string :param cascade: True if calling next in the new filter will also set index for this filter, False otherwise :param vars: variables for filter string :return: a new PacketFilter """ print('\n>>> filtering in range %s~%s%s:' % (self._index, self._stop_index, "<end>" if self._stop_index == len(self._pkts) else "<stop>"), file=sys.stderr) func = make_filter_func(func, **vars) self._check_type_ok() return PacketFilter(self._pkts, self._index, self._stop_index, filter_func=lambda p: self._filter_func(p) and func(p), parent=self if cascade else None) def filter_if(self, cond: bool, *args, **kwargs) -> 'PacketFilter': """ Create a filter using given arguments if `cond` is true. :param cond: the condition to be checked :param args: arguments for filter func :param kwargs: arguments for filter func :return: a sub filter using given arguments if cond is true, or self otherwise """ if cond: return self.filter(*args, **kwargs) else: return self @property def last_index(self) -> Tuple[int, int]: return self._last_index def last(self) -> Packet: """ :return: the last packet found """ if self._last_index >= 0: return self._pkts[self._last_index] else: raise errors.PacketNotFound(self.index, self._stop_index) def next(self) -> Optional[Packet]: """ Find the next packet starting from the current index to the stop index that matches the current filter. :return: the next matching packet, or None if packet not found """ self._check_type_ok() idx = min(self._index) stop_idx = max(self._stop_index) while idx < stop_idx: p = self._pkts[idx] sys.stderr.write('#%d %s' % (idx + 1, '\n' if idx % 40 == 39 else '')) if self._filter_func(p): if p.wpan and not (self._index[0] <= idx < self._stop_index[0]): # wpan matched but not in range pass elif p.eth and not (self._index[1] <= idx < self._stop_index[1]): # eth matched but not in range pass else: self._on_found_next(idx, p) print("\n>>> found packet at #%d!" % (idx + 1,), file=sys.stderr) return p idx += 1 return None def must_next(self) -> Packet: """ Call .next(), raise error if packet is not found. :return: the next matching packet """ p = self.next() if p is not None: return p else: raise errors.PacketNotFound(self.index, self._stop_index) def must_not_next(self) -> None: """ Call .next(), raise error if packet is found """ p = self.next() if p is None: return else: logging.error("Found unexpected packet at #%s", self.index) p.show() p.debug_fields() raise errors.UnexpectedPacketFound(self.index, p) def _on_found_next(self, idx: int, p: Packet): assert self._pkts[idx] is p assert idx >= min(self._index) assert not p.wpan or idx >= self._index[0] assert not p.eth or idx >= self._index[1], (self._index, idx) if p.wpan: wpan_idx = idx + 1 eth_idx = max(self._index[1], self._find_prev_packet(idx + 1, p.sniff_timestamp - consts.AUTO_SEEK_BACK_MAX_DURATION, ETH)) else: eth_idx = idx + 1 wpan_idx = max( self._index[0], self._find_prev_packet(idx + 1, p.sniff_timestamp - consts.AUTO_SEEK_BACK_MAX_DURATION, WPAN)) # make sure index never go back assert wpan_idx >= self._index[0] assert eth_idx >= self._index[1] print('\n>>>_on_found_next %d %s => %s' % (idx, self._index, (wpan_idx, eth_idx)), file=sys.stderr) self._set_found_index(idx, (wpan_idx, eth_idx)) def _find_prev_packet(self, idx, min_sniff_timestamp, pkttype): assert pkttype in (WPAN, ETH) prev_idx = idx while idx > 0 and self._pkts[idx - 1].sniff_timestamp >= min_sniff_timestamp: idx -= 1 if pkttype == WPAN and self._pkts[idx].wpan: prev_idx = idx elif pkttype == ETH and self._pkts[idx].eth: prev_idx = idx return prev_idx def __iter__(self): for pkt in self._pkts: yield pkt def range(self, start, stop=None, cascade=True) -> 'PacketFilter': """ Create a new PacketFilter using the specified start and stop index tuples :param start: the new start index tuple :param stop: the new stop index tuple :param cascade: True if calling next in the new filter will also set index for this filter, False otherwise :return: a new PacketFilter with new start and stop range """ if stop is None: stop = self._stop_index assert self._start_index <= start <= self._stop_index assert self._start_index <= stop <= self._stop_index return PacketFilter(self._pkts, start, stop, filter_func=self._filter_func, parent=self if cascade else None) def copy(self) -> 'PacketFilter': """ :return: a copy of the current PacketFilter """ return PacketFilter(self._pkts, self._index, self._stop_index, filter_func=self._filter_func, parent=None) def __getitem__(self, index: int) -> Packet: """ :param index: the packet index (not tuple!) :return: the packet at the specified index """ assert isinstance(index, int), index return self._pkts[index] def seek_back(self, max_duration: float, *, eth=False, wpan=False) -> 'PacketFilter': """ Move the current index back in time within the specified max duration. Either eth or wpan must be True. :param max_duration: the max duration to move back :param eth: True if eth index can be moved back :param wpan: True if wpan index can be moved back :return: self """ assert eth or wpan, "must have eth or wpan" wpan_idx = self._index[0] if wpan and wpan_idx < len(self._pkts): wpan_idx = self._find_prev_packet(wpan_idx, self._pkts[wpan_idx].sniff_timestamp - max_duration, WPAN) wpan_idx = max(self._start_index[0], wpan_idx) eth_idx = self._index[1] if eth and eth_idx < len(self._pkts): eth_idx = self._find_prev_packet(eth_idx, self._pkts[eth_idx].sniff_timestamp - max_duration, ETH) eth_idx = max(self._start_index[1], eth_idx) print("\n>>> back %s wpan=%s, eth=%s: index %s => %s" % (max_duration, wpan, eth, self._index, (wpan_idx, eth_idx)), file=sys.stderr) self._index = (wpan_idx, eth_idx) self._check_type_ok() return self def _set_found_index(self, last_index: Tuple[int, int], index: Tuple[int, int]): self._last_index = last_index self._index = index self._check_type_ok() if self._parent is not None: self._parent._set_found_index(last_index, index) def filter_mle_advertisement(self, role: str, **kwargs): assert role in ('Leader', 'Router', 'REED'), role tlv_set = {consts.LEADER_DATA_TLV, consts.SOURCE_ADDRESS_TLV} if role != 'REED': tlv_set.add(consts.ROUTE64_TLV) return self.filter_LLANMA().\ filter_mle_cmd(consts.MLE_ADVERTISEMENT).\ filter(lambda p: tlv_set == set(p.mle.tlv.type) and\ p.ipv6.hlim == 255, **kwargs ) def filter_coap(self, **kwargs): """ Create a new PacketFilter to filter COAP packets. :param kwargs: Extra arguments for `filter`. :return: The new PacketFilter to filter COAP packets. """ return self.filter(attrgetter('coap'), **kwargs) def filter_coap_request(self, uri_path, port=None, confirmable=None, **kwargs): """ Create a new PacketFilter to filter COAP Request packets. :param uri_path: The COAP URI path to filter. :param port: The UDP port to filter if specified. :param kwargs: Extra arguments for `filter`. :return: The new PacketFilter to filter COAP Request packets. """ assert isinstance(uri_path, str), uri_path assert port is None or isinstance(port, int), port return self.filter( lambda p: (p.coap.is_post and p.coap.opt.uri_path_recon == uri_path and (confirmable is None or p.coap.type == (0 if confirmable else 1)) and (port is None or p.udp.dstport == port)), **kwargs) def filter_coap_ack(self, uri_path, port=None, **kwargs): """ Create a new PacketFilter for filter COAP ACK packets. :param uri_path: The COAP URI path to filter. :param port: The UDP port to filter if specified. :param kwargs: Extra arguments for `filter`. :return: The new PacketFilter to filter COAP ACK packets. """ assert isinstance(uri_path, str), uri_path assert port is None or isinstance(port, int), port return self.filter( lambda p: (p.coap.is_ack and p.coap.opt.uri_path_recon == uri_path and (port is None or p.udp.dstport == port)), **kwargs) def filter_backbone_answer(self, target: str, *, eth_src: Optional[EthAddr] = None, port: int = None, confirmable: bool = None, mliid=None): filter_eth = self.filter_eth_src(eth_src) if eth_src else self.filter_eth() f = filter_eth.filter_coap_request('/b/ba', port=port, confirmable=confirmable).filter('thread_bl.tlv.target_eid == {target}', target=target) if mliid is not None: f = f.filter('thread_bl.tlv.ml_eid == {mliid}', mliid=mliid) return f def filter_backbone_query(self, target: str, *, eth_src: EthAddr, port: int = None) -> 'PacketFilter': return self.filter_eth_src(eth_src).filter_coap_request('/b/bq', port=port, confirmable=False).filter( 'thread_bl.tlv.target_eid == {target}', target=target) def filter_wpan(self, **kwargs): """ Create a new PacketFilter for filter WPAN packets. :param kwargs: Extra arguments for `filter`. :return: The new PacketFilter to filter WPAN packets. """ return self.filter(attrgetter('wpan'), **kwargs) def filter_wpan_version(self, version: int, **kwargs): """ Create a new PacketFilter for filter WPAN packets of a given version. :param version: The version to filter. :param kwargs: Extra arguments for `filter`. :return: The new PacketFilter to filter WPAN packets. """ return self.filter(lambda p: p.wpan.version == version, **kwargs) def filter_wpan_channel(self, channel: int, **kwargs): """ Create a new PacketFilter for filter WPAN packets of a given channel. :param channel: The channel to filter. :param kwargs: Extra arguments for `filter`. :return: The new PacketFilter to filter WPAN packets. """ return self.filter(lambda p: p.wpan.channel == channel, **kwargs) def filter_wpan_src16(self, addr, **kwargs): return self.filter(lambda p: p.wpan.src16 == addr, **kwargs) def filter_wpan_dst16(self, addr, **kwargs): return self.filter(lambda p: p.wpan.dst16 == addr, **kwargs) def filter_wpan_src16_dst16(self, src_addr, dst_addr, **kwargs): return self.filter(lambda p: p.wpan.src16 == src_addr and p.wpan.dst16 == dst_addr, **kwargs) def filter_wpan_src64(self, addr, **kwargs): assert isinstance(addr, (str, ExtAddr)), addr return self.filter(lambda p: p.wpan.src64 == addr, **kwargs) def filter_wpan_dst64(self, addr, **kwargs): assert isinstance(addr, (str, ExtAddr)), addr return self.filter(lambda p: p.wpan.dst64 == addr, **kwargs) def filter_dst16(self, rloc16: int, **kwargs): return self.filter(lambda p: p.lowpan.mesh.dest16 == rloc16 or p.wpan.dst16 == rloc16, **kwargs) def filter_ping_request(self, identifier=None, **kwargs): return self.filter( lambda p: p.icmpv6.is_ping_request and (identifier is None or p.icmpv6.echo.identifier == identifier), **kwargs) def filter_ping_reply(self, **kwargs): identifier = kwargs.pop('identifier', None) return self.filter( lambda p: (p.icmpv6.is_ping_reply and (identifier is None or p.icmpv6.echo.identifier == identifier)), **kwargs) def filter_eth(self, **kwargs): return self.filter(attrgetter('eth'), **kwargs) def filter_eth_src(self, addr, **kwargs): assert isinstance(addr, (str, EthAddr)) return self.filter(lambda p: p.eth.src == addr, **kwargs) def filter_ipv6_dst(self, addr, **kwargs): assert isinstance(addr, (str, Ipv6Addr)) return self.filter(lambda p: p.ipv6.dst == addr, **kwargs) def filter_ipv6_2dsts(self, addr1, addr2, **kwargs): assert isinstance(addr1, (str, Ipv6Addr)) assert isinstance(addr2, (str, Ipv6Addr)) return self.filter(lambda p: p.ipv6.dst == addr1 or p.ipv6.dst == addr2, **kwargs) def filter_ipv6_src_dst(self, src_addr, dst_addr, **kwargs): assert isinstance(src_addr, (str, Ipv6Addr)) assert isinstance(dst_addr, (str, Ipv6Addr)) return self.filter(lambda p: p.ipv6.src == src_addr and p.ipv6.dst == dst_addr, **kwargs) def filter_LLATNMA(self, **kwargs): return self.filter(lambda p: p.ipv6.dst == consts.LINK_LOCAL_All_THREAD_NODES_MULTICAST_ADDRESS, **kwargs) def filter_RLANMA(self, **kwargs): return self.filter(lambda p: p.ipv6.dst == consts.REALM_LOCAL_ALL_NODES_ADDRESS, **kwargs) def filter_RLARMA(self, **kwargs): return self.filter(lambda p: p.ipv6.dst == consts.REALM_LOCAL_ALL_ROUTERS_ADDRESS, **kwargs) def filter_RLATNMA(self, **kwargs): return self.filter(lambda p: p.ipv6.dst == consts.REALM_LOCAL_All_THREAD_NODES_MULTICAST_ADDRESS, **kwargs) def filter_LLANMA(self, **kwargs): return self.filter(lambda p: p.ipv6.dst == consts.LINK_LOCAL_ALL_NODES_MULTICAST_ADDRESS, **kwargs) def filter_LLABMA(self, **kwargs): return self.filter(lambda p: p.ipv6.dst == consts.LINK_LOCAL_ALL_BBRS_MULTICAST_ADDRESS, **kwargs) def filter_LLARMA(self, **kwargs): return self.filter(lambda p: p.ipv6.dst == consts.LINK_LOCAL_ALL_ROUTERS_MULTICAST_ADDRESS, **kwargs) def filter_AMPLFMA(self, **kwargs): return self.filter(lambda p: p.ipv6.dst == consts.ALL_MPL_FORWARDERS_MA, **kwargs) def filter_mle(self, **kwargs): return self.filter(attrgetter('mle'), **kwargs) def filter_wpan_cmd(self, cmd, **kwargs): assert isinstance(cmd, int), cmd return self.filter(lambda p: p.wpan.cmd == cmd, **kwargs) def filter_mle_cmd(self, cmd, **kwargs): assert isinstance(cmd, int), cmd return self.filter(lambda p: p.mle.cmd == cmd, **kwargs) def filter_mle_cmd2(self, cmd1, cmd2, **kwargs): assert isinstance(cmd1, int), cmd1 assert isinstance(cmd2, int), cmd2 return self.filter(lambda p: p.mle.cmd == cmd1 or p.mle.cmd == cmd2, **kwargs) def filter_mle_has_tlv(self, *tlv_types, **kwargs): return self.filter(lambda p: set(tlv_types) <= set(p.mle.tlv.type), **kwargs) def filter_icmpv6(self, **kwargs): return self.filter(attrgetter('icmpv6'), **kwargs) def filter_icmpv6_nd_ns(self, target_address: Ipv6Addr): return self.filter(lambda p: (p.icmpv6.is_neighbor_solicitation and p.icmpv6.nd.ns.target_address == target_address)) def filter_icmpv6_nd_na(self, target_address: Ipv6Addr): return self.filter(lambda p: (p.icmpv6.is_neighbor_advertisement and p.icmpv6.nd.na.target_address == target_address)) def filter_has_bbr_dataset(self): return self.filter(""" thread_nwd.tlv.server.has('16') and thread_nwd.tlv.service.s_data.seqno is not null and thread_nwd.tlv.service.s_data.rrdelay is not null and thread_nwd.tlv.service.s_data.mlrtimeout is not null """)
import sys sys.path.insert(0, '../') import ply.yacc as yacc from ctokens import tokens from pymag_trees.gen import Tree def span(p, start, end): if isinstance(p[start], Tree): s = p[start].node['span'][0] else: s = p.lexpos(start) if isinstance(p[end], Tree): e = p[end].node['span'][1] else: e = p.lexpos(end) + len(p[end]) return [s, e] def Node(type="", span=[-1, -1]): return { 'type': type, 'span': span, 'value': None } start = 'trans_unit' precedence = ( ('left', 'OROR'), ('left', 'ANDAND'), ('left', 'EQUALEQUAL'), ('left', 'LT', 'LE', 'GT', 'GE'), ('left', 'PLUS', 'MINUS'), ('left', 'TIMES', 'DIVIDE', 'MOD'), ('right', 'NOT'), ('nonassoc', 'LOWER_THAN_ELSE') , ('nonassoc', 'ELSE'), ) def p_trans_unit(p): 'trans_unit : element trans_unit' p[0] = Tree(Node('trans_unit'), p[1], p[2]) def p_trans_unit_empty(p): 'trans_unit : element' p[0] = Tree(Node('trans_unit'), p[1]) def p_element_stmt(p): 'element : stmt' p[0] = p[1] def p_element_function(p): 'element : type identifier LPAREN optparams RPAREN compoundstmt' p[0] = Tree(Node('function'), p[1], p[2], p[4], p[6]) def p_identifier(p): 'identifier : IDENTIFIER' p[0] = Tree(Node('identifier', span(p, 1, 1)), Tree(Node(p[1], span(p, 1, 1)))) def p_reference(p): 'reference : AND IDENTIFIER' p[0] = Tree(Node('reference', span(p, 1, 2)), Tree(Node(p[2], span(p, 2, 2)))) def p_type(p): '''type : INT | CHAR | FLOAT | VOID''' p[0] = Tree(Node('type', span(p, 1, 1)), Tree(Node(p[1], span(p, 1, 1)))) def p_optparams(p): 'optparams : params' p[0] = p[1] def p_optparams_empty(p): 'optparams : ' p[0] = Tree(Node('params')) def p_params_one(p): 'params : param' p[0] = Tree(Node('params'), p[1]) def p_params_comma(p): 'params : param COMMA params' p[0] = Tree(Node('params'), p[1], p[3]) def p_param(p): 'param : type identifier' p[0] = Tree(Node('param'), p[1], p[2]) def p_compoundstmt(p): 'compoundstmt : LBRACE stmts RBRACE' p[0] = p[2] def p_stmts(p): 'stmts : stmt stmts' p[0] = Tree(Node('stmts'), p[1], p[2]) def p_stmts_one(p): 'stmts : stmt' p[0] = Tree(Node('stmts'), p[1]) def p_stmt_or_compound(p): 'stmt_or_compound : stmt' p[0] = Tree(Node('stmts'), p[1]) def p_stmt_or_compound_c(p): 'stmt_or_compound : compoundstmt' p[0] = p[1] def p_optsemi_none(p): 'optsemi : ' p[0] = Tree(Node()) def p_optsemi_some(p): 'optsemi : SEMICOLON' p[0] = Tree(Node()) def p_stmt_estmt(p): 'stmt : estmt' p[0] = Tree(Node('stmt'), p[1]) def p_stmt_if(p): 'estmt : IF exp stmt_or_compound optsemi %prec LOWER_THAN_ELSE' p[0] = Tree(Node('if-then'), p[2], p[3]) def p_stmt_while(p): 'estmt : WHILE exp compoundstmt optsemi' p[0] = Tree(Node('while'), p[2], p[3]) def p_stmt_if_else(p): 'estmt : IF exp compoundstmt ELSE stmt_or_compound optsemi' p[0] = Tree(Node('if-then-else'), p[2], p[3], p[5]) def p_stmt_declaration(p): 'estmt : type identifier EQUAL exp optsemi' p[0] = Tree(Node('declaration', span(p, 1, 4)), p[1], p[2], Tree(Node(p[3], span(p, 3, 3))), p[4]) def p_stmt_assigment(p): 'estmt : identifier EQUAL exp optsemi' p[0] = Tree(Node('assign', span(p, 1, 3)), p[1], Tree(Node(p[2], span(p, 2, 2))), p[3]) def p_stmt_return(p): 'estmt : RETURN exp optsemi' p[0] = Tree(Node('return', span(p, 1, 2)), p[2]) def p_stmt_exp(p): 'estmt : exp optsemi' p[0] = p[1] def p_exp_eexp(p): 'exp : eexp' p[0] = Tree(Node('exp', span(p, 1, 1)), p[1]) def p_exp_identifier(p): 'eexp : identifier' p[0] = p[1] def p_exp_reference(p): 'eexp : reference' p[0] = p[1] def p_exp_paren(p): 'exp : LPAREN exp RPAREN' p[0] = p[2] def p_exp_number(p): 'eexp : NUMBER' p[0] = Tree(Node('number', span(p, 1, 1)), Tree(Node(p[1], span(p, 1, 1)))) def p_exp_string(p): 'eexp : STRING' p[0] = Tree(Node('string', span(p, 1, 1)), Tree(Node(p[1]))) def p_exp_true(p): 'eexp : TRUE' p[0] = Tree(Node('boolean', span(p, 1, 1)), Tree(Node(p[1]))) def p_exp_false(p): 'eexp : FALSE' p[0] = Tree(Node('boolean', span(p, 1, 1)), Tree(Node(p[1]))) def p_exp_not(p): 'eexp : NOT exp' p[0] = Tree(Node('not'), p[2]) def p_exp_binop(p): '''eexp : exp PLUS exp | exp MINUS exp | exp TIMES exp | exp MOD exp | exp DIVIDE exp | exp EQUALEQUAL exp | exp LE exp | exp LT exp | exp GE exp | exp GT exp | exp ANDAND exp | exp OROR exp''' p[0] = Tree(Node('binop', span(p, 1, 3)), p[1], Tree(Node(p[2], span(p, 2, 2))), p[3]) def p_exp_call(p): 'eexp : identifier LPAREN optargs RPAREN' p[0] = Tree(Node('call', span(p, 1, 4)), p[1], p[3]) def p_optargs(p): 'optargs : args' p[0] = p[1] def p_optargs_empty(p): 'optargs : ' p[0] = Tree(Node('args')) def p_args_comma(p): 'args : arg COMMA args' p[0] = Tree(Node('args'), p[1], p[3]) def p_args_one(p): 'args : arg' p[0] = Tree(Node('args'), p[1]) def p_arg(p): 'arg : exp' p[0] = Tree(Node('arg', span(p, 1, 1)), p[1]) def p_error(p): pass
""" This tutorial shows how to generate adversarial examples using FGSM in black-box setting. The original paper can be found at: https://arxiv.org/abs/1602.02697 """ # pylint: disable=missing-docstring from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import functools import logging import numpy as np from six.moves import xrange import tensorflow as tf from cleverhans.attacks import FastGradientMethod from cleverhans.utils_tf import jacobian_graph, jacobian_augmentation from cleverhans.compat import flags from cleverhans.dataset import MNIST from cleverhans.initializers import HeReLuNormalInitializer from cleverhans.loss import CrossEntropy from cleverhans.model import Model from cleverhans.train import train from cleverhans.utils import set_log_level from cleverhans.utils import TemporaryLogLevel from cleverhans.utils import to_categorical from cleverhans.utils_tf import model_eval, batch_eval from cleverhans.model_zoo.basic_cnn import ModelBasicCNN FLAGS = flags.FLAGS NB_CLASSES = 10 BATCH_SIZE = 128 LEARNING_RATE = .001 NB_EPOCHS = 10 HOLDOUT = 150 DATA_AUG = 6 NB_EPOCHS_S = 10 LMBDA = .1 AUG_BATCH_SIZE = 512 def setup_tutorial(): """ Helper function to check correct configuration of tf for tutorial :return: True if setup checks completed """ # Set TF random seed to improve reproducibility tf.set_random_seed(1234) return True def prep_bbox(sess, x, y, x_train, y_train, x_test, y_test, nb_epochs, batch_size, learning_rate, rng, nb_classes=10, img_rows=28, img_cols=28, nchannels=1): """ Define and train a model that simulates the "remote" black-box oracle described in the original paper. :param sess: the TF session :param x: the input placeholder for MNIST :param y: the ouput placeholder for MNIST :param x_train: the training data for the oracle :param y_train: the training labels for the oracle :param x_test: the testing data for the oracle :param y_test: the testing labels for the oracle :param nb_epochs: number of epochs to train model :param batch_size: size of training batches :param learning_rate: learning rate for training :param rng: numpy.random.RandomState :return: """ # Define TF model graph (for the black-box model) nb_filters = 64 model = ModelBasicCNN('model1', nb_classes, nb_filters) loss = CrossEntropy(model, smoothing=0.1) predictions = model.get_logits(x) print("Defined TensorFlow model graph.") # Train an MNIST model train_params = { 'nb_epochs': nb_epochs, 'batch_size': batch_size, 'learning_rate': learning_rate } train(sess, loss, x_train, y_train, args=train_params, rng=rng) # Print out the accuracy on legitimate data eval_params = {'batch_size': batch_size} accuracy = model_eval(sess, x, y, predictions, x_test, y_test, args=eval_params) print('Test accuracy of black-box on legitimate test ' 'examples: ' + str(accuracy)) return model, predictions, accuracy class ModelSubstitute(Model): def __init__(self, scope, nb_classes, nb_filters=200, **kwargs): del kwargs Model.__init__(self, scope, nb_classes, locals()) self.nb_filters = nb_filters def fprop(self, x, **kwargs): del kwargs my_dense = functools.partial( tf.layers.dense, kernel_initializer=HeReLuNormalInitializer) with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE): y = tf.layers.flatten(x) y = my_dense(y, self.nb_filters, activation=tf.nn.relu) y = my_dense(y, self.nb_filters, activation=tf.nn.relu) logits = my_dense(y, self.nb_classes) return {self.O_LOGITS: logits, self.O_PROBS: tf.nn.softmax(logits=logits)} def train_sub(sess, x, y, bbox_preds, x_sub, y_sub, nb_classes, nb_epochs_s, batch_size, learning_rate, data_aug, lmbda, aug_batch_size, rng, img_rows=28, img_cols=28, nchannels=1): """ This function creates the substitute by alternatively augmenting the training data and training the substitute. :param sess: TF session :param x: input TF placeholder :param y: output TF placeholder :param bbox_preds: output of black-box model predictions :param x_sub: initial substitute training data :param y_sub: initial substitute training labels :param nb_classes: number of output classes :param nb_epochs_s: number of epochs to train substitute model :param batch_size: size of training batches :param learning_rate: learning rate for training :param data_aug: number of times substitute training data is augmented :param lmbda: lambda from arxiv.org/abs/1602.02697 :param rng: numpy.random.RandomState instance :return: """ # Define TF model graph (for the black-box model) model_sub = ModelSubstitute('model_s', nb_classes) preds_sub = model_sub.get_logits(x) loss_sub = CrossEntropy(model_sub, smoothing=0) print("Defined TensorFlow model graph for the substitute.") # Define the Jacobian symbolically using TensorFlow grads = jacobian_graph(preds_sub, x, nb_classes) # Train the substitute and augment dataset alternatively for rho in xrange(data_aug): print("Substitute training epoch #" + str(rho)) train_params = { 'nb_epochs': nb_epochs_s, 'batch_size': batch_size, 'learning_rate': learning_rate } with TemporaryLogLevel(logging.WARNING, "cleverhans.utils.tf"): train(sess, loss_sub, x_sub, to_categorical(y_sub, nb_classes), init_all=False, args=train_params, rng=rng, var_list=model_sub.get_params()) # If we are not at last substitute training iteration, augment dataset if rho < data_aug - 1: print("Augmenting substitute training data.") # Perform the Jacobian augmentation lmbda_coef = 2 * int(int(rho / 3) != 0) - 1 x_sub = jacobian_augmentation(sess, x, x_sub, y_sub, grads, lmbda_coef * lmbda, aug_batch_size) print("Labeling substitute training data.") # Label the newly generated synthetic points using the black-box y_sub = np.hstack([y_sub, y_sub]) x_sub_prev = x_sub[int(len(x_sub)/2):] eval_params = {'batch_size': batch_size} bbox_val = batch_eval(sess, [x], [bbox_preds], [x_sub_prev], args=eval_params)[0] # Note here that we take the argmax because the adversary # only has access to the label (not the probabilities) output # by the black-box model y_sub[int(len(x_sub)/2):] = np.argmax(bbox_val, axis=1) return model_sub, preds_sub def mnist_blackbox(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_classes=NB_CLASSES, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, nb_epochs=NB_EPOCHS, holdout=HOLDOUT, data_aug=DATA_AUG, nb_epochs_s=NB_EPOCHS_S, lmbda=LMBDA, aug_batch_size=AUG_BATCH_SIZE): """ MNIST tutorial for the black-box attack from arxiv.org/abs/1602.02697 :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :return: a dictionary with: * black-box model accuracy on test set * substitute model accuracy on test set * black-box model accuracy on adversarial examples transferred from the substitute model """ # Set logging level to see debug information set_log_level(logging.DEBUG) # Dictionary used to keep track and return key accuracies accuracies = {} # Perform tutorial setup assert setup_tutorial() # Create TF session sess = tf.Session() # Get MNIST data mnist = MNIST(train_start=train_start, train_end=train_end, test_start=test_start, test_end=test_end) x_train, y_train = mnist.get_set('train') x_test, y_test = mnist.get_set('test') # Initialize substitute training set reserved for adversary x_sub = x_test[:holdout] y_sub = np.argmax(y_test[:holdout], axis=1) # Redefine test set as remaining samples unavailable to adversaries x_test = x_test[holdout:] y_test = y_test[holdout:] # Obtain Image parameters img_rows, img_cols, nchannels = x_train.shape[1:4] nb_classes = y_train.shape[1] # Define input TF placeholder x = tf.placeholder(tf.float32, shape=(None, img_rows, img_cols, nchannels)) y = tf.placeholder(tf.float32, shape=(None, nb_classes)) # Seed random number generator so tutorial is reproducible rng = np.random.RandomState([2017, 8, 30]) # Simulate the black-box model locally # You could replace this by a remote labeling API for instance print("Preparing the black-box model.") prep_bbox_out = prep_bbox(sess, x, y, x_train, y_train, x_test, y_test, nb_epochs, batch_size, learning_rate, rng, nb_classes, img_rows, img_cols, nchannels) model, bbox_preds, accuracies['bbox'] = prep_bbox_out # Train substitute using method from https://arxiv.org/abs/1602.02697 print("Training the substitute model.") train_sub_out = train_sub(sess, x, y, bbox_preds, x_sub, y_sub, nb_classes, nb_epochs_s, batch_size, learning_rate, data_aug, lmbda, aug_batch_size, rng, img_rows, img_cols, nchannels) model_sub, preds_sub = train_sub_out # Evaluate the substitute model on clean test examples eval_params = {'batch_size': batch_size} acc = model_eval(sess, x, y, preds_sub, x_test, y_test, args=eval_params) accuracies['sub'] = acc # Initialize the Fast Gradient Sign Method (FGSM) attack object. fgsm_par = {'eps': 0.3, 'ord': np.inf, 'clip_min': 0., 'clip_max': 1.} fgsm = FastGradientMethod(model_sub, sess=sess) # Craft adversarial examples using the substitute eval_params = {'batch_size': batch_size} x_adv_sub = fgsm.generate(x, **fgsm_par) # Evaluate the accuracy of the "black-box" model on adversarial examples accuracy = model_eval(sess, x, y, model.get_logits(x_adv_sub), x_test, y_test, args=eval_params) print('Test accuracy of oracle on adversarial examples generated ' 'using the substitute: ' + str(accuracy)) accuracies['bbox_on_sub_adv_ex'] = accuracy return accuracies def main(argv=None): from cleverhans_tutorials import check_installation check_installation(__file__) mnist_blackbox(nb_classes=FLAGS.nb_classes, batch_size=FLAGS.batch_size, learning_rate=FLAGS.learning_rate, nb_epochs=FLAGS.nb_epochs, holdout=FLAGS.holdout, data_aug=FLAGS.data_aug, nb_epochs_s=FLAGS.nb_epochs_s, lmbda=FLAGS.lmbda, aug_batch_size=FLAGS.data_aug_batch_size) if __name__ == '__main__': # General flags flags.DEFINE_integer('nb_classes', NB_CLASSES, 'Number of classes in problem') flags.DEFINE_integer('batch_size', BATCH_SIZE, 'Size of training batches') flags.DEFINE_float('learning_rate', LEARNING_RATE, 'Learning rate for training') # Flags related to oracle flags.DEFINE_integer('nb_epochs', NB_EPOCHS, 'Number of epochs to train model') # Flags related to substitute flags.DEFINE_integer('holdout', HOLDOUT, 'Test set holdout for adversary') flags.DEFINE_integer('data_aug', DATA_AUG, 'Number of substitute data augmentations') flags.DEFINE_integer('nb_epochs_s', NB_EPOCHS_S, 'Training epochs for substitute') flags.DEFINE_float('lmbda', LMBDA, 'Lambda from arxiv.org/abs/1602.02697') flags.DEFINE_integer('data_aug_batch_size', AUG_BATCH_SIZE, 'Batch size for augmentation') tf.app.run()
# Copyright (c) 2006-2007 The Regents of The University of Michigan # Copyright (c) 2009 Advanced Micro Devices, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: Brad Beckmann import math import m5 import VI_hammer from m5.objects import * from m5.defines import buildEnv from Cluster import Cluster from Ruby import send_evicts class L1Cache(RubyCache): pass class L2Cache(RubyCache): pass def create_system(options, full_system, system, dma_devices, ruby_system): if not buildEnv['GPGPU_SIM']: m5.util.panic("This script requires GPGPU-Sim integration to be built.") # Run the protocol script to setup CPU cluster, directory and DMA (all_sequencers, dir_cntrls, dma_cntrls, cpu_cluster) = \ VI_hammer.create_system(options, full_system, system, dma_devices, ruby_system) cpu_cntrl_count = len(cpu_cluster) + len(dir_cntrls) # # Build GPU cluster # # Empirically, Fermi per-core bandwidth peaks at roughly 23GB/s # (32B/cycle @ 772MHz). Use ~16B per Ruby cycle to match this. Maxwell # per-core bandwidth peaks at 40GB/s (42B/cycle @ 1029MHz). Use ~24B per # Ruby cycle to match this. if options.gpu_core_config == 'Fermi': l1_cluster_bw = 16 elif options.gpu_core_config == 'Maxwell': l1_cluster_bw = 24 elif options.gpu_core_config == 'Tegra': #FIXME using Fermi for now l1_cluster_bw = 16 else: m5.util.fatal("Unknown GPU core config: %s" % options.gpu_core_config) gpu_cluster = Cluster(intBW = l1_cluster_bw, extBW = l1_cluster_bw) gpu_cluster.disableConnectToParent() l2_bits = int(math.log(options.gpu_num_l2caches, 2)) block_size_bits = int(math.log(options.cacheline_size, 2)) # This represents the L1 to L2 interconnect latency # NOTES! 1) This latency is in Ruby (cache) cycles, not SM cycles # 2) Since the cluster interconnect doesn't model multihop latencies, # model these latencies with the controller latency variables. If # the interconnect model is changed, latencies will need to be # adjusted for reasonable total memory access delay. per_hop_interconnect_latency = 45 # ~15 GPU cycles num_dance_hall_hops = int(math.log(options.num_sc, 2)) if num_dance_hall_hops == 0: num_dance_hall_hops = 1 l1_to_l2_noc_latency = per_hop_interconnect_latency * num_dance_hall_hops # # Caches for GPU cores # for i in xrange(options.num_sc): # # First create the Ruby objects associated with the GPU cores # data_cache = L1Cache(size = options.sc_l1_size, assoc = options.sc_l1_assoc, replacement_policy = LRUReplacementPolicy(), start_index_bit = block_size_bits, dataArrayBanks = 4, tagArrayBanks = 4, dataAccessLatency = 4, tagAccessLatency = 4, resourceStalls = False) data_l1_cntrl = GPUL1Cache_Controller(version = i*2, cache = data_cache, l2_select_num_bits = l2_bits, num_l2 = options.gpu_num_l2caches, transitions_per_cycle = options.ports, issue_latency = l1_to_l2_noc_latency, number_of_TBEs = options.gpu_l1_buf_depth, ruby_system = ruby_system) data_gpu_seq = RubySequencer(version = options.num_cpus + i*2, icache = data_cache, dcache = data_cache, max_outstanding_requests = options.gpu_l1_buf_depth, ruby_system = ruby_system, deadlock_threshold = 2000000, connect_to_io = False) tex_cache = L1Cache(size = options.sc_tl1_size, assoc = options.sc_tl1_assoc, replacement_policy = LRUReplacementPolicy(), start_index_bit = block_size_bits, dataArrayBanks = 4, tagArrayBanks = 4, dataAccessLatency = 4, tagAccessLatency = 4, resourceStalls = False) tex_l1_cntrl = GPUL1Cache_Controller(version = i*2+1, cache = tex_cache, l2_select_num_bits = l2_bits, num_l2 = options.gpu_num_l2caches, transitions_per_cycle = options.ports, issue_latency = l1_to_l2_noc_latency, number_of_TBEs = options.gpu_tl1_buf_depth, ruby_system = ruby_system) tex_gpu_seq = RubySequencer(version = options.num_cpus + i*2+1, icache = tex_cache, dcache = tex_cache, max_outstanding_requests = options.gpu_tl1_buf_depth, ruby_system = ruby_system, deadlock_threshold = 2000000, connect_to_io = False) data_l1_cntrl.sequencer = data_gpu_seq tex_l1_cntrl.sequencer = tex_gpu_seq data_i = i*2; tex_i = i*2 +1; exec("ruby_system.l1_cntrl_sp%02d = data_l1_cntrl" % data_i) exec("ruby_system.l1_cntrl_sp%02d = tex_l1_cntrl" % tex_i) # # Add controllers and sequencers to the appropriate lists # all_sequencers.append(data_gpu_seq) all_sequencers.append(tex_gpu_seq) gpu_cluster.add(data_l1_cntrl) gpu_cluster.add(tex_l1_cntrl) # Connect the controllers to the network data_l1_cntrl.requestFromL1Cache = MessageBuffer(ordered = True) data_l1_cntrl.requestFromL1Cache.master = ruby_system.network.slave data_l1_cntrl.responseToL1Cache = MessageBuffer(ordered = True) data_l1_cntrl.responseToL1Cache.slave = ruby_system.network.master data_l1_cntrl.mandatoryQueue = MessageBuffer() tex_l1_cntrl.requestFromL1Cache = MessageBuffer(ordered = True) tex_l1_cntrl.requestFromL1Cache.master = ruby_system.network.slave tex_l1_cntrl.responseToL1Cache = MessageBuffer(ordered = True) tex_l1_cntrl.responseToL1Cache.slave = ruby_system.network.master tex_l1_cntrl.mandatoryQueue = MessageBuffer() l2_index_start = block_size_bits + l2_bits # Use L2 cache and interconnect latencies to calculate protocol latencies # NOTES! 1) These latencies are in Ruby (cache) cycles, not SM cycles # 2) Since the cluster interconnect doesn't model multihop latencies, # model these latencies with the controller latency variables. If # the interconnect model is changed, latencies will need to be # adjusted for reasonable total memory access delay. l2_cache_access_latency = 30 # ~10 GPU cycles l2_to_l1_noc_latency = per_hop_interconnect_latency * num_dance_hall_hops l2_to_mem_noc_latency = 125 # ~40 GPU cycles # Empirically, Fermi per-L2 bank bandwidth peaks at roughly 66GB/s # (92B/cycle @ 772MHz). Use ~34B per Ruby cycle to match this. Maxwell # per-L2 bank bandwidth peaks at 123GB/s (128B/cycle @ 1029MHz). Use ~64B # per Ruby cycle to match this. if options.gpu_core_config == 'Fermi': l2_cluster_bw = 34 elif options.gpu_core_config == 'Maxwell': l2_cluster_bw = 68 elif options.gpu_core_config == 'Tegra': #FIXME using Fermi configs for now l2_cluster_bw = 34 else: m5.util.fatal("Unknown GPU core config: %s" % options.gpu_core_config) l2_clusters = [] for i in xrange(options.gpu_num_l2caches): # # First create the Ruby objects associated with this cpu # l2_cache = L2Cache(size = options.sc_l2_size, assoc = options.sc_l2_assoc, start_index_bit = l2_index_start, replacement_policy = LRUReplacementPolicy(), dataArrayBanks = 4, tagArrayBanks = 4, dataAccessLatency = 4, tagAccessLatency = 4, resourceStalls = options.gpu_l2_resource_stalls) l2_cntrl = GPUL2Cache_Controller(version = i, L2cache = l2_cache, transitions_per_cycle = options.ports, l2_response_latency = l2_cache_access_latency + l2_to_l1_noc_latency, l2_request_latency = l2_to_mem_noc_latency, cache_response_latency = l2_cache_access_latency, ruby_system = ruby_system) exec("ruby_system.l2_cntrl%d = l2_cntrl" % i) l2_cluster = Cluster(intBW = l2_cluster_bw, extBW = l2_cluster_bw) l2_cluster.add(l2_cntrl) gpu_cluster.add(l2_cluster) l2_clusters.append(l2_cluster) # Connect the controller to the network l2_cntrl.responseToL1Cache = MessageBuffer(ordered = True) l2_cntrl.responseToL1Cache.master = ruby_system.network.slave l2_cntrl.requestFromCache = MessageBuffer() l2_cntrl.requestFromCache.master = ruby_system.network.slave l2_cntrl.responseFromCache = MessageBuffer() l2_cntrl.responseFromCache.master = ruby_system.network.slave l2_cntrl.unblockFromCache = MessageBuffer() l2_cntrl.unblockFromCache.master = ruby_system.network.slave l2_cntrl.requestFromL1Cache = MessageBuffer(ordered = True) l2_cntrl.requestFromL1Cache.slave = ruby_system.network.master l2_cntrl.forwardToCache = MessageBuffer() l2_cntrl.forwardToCache.slave = ruby_system.network.master l2_cntrl.responseToCache = MessageBuffer() l2_cntrl.responseToCache.slave = ruby_system.network.master l2_cntrl.triggerQueue = MessageBuffer() ############################################################################ # Pagewalk cache # NOTE: We use a CPU L1 cache controller here. This is to facilatate MMU # cache coherence (as the GPU L1 caches are incoherent without flushes # The L2 cache is small, and should have minimal affect on the # performance (see Section 6.2 of Power et al. HPCA 2014). pwd_cache = L1Cache(size = options.pwc_size, assoc = options.pwc_assoc, replacement_policy = options.pwc_policy, start_index_bit = block_size_bits, resourceStalls = False) # Small cache since CPU L1 requires I and D pwi_cache = L1Cache(size = "512B", assoc = 2, replacement_policy = LRUReplacementPolicy(), start_index_bit = block_size_bits, resourceStalls = False) # Small cache since CPU L1 controller requires L2 l2_cache = L2Cache(size = "512B", assoc = 2, start_index_bit = block_size_bits, resourceStalls = False) l1_cntrl = L1Cache_Controller(version = options.num_cpus, L1Icache = pwi_cache, L1Dcache = pwd_cache, L2cache = l2_cache, send_evictions = False, transitions_per_cycle = options.ports, issue_latency = l1_to_l2_noc_latency, cache_response_latency = 1, l2_cache_hit_latency = 1, number_of_TBEs = options.gpu_l1_buf_depth, ruby_system = ruby_system) cpu_seq = RubySequencer(version = options.num_cpus + options.num_sc*2, icache = pwd_cache, # Never get data from pwi_cache dcache = pwd_cache, dcache_hit_latency = 8, icache_hit_latency = 8, max_outstanding_requests = options.gpu_l1_buf_depth, ruby_system = ruby_system, deadlock_threshold = 2000000, connect_to_io = False) l1_cntrl.sequencer = cpu_seq ruby_system.l1_pw_cntrl = l1_cntrl all_sequencers.append(cpu_seq) gpu_cluster.add(l1_cntrl) # Connect the L1 controller and the network # Connect the buffers from the controller to network l1_cntrl.requestFromCache = MessageBuffer() l1_cntrl.requestFromCache.master = ruby_system.network.slave l1_cntrl.responseFromCache = MessageBuffer() l1_cntrl.responseFromCache.master = ruby_system.network.slave l1_cntrl.unblockFromCache = MessageBuffer() l1_cntrl.unblockFromCache.master = ruby_system.network.slave # Connect the buffers from the network to the controller l1_cntrl.forwardToCache = MessageBuffer() l1_cntrl.forwardToCache.slave = ruby_system.network.master l1_cntrl.responseToCache = MessageBuffer() l1_cntrl.responseToCache.slave = ruby_system.network.master l1_cntrl.mandatoryQueue = MessageBuffer() l1_cntrl.triggerQueue = MessageBuffer() # # Create controller for the copy engine to connect to in GPU cluster # Cache is unused by controller # cache = L1Cache(size = "4096B", assoc = 2) # Setting options.ce_buffering = 0 indicates that the CE can use infinite # buffering, but we need to specify a finite number of outstandng accesses # that the CE is allowed to issue. Just set it to some large number greater # than normal memory access latencies to ensure that the sequencer could # service one access per cycle. max_out_reqs = options.ce_buffering if max_out_reqs == 0: max_out_reqs = 1024 gpu_ce_seq = RubySequencer(version = options.num_cpus + options.num_sc*2 +1, icache = cache, dcache = cache, max_outstanding_requests = max_out_reqs, support_inst_reqs = False, ruby_system = ruby_system, connect_to_io = False) gpu_ce_cntrl = GPUCopyDMA_Controller(version = 0, sequencer = gpu_ce_seq, transitions_per_cycle = options.ports, number_of_TBEs = max_out_reqs, ruby_system = ruby_system) gpu_ce_cntrl.responseFromDir = MessageBuffer(ordered = True) gpu_ce_cntrl.responseFromDir.slave = ruby_system.network.master gpu_ce_cntrl.reqToDirectory = MessageBuffer(ordered = True) gpu_ce_cntrl.reqToDirectory.master = ruby_system.network.slave gpu_ce_cntrl.mandatoryQueue = MessageBuffer() ruby_system.ce_cntrl = gpu_ce_cntrl all_sequencers.append(gpu_ce_seq) # To limit the copy engine's bandwidth, we add it to a limited bandwidth # cluster. Approximate settings are as follows (assuming 2GHz Ruby clock): # PCIe v1.x x16 effective bandwidth ~= 4GB/s: intBW = 3, extBW = 3 # PCIe v2.x x16 effective bandwidth ~= 8GB/s: intBW = 5, extBW = 5 # PCIe v3.x x16 effective bandwidth ~= 16GB/s: intBW = 10, extBW = 10 # PCIe v4.x x16 effective bandwidth ~= 32GB/s: intBW = 21, extBW = 21 # NOTE: Bandwidth may bottleneck at other parts of the memory hierarchy, # so bandwidth considerations should be made in other parts of the memory # hierarchy also. gpu_ce_cluster = Cluster(intBW = 10, extBW = 10) gpu_ce_cluster.add(gpu_ce_cntrl) #z cache z_cache = L1Cache(size = options.sc_zl1_size, assoc = options.sc_zl1_assoc, replacement_policy = LRUReplacementPolicy(), start_index_bit = block_size_bits, dataArrayBanks = 8, tagArrayBanks = 8, dataAccessLatency = 1, tagAccessLatency = 1, resourceStalls = False) z_cntrl = GPUL1Cache_Controller(version = options.num_sc*2, cache = z_cache, l2_select_num_bits = l2_bits, num_l2 = options.gpu_num_l2caches, issue_latency = l1_to_l2_noc_latency, number_of_TBEs = options.gpu_zl1_buf_depth, ruby_system = ruby_system) z_seq = RubySequencer(version = options.num_cpus + options.num_sc*2+2, icache = z_cache, dcache = z_cache, max_outstanding_requests = options.gpu_zl1_buf_depth, ruby_system = ruby_system, deadlock_threshold = 2000000, connect_to_io = False) z_cntrl.sequencer = z_seq ruby_system.l1z_cntrl = z_cntrl all_sequencers.append(z_seq) gpu_cluster.add(z_cntrl) z_cntrl.requestFromL1Cache = MessageBuffer(ordered = True) z_cntrl.requestFromL1Cache.master = ruby_system.network.slave z_cntrl.responseToL1Cache = MessageBuffer(ordered = True) z_cntrl.responseToL1Cache.slave = ruby_system.network.master z_cntrl.mandatoryQueue = MessageBuffer() #z cache acl_cntrls = [] if options.accel_cfg_file: for idx, datapath in enumerate(system.datapaths): acl_cache = L1Cache(size = str(datapath.cacheSize), assoc = datapath.cacheAssoc, replacement_policy = LRUReplacementPolicy(), start_index_bit = block_size_bits, dataAccessLatency = datapath.cacheHitLatency) acli_cache = L1Cache(size = "512B", assoc = 2, replacement_policy = LRUReplacementPolicy(), start_index_bit = block_size_bits, dataAccessLatency = datapath.cacheHitLatency) #l2 cache to satisfy ruby l2_cache = L2Cache(size = "512B", #size = str(datapath.cacheSize), assoc = 2, #assoc = datapath.cacheAssoc, start_index_bit = block_size_bits) assert (not options.is_perfect_cache) #TODO: handle this option acl_cntrl = L1Cache_Controller(version = options.num_cpus+idx+1, L1Dcache = acl_cache, L1Icache = acli_cache, #never used L2cache = l2_cache, no_mig_atomic = not options.allow_atomic_migration, send_evictions = send_evicts(options), transitions_per_cycle = options.ports, ruby_system = ruby_system) acl_seq = RubySequencer(version = options.num_cpus + options.num_sc*2+3+idx, icache = acl_cache, dcache = acl_cache, ruby_system = ruby_system, deadlock_threshold = 2000000) # Connect the L1 controller and the network # Connect the buffers from the controller to network acl_cntrl.requestFromCache = MessageBuffer() acl_cntrl.requestFromCache.master = ruby_system.network.slave acl_cntrl.responseFromCache = MessageBuffer() acl_cntrl.responseFromCache.master = ruby_system.network.slave acl_cntrl.unblockFromCache = MessageBuffer() acl_cntrl.unblockFromCache.master = ruby_system.network.slave # Connect the buffers from the network to the controller acl_cntrl.forwardToCache = MessageBuffer() acl_cntrl.forwardToCache.slave = ruby_system.network.master acl_cntrl.responseToCache = MessageBuffer() acl_cntrl.responseToCache.slave = ruby_system.network.master acl_cntrl.mandatoryQueue = MessageBuffer() acl_cntrl.triggerQueue = MessageBuffer() acl_cntrl.sequencer = acl_seq exec("ruby_system.acl_cntrl%02d = acl_cntrl" % idx) all_sequencers.append(acl_seq) acl_cntrls.append(acl_cntrl) complete_cluster = Cluster(intBW = 32, extBW = 32) complete_cluster.add(gpu_ce_cluster) complete_cluster.add(cpu_cluster) complete_cluster.add(gpu_cluster) for cntrl in dir_cntrls: complete_cluster.add(cntrl) for cntrl in dma_cntrls: complete_cluster.add(cntrl) for cntrl in acl_cntrls: complete_cluster.add(cntrl) for cluster in l2_clusters: complete_cluster.add(cluster) return (all_sequencers, dir_cntrls, complete_cluster)
#!/usr/bin/env python import sys import os import re import glob import shutil import argparse from fractions import * import common log = common.get_log() # Global paths base_path = os.path.dirname(os.path.normpath(sys.argv[0])) tmp_base_path = os.path.join(base_path, "tmp") tmp_path = os.path.join(tmp_base_path, "tmp_gappa_data") cache_path = os.path.join(tmp_base_path, "cache_gappa_data") fptaylor_base = os.path.normpath(os.path.join(base_path, "..")) fptaylor_tmp = os.path.join(tmp_base_path, "tmp_fptaylor") fptaylor_log = os.path.join(tmp_base_path, "log_export_fptaylor") fptaylor = os.path.join(fptaylor_base, "fptaylor") gappa = os.path.expanduser(os.path.normpath("~/Work/tools/gappa-1.3.1/src/gappa")) fpbench_path = os.path.normpath( os.path.join(base_path, "..", "..", "forks", "FPBench", "tools")) core2gappa = os.path.join(fpbench_path, "core2gappa.rkt") racket = "racket" def basename(fname): return os.path.splitext(os.path.basename(fname))[0] # Parse arguments parser = argparse.ArgumentParser( description="Splits input intervals into small pieces and runs Gappa on each subinterval") parser.add_argument('--debug', action='store_true', help="debug mode") parser.add_argument('-e', '--error', choices=['abs', 'rel'], default='abs', help="error type") parser.add_argument('-t', '--type', default='64', choices=['16', '32', '64', 'real'], help="default type of variables and rounding operations") parser.add_argument('-v', '--verbosity', type=int, default=0, help="FPTaylor's verbosity level") parser.add_argument('-o', '--output-path', default=".", help="specifies where to save data files") parser.add_argument('-n', '--segments', type=int, default=100, help="number of subintervals") parser.add_argument('input', help="input FPTaylor file") args = parser.parse_args() if args.debug: log.setLevel(logging.DEBUG) if not os.path.isdir(tmp_path): os.makedirs(tmp_path) if not os.path.isdir(cache_path): os.makedirs(cache_path) common.remove_all(tmp_path, "*") def decode_binary(s): pat = r'([0-9+-]+)(b([0-9+-]+))?' m = re.match(pat, s) v = Fraction(m.group(1)) if m.group(3): p = Fraction(2) ** int(m.group(3)) v *= p return v def get_input_bounds(input_file): pat = r'in[\s]*\[([0-9.e+-]+)[\s]*,[\s]*([0-9.e+-]+)\]' with open(input_file, 'r') as f: data = f.read() m = re.search(pat, data) return float(m.group(1)), float(m.group(2)) class GappaTask: def __init__(self, name): self.input_files = [] self.name = name def __repr__(self): s = "GappaTask({0}): {1}".format(self.name, self.input_files) return s def create_data(self, out_file): pat = r'in[\s]*\[([0-9b+-]+)[\s]*(\{[^}]*\})?,[\s]*([0-9b+-]+)' self.input_files.sort(key=lambda x: x[0]) data = [] log.info("Running Gappa...") total = len(self.input_files) i = 0 for _, input_file in self.input_files: bounds = get_input_bounds(input_file) cmd = [gappa, input_file] output = common.run_output(cmd, silent=True) m = re.search(pat, output) v1 = decode_binary(m.group(1)) v2 = decode_binary(m.group(3)) v = max(abs(v1), abs(v2)) data.append((bounds, v)) i += 1 sys.stdout.write("\r{0}/{1} ".format(i, total)) print("") log.info("done") with open(out_file, 'w') as f: n = len(data) if n != args.segments: log.error("Wrong number of results: {0} (expected {1})".format(n, args.segments)) lo = 1 hi = 2 else: lo = data[0][0][0] hi = data[n - 1][0][1] f.write("[Gappa]{0}\n".format(self.name)) i = 1 for ((low, high), v) in data: if args.error == 'abs': abs_err = float(v) rel_err = 0 else: abs_err = 0 rel_err = float(v) if i == 1: low = lo if i == n: high = hi f.write("{0}, {1}, {2}, {3}, {4}, 0\n".format(i, low, high, abs_err, rel_err)) i += 1 # Export FPTaylor tasks to FPCore out_file = os.path.join(tmp_path, basename(args.input) + ".fpcore") cmd = [fptaylor, args.input, "--fpcore-out", out_file, "--log-base-dir", fptaylor_log, "--log-append-date", "none", "--tmp-base-dir", fptaylor_tmp, "--tmp-date", "false", "-v", str(args.verbosity)] rnd_types = { "16": ("float16", "rnd16", "binary16"), "32": ("float32", "rnd32", "binary32"), "64": ("float64", "rnd64", "binary64"), "real": ("real", "rnd64", "real") } var_type, rnd_type, fpcore_type = rnd_types[args.type] cmd += ["--default-var-type", var_type] cmd += ["--default-rnd", rnd_type] common.run(cmd, log=log) # Run core2gappa.rkt cmd = [racket, core2gappa, "--var-precision", fpcore_type, "--split", str(args.segments)] if args.error == 'rel': cmd += ["--rel-error"] cmd += ["--out-path", tmp_path] common.run(cmd + ["--", out_file], log=log) # Collect files corresponding to each task gappa_tasks = dict() for file_path in glob.glob(os.path.join(tmp_path, "*.g")): pat = r'(.+)\_case([0-9]+)\.g' fname = os.path.basename(file_path) m = re.match(pat, fname) if not m: task_name = os.path.splitext(fname)[0] case = 0 else: task_name = m.group(1) case = int(m.group(2)) if task_name not in gappa_tasks: gappa_tasks[task_name] = GappaTask(task_name) gappa_tasks[task_name].input_files.append((case, file_path)) for task_name, task in gappa_tasks.iteritems(): out_file = os.path.join(args.output_path, "gappa-data-" + task_name + ".txt") task.create_data(out_file)
# Copyright 2015 Open Source Robotics Foundation, Inc. # Copyright 2013 Willow Garage, 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 unittest import parse_cmake.parsing from parse_cmake.parsing import ( File, Command, Comment, BlankLine, Arg, parse, FormattingOptions) def prettify(src): opts = FormattingOptions() opts.indent = ' ' return parse_cmake.parsing.prettify(src, opts) class ParsingTestCase(unittest.TestCase): def setUp(self): self.maxDiff = None def test_parse_empty_raises_exception(self): self.assertEqual(File([]), parse('')) def test_parse_nonempty1(self): input = 'FIND_PACKAGE(ITK REQUIRED)' output = parse(input) expected = File([Command('FIND_PACKAGE', [Arg('ITK'), Arg('REQUIRED')])]) msg = '\nexpected\n%s\ngot\n%s' % (repr(expected), repr(output)) self.assertEqual(expected, output, msg) def test_parse_nonempty2(self): input = '''\ # Top level comment FIND_PACKAGE(ITK REQUIRED) INCLUDE(${ITK_USE_FILE}) ADD_EXECUTABLE(CastImageFilter CastImageFilter.cxx) TARGET_LINK_LIBRARIES(CastImageFilter # inline comment 1 vtkHybrid #inline comment 2 ITKIO ITKBasicFilters ITKCommon ) ''' output = parse(input) expected = File([ Comment('# Top level comment'), Command('FIND_PACKAGE', [Arg('ITK'), Arg('REQUIRED')]), Command('INCLUDE', [Arg('${ITK_USE_FILE}')]), BlankLine(), Command('ADD_EXECUTABLE', [Arg('CastImageFilter'), Arg('CastImageFilter.cxx')]), Command('TARGET_LINK_LIBRARIES', [ Arg('CastImageFilter', comments=['# inline comment 1']), Arg('vtkHybrid', comments=['#inline comment 2']), Arg('ITKIO'), Arg('ITKBasicFilters'), Arg('ITKCommon'), ]) ]) msg = '\nexpected\n%s\ngot\n%s' % (expected, output) self.assertEqual(expected, output, msg) def test_idempotency_of_parsing_and_unparsing(self): input = '''\ # Top level comment FIND_PACKAGE(ITK REQUIRED) INCLUDE(${ITK_USE_FILE}) ''' round_trip = lambda s: str(parse(s)) self.assertEqual(round_trip(input), round_trip(round_trip(input))) def test_invalid_format_raises_an_exception(self): input = 'FIND_PACKAGE(' self.assertRaises(Exception, parse, input) def test_line_numbers_in_exceptions(self): input = '''\ FIND_PACKAGE(ITK) INCLUDE( ''' try: parse(input) self.fail('Expected an exception, but none was raised.') except Exception as e: self.assertTrue('line 2' in str(e)) def test_arg_with_a_slash(self): tree = parse('include_directories (${HELLO_SOURCE_DIR}/Hello)') expected = File([ Command('include_directories', [Arg('${HELLO_SOURCE_DIR}/Hello')]) ]) self.assertEqual(expected, tree) def test_command_with_no_args(self): tree = parse('cmd()') expected = File([Command('cmd', [])]) self.assertEqual(expected, tree) def assertStringEqualIgnoreSpace(self, a, b): a2 = ''.join(a.split()) b2 = ''.join(b.split()) msg = '\nExpected\n%s\ngot\n%s\n(ignoring whitespace details)' % (a, b) self.assertEqual(a2, b2, msg) def test_arg_comments_preserved(self): input = ''' some_command(x # inline comment about x ) ''' self.assertMultiLineEqual(input, prettify(input)) def test_comments_preserved(self): input = '''\ # file comment # more about the file # comment above Command1 command1(VERSION 2.6) # inline comment for Command1 command2(x # inline comment about x "y" # inline comment about a quoted string "y" ) # inline comment for Command2 ''' self.assertMultiLineEqual(input, prettify(input)) def test_multiline_string(self): s = ''' string containing newlines ''' input = '''\ set (MY_STRING "%s") ''' % s tree = parse(input) expected = File([Command('set', [Arg('MY_STRING'), Arg('"' + s + '"')])]) self.assertEqual(expected, tree) # TODO: test macros and functions def test_ifs_indented(self): input = ''' if(a) if(b) set(X 1) endif() elseif(a) if(foo) set(Z 3) endif() else(a) if(c) set(Y 2) endif(c) endif(a) ''' self.assertMultiLineEqual(input, prettify(input)) def test_macros_indented(self): input = ''' macro(hello MESSAGE) message(${MESSAGE}) endmacro(hello) # call the macro with the string "hello world" hello("hello world") ''' self.assertUnchangedByPrettyPrinting(input) def test_functions_indented(self): input = ''' function(hello MESSAGE) message(${MESSAGE}) endfunction(hello) # call the macro with the string "hello world" hello("hello world") ''' self.assertUnchangedByPrettyPrinting(input) def test_loops_indented(self): input = ''' foreach(var ${LIST}) command(var) endforeach() while(cond) command(var) endwhile() ''' self.assertUnchangedByPrettyPrinting(input) def test_breaks_commands_at_parameter_names(self): input = ''' set_source_files_properties(source_file.cpp PROPERTIES COMPILE_FLAGS "-Wsome-error -Wanother-error -fsome-flag") ''' self.assertMultiLineEqual(input, prettify(input)) def assertUnchangedByPrettyPrinting(self, input): self.assertMultiLineEqual(input, prettify(input)) if __name__ == '__main__': unittest.main()
# Copyright 2016 SAS Project 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. from datetime import datetime import json import os import unittest import sas class HeartbeatTestcase(unittest.TestCase): def setUp(self): self._sas, self._sas_admin = sas.GetTestingSas() self._sas_admin.Reset() def tearDown(self): pass def test_10_9_4_1_1_1(self): """Heartbeat request immediately after CBSD moves into Granted State. The response should be SUCCESS. """ # Register the device device_a = json.load( open(os.path.join('testcases', 'testdata', 'device_a.json'))) self._sas_admin.InjectFccId({'fccId': device_a['fccId']}) request = {'registrationRequest': [device_a]} response = self._sas.Registration(request)['registrationResponse'][0] # Check registration response self.assertEqual(response['response']['responseCode'], 0) cbsd_id = response['cbsdId'] del request, response # Request grant grant_0 = json.load( open(os.path.join('testcases', 'testdata', 'grant_0.json'))) grant_0['cbsdId'] = cbsd_id request = {'grantRequest': [grant_0]} # Check grant response response = self._sas.Grant(request)['grantResponse'][0] self.assertEqual(response['cbsdId'], cbsd_id) self.assertTrue(response['grantId']) self.assertEqual(response['response']['responseCode'], 0) grant_id = response['grantId'] del request, response # Heartbeat request = { 'heartbeatRequest': [{ 'cbsdId': cbsd_id, 'grantId': grant_id, 'operationState': 'GRANTED' }] } response = self._sas.Heartbeat(request)['heartbeatResponse'][0] # Check the heartbeat response self.assertEqual(response['cbsdId'], cbsd_id) self.assertEqual(response['grantId'], grant_id) self.assertLess(datetime.utcnow(), datetime.strptime(response['transmitExpireTime'], '%Y-%m-%dT%H:%M:%SZ')) self.assertEqual(response['response']['responseCode'], 0) def test_10_9_4_2_3_1_1(self): """CBSD heartbeat request with missing cbsdId parameter. Heartbeat request immediately after CBSD moves into Granted State. The cbsdId is missing in heartbeat request. The response should be FAIL. """ # Register the device device_a = json.load( open(os.path.join('testcases', 'testdata', 'device_a.json'))) self._sas_admin.InjectFccId({'fccId': device_a['fccId']}) request = {'registrationRequest': [device_a]} response = self._sas.Registration(request)['registrationResponse'][0] # Check registration response self.assertEqual(response['response']['responseCode'], 0) cbsd_id = response['cbsdId'] del request, response # Request grant grant_0 = json.load( open(os.path.join('testcases', 'testdata', 'grant_0.json'))) grant_0['cbsdId'] = cbsd_id request = {'grantRequest': [grant_0]} # Check grant response response = self._sas.Grant(request)['grantResponse'][0] self.assertEqual(response['cbsdId'], cbsd_id) self.assertTrue(response['grantId']) self.assertEqual(response['response']['responseCode'], 0) grant_id = response['grantId'] del request, response # First successful Heartbeat request = { 'heartbeatRequest': [{ 'cbsdId': cbsd_id, 'grantId': grant_id, 'operationState': 'GRANTED' }] } response = self._sas.Heartbeat(request)['heartbeatResponse'][0] # Check the heartbeat response self.assertEqual(response['cbsdId'], cbsd_id) self.assertEqual(response['grantId'], grant_id) self.assertLess(datetime.utcnow(), datetime.strptime(response['transmitExpireTime'], '%Y-%m-%dT%H:%M:%SZ')) self.assertEqual(response['response']['responseCode'], 0) del request, response # cbsdId is missing request = { 'heartbeatRequest': [{ 'grantId': grant_id, 'operationState': 'GRANTED' }] } response = self._sas.Heartbeat(request)['heartbeatResponse'][0] # Check the heartbeat response self.assertEqual(response['response']['responseCode'], 102) def test_10_9_4_2_3_1_2(self): """CBSD heartbeat request with missing grantId parameter. Heartbeat request immediately after CBSD moves into Granted State. The grantId is missing in heartbeat request. The response should be FAIL. """ # Register the device device_a = json.load( open(os.path.join('testcases', 'testdata', 'device_a.json'))) self._sas_admin.InjectFccId({'fccId': device_a['fccId']}) request = {'registrationRequest': [device_a]} response = self._sas.Registration(request)['registrationResponse'][0] # Check registration response self.assertEqual(response['response']['responseCode'], 0) cbsd_id = response['cbsdId'] del request, response # Request grant grant_0 = json.load( open(os.path.join('testcases', 'testdata', 'grant_0.json'))) grant_0['cbsdId'] = cbsd_id request = {'grantRequest': [grant_0]} # Check grant response response = self._sas.Grant(request)['grantResponse'][0] self.assertEqual(response['cbsdId'], cbsd_id) self.assertTrue(response['grantId']) self.assertEqual(response['response']['responseCode'], 0) grant_id = response['grantId'] del request, response # First successful Heartbeat request = { 'heartbeatRequest': [{ 'cbsdId': cbsd_id, 'grantId': grant_id, 'operationState': 'GRANTED' }] } response = self._sas.Heartbeat(request)['heartbeatResponse'][0] # Check the heartbeat response self.assertEqual(response['cbsdId'], cbsd_id) self.assertEqual(response['grantId'], grant_id) self.assertLess(datetime.utcnow(), datetime.strptime(response['transmitExpireTime'], '%Y-%m-%dT%H:%M:%SZ')) self.assertEqual(response['response']['responseCode'], 0) del request, response # grantId is missing request = { 'heartbeatRequest': [{ 'cbsdId': cbsd_id, 'operationState': 'GRANTED' }] } response = self._sas.Heartbeat(request)['heartbeatResponse'][0] # Check the heartbeat response self.assertEqual(response['response']['responseCode'], 102) def test_10_9_4_2_3_1_3(self): """CBSD heartbeat request with missing operationState parameter. Heartbeat request immediately after CBSD moves into Granted State. The operationState is missing in heartbeat request. The response should be FAIL. """ # Register the device device_a = json.load( open(os.path.join('testcases', 'testdata', 'device_a.json'))) self._sas_admin.InjectFccId({'fccId': device_a['fccId']}) request = {'registrationRequest': [device_a]} response = self._sas.Registration(request)['registrationResponse'][0] # Check registration response self.assertEqual(response['response']['responseCode'], 0) cbsd_id = response['cbsdId'] del request, response # Request grant grant_0 = json.load( open(os.path.join('testcases', 'testdata', 'grant_0.json'))) grant_0['cbsdId'] = cbsd_id request = {'grantRequest': [grant_0]} # Check grant response response = self._sas.Grant(request)['grantResponse'][0] self.assertEqual(response['cbsdId'], cbsd_id) self.assertTrue(response['grantId']) self.assertEqual(response['response']['responseCode'], 0) grant_id = response['grantId'] del request, response # First successful Heartbeat request = { 'heartbeatRequest': [{ 'cbsdId': cbsd_id, 'grantId': grant_id, 'operationState': 'GRANTED' }] } response = self._sas.Heartbeat(request)['heartbeatResponse'][0] # Check the heartbeat response self.assertEqual(response['cbsdId'], cbsd_id) self.assertEqual(response['grantId'], grant_id) self.assertLess(datetime.utcnow(), datetime.strptime(response['transmitExpireTime'], '%Y-%m-%dT%H:%M:%SZ')) self.assertEqual(response['response']['responseCode'], 0) del request, response # operationState is missing request = { 'heartbeatRequest': [{ 'cbsdId': cbsd_id, 'grantId': grant_id }] } response = self._sas.Heartbeat(request)['heartbeatResponse'][0] # Check the heartbeat response self.assertEqual(response['response']['responseCode'], 102)
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Order.tax_type' db.add_column('shop_order', 'tax_type', self.gf('django.db.models.fields.CharField')(default='', max_length=50, blank=True), keep_default=False) # Adding field 'Order.tax_total' db.add_column('shop_order', 'tax_total', self.gf('cartridge.shop.fields.MoneyField')(null=True, max_digits=10, decimal_places=2, blank=True), keep_default=False) def backwards(self, orm): # Deleting field 'Order.tax_type' db.delete_column('shop_order', 'tax_type') # Deleting field 'Order.tax_total' db.delete_column('shop_order', 'tax_total') models = { 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'generic.assignedkeyword': { 'Meta': {'ordering': "('_order',)", 'object_name': 'AssignedKeyword'}, '_order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'keyword': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'assignments'", 'to': "orm['generic.Keyword']"}), 'object_pk': ('django.db.models.fields.IntegerField', [], {}) }, 'generic.keyword': { 'Meta': {'object_name': 'Keyword'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}), 'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}) }, 'generic.rating': { 'Meta': {'object_name': 'Rating'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_pk': ('django.db.models.fields.IntegerField', [], {}), 'value': ('django.db.models.fields.IntegerField', [], {}) }, 'pages.page': { 'Meta': {'ordering': "('titles',)", 'object_name': 'Page'}, '_meta_title': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}), '_order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}), 'content_model': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'expiry_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'gen_description': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'in_menus': ('mezzanine.pages.fields.MenusField', [], {'default': '[1, 2, 3]', 'max_length': '100', 'null': 'True', 'blank': 'True'}), 'in_sitemap': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'keywords': ('mezzanine.generic.fields.KeywordsField', [], {'object_id_field': "'object_pk'", 'to': "orm['generic.AssignedKeyword']", 'frozen_by_south': 'True'}), 'keywords_string': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}), 'login_required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['pages.Page']"}), 'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}), 'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}), 'titles': ('django.db.models.fields.CharField', [], {'max_length': '1000', 'null': 'True'}) }, 'shop.cart': { 'Meta': {'object_name': 'Cart'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}) }, 'shop.cartitem': { 'Meta': {'object_name': 'CartItem'}, 'cart': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'items'", 'to': "orm['shop.Cart']"}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'}), 'quantity': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'sku': ('cartridge.shop.fields.SKUField', [], {'max_length': '20'}), 'total_price': ('cartridge.shop.fields.MoneyField', [], {'default': "'0'", 'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'unit_price': ('cartridge.shop.fields.MoneyField', [], {'default': "'0'", 'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'url': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'shop.category': { 'Meta': {'ordering': "('_order',)", 'object_name': 'Category', '_ormbases': ['pages.Page']}, 'combined': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'content': ('mezzanine.core.fields.RichTextField', [], {}), 'featured_image': ('mezzanine.core.fields.FileField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'options': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'product_options'", 'blank': 'True', 'to': "orm['shop.ProductOption']"}), 'page_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['pages.Page']", 'unique': 'True', 'primary_key': 'True'}), 'price_max': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'price_min': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'products': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['shop.Product']", 'symmetrical': 'False', 'blank': 'True'}), 'sale': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['shop.Sale']", 'null': 'True', 'blank': 'True'}) }, 'shop.discountcode': { 'Meta': {'object_name': 'DiscountCode'}, 'active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'categories': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'discountcode_related'", 'blank': 'True', 'to': "orm['shop.Category']"}), 'code': ('cartridge.shop.fields.DiscountCodeField', [], {'unique': 'True', 'max_length': '20'}), 'discount_deduct': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'discount_exact': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'discount_percent': ('cartridge.shop.fields.PercentageField', [], {'null': 'True', 'max_digits': '5', 'decimal_places': '2', 'blank': 'True'}), 'free_shipping': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'min_purchase': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'products': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['shop.Product']", 'symmetrical': 'False', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'uses_remaining': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'valid_from': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'valid_to': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}) }, 'shop.order': { 'Meta': {'ordering': "('-id',)", 'object_name': 'Order'}, 'additional_instructions': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'billing_detail_city': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'billing_detail_country': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'billing_detail_email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'billing_detail_first_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'billing_detail_last_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'billing_detail_phone': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'billing_detail_postcode': ('django.db.models.fields.CharField', [], {'max_length': '10'}), 'billing_detail_state': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'billing_detail_street': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'discount_code': ('cartridge.shop.fields.DiscountCodeField', [], {'max_length': '20', 'blank': 'True'}), 'discount_total': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'item_total': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '40'}), 'shipping_detail_city': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'shipping_detail_country': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'shipping_detail_first_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'shipping_detail_last_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'shipping_detail_phone': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'shipping_detail_postcode': ('django.db.models.fields.CharField', [], {'max_length': '10'}), 'shipping_detail_state': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'shipping_detail_street': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'shipping_total': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'shipping_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '1'}), 'tax_total': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'tax_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), 'time': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}), 'total': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'transaction_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'user_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}) }, 'shop.orderitem': { 'Meta': {'object_name': 'OrderItem'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'order': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'items'", 'to': "orm['shop.Order']"}), 'quantity': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'sku': ('cartridge.shop.fields.SKUField', [], {'max_length': '20'}), 'total_price': ('cartridge.shop.fields.MoneyField', [], {'default': "'0'", 'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'unit_price': ('cartridge.shop.fields.MoneyField', [], {'default': "'0'", 'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}) }, 'shop.product': { 'Meta': {'object_name': 'Product'}, '_meta_title': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}), 'available': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'categories': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['shop.Category']", 'symmetrical': 'False', 'blank': 'True'}), 'content': ('mezzanine.core.fields.RichTextField', [], {}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'expiry_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'gen_description': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'in_sitemap': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'keywords': ('mezzanine.generic.fields.KeywordsField', [], {'object_id_field': "'object_pk'", 'to': "orm['generic.AssignedKeyword']", 'frozen_by_south': 'True'}), 'keywords_string': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}), 'num_in_stock': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'rating': ('mezzanine.generic.fields.RatingField', [], {'object_id_field': "'object_pk'", 'to': "orm['generic.Rating']", 'frozen_by_south': 'True'}), 'rating_average': ('django.db.models.fields.FloatField', [], {'default': '0'}), 'rating_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'related_products': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'related_products_rel_+'", 'blank': 'True', 'to': "orm['shop.Product']"}), 'sale_from': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'sale_id': ('django.db.models.fields.IntegerField', [], {'null': 'True'}), 'sale_price': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'sale_to': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}), 'sku': ('cartridge.shop.fields.SKUField', [], {'max_length': '20', 'unique': 'True', 'null': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}), 'unit_price': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'upsell_products': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'upsell_products_rel_+'", 'blank': 'True', 'to': "orm['shop.Product']"}) }, 'shop.productaction': { 'Meta': {'unique_together': "(('product', 'timestamp'),)", 'object_name': 'ProductAction'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'product': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'actions'", 'to': "orm['shop.Product']"}), 'timestamp': ('django.db.models.fields.IntegerField', [], {}), 'total_cart': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'total_purchase': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'shop.productimage': { 'Meta': {'ordering': "('_order',)", 'object_name': 'ProductImage'}, '_order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'file': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'product': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'images'", 'to': "orm['shop.Product']"}) }, 'shop.productoption': { 'Meta': {'object_name': 'ProductOption'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('cartridge.shop.fields.OptionField', [], {'max_length': '50', 'null': 'True'}), 'type': ('django.db.models.fields.IntegerField', [], {}) }, 'shop.productvariation': { 'Meta': {'ordering': "('-default',)", 'object_name': 'ProductVariation'}, 'default': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['shop.ProductImage']", 'null': 'True', 'blank': 'True'}), 'num_in_stock': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'option1': ('cartridge.shop.fields.OptionField', [], {'max_length': '50', 'null': 'True'}), 'option2': ('cartridge.shop.fields.OptionField', [], {'max_length': '50', 'null': 'True'}), 'product': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'variations'", 'to': "orm['shop.Product']"}), 'sale_from': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'sale_id': ('django.db.models.fields.IntegerField', [], {'null': 'True'}), 'sale_price': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'sale_to': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'sku': ('cartridge.shop.fields.SKUField', [], {'max_length': '20', 'unique': 'True', 'null': 'True', 'blank': 'True'}), 'unit_price': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}) }, 'shop.sale': { 'Meta': {'object_name': 'Sale'}, 'active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'categories': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'sale_related'", 'blank': 'True', 'to': "orm['shop.Category']"}), 'discount_deduct': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'discount_exact': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'discount_percent': ('cartridge.shop.fields.PercentageField', [], {'null': 'True', 'max_digits': '5', 'decimal_places': '2', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'products': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['shop.Product']", 'symmetrical': 'False', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'valid_from': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'valid_to': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}) }, 'sites.site': { 'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"}, 'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) } } complete_apps = ['shop']
# Copyright 2014 # The 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. import copy try: from neutronclient.common import exceptions as neutron_exception except ImportError: pass # clients will log absense of neutronclient in this case from oslo_config import cfg from oslo_log import log as logging from ec2api.api import common from ec2api.api import ec2utils from ec2api.api import validator from ec2api import clients from ec2api.db import api as db_api from ec2api import exception from ec2api.i18n import _ CONF = cfg.CONF LOG = logging.getLogger(__name__) """Security Groups related API implementation """ Validator = common.Validator SECURITY_GROUP_MAP = {'domain-name-servers': 'dns-servers', 'domain-name': 'domain-name', 'ntp-servers': 'ntp-server', 'netbios-name-servers': 'netbios-ns', 'netbios-node-type': 'netbios-nodetype'} DEFAULT_GROUP_NAME = 'default' def get_security_group_engine(): return SecurityGroupEngineNeutron() def create_security_group(context, group_name, group_description, vpc_id=None): if group_name == DEFAULT_GROUP_NAME: if vpc_id: raise exception.InvalidParameterValue( _('Cannot use reserved security group name: %s') % DEFAULT_GROUP_NAME) else: raise exception.InvalidGroupReserved(group_name=group_name) filter = [{'name': 'group-name', 'value': [group_name]}] if not vpc_id and CONF.disable_ec2_classic: vpc_id = ec2utils.get_default_vpc(context)['id'] if vpc_id and group_name != vpc_id: filter.append({'name': 'vpc-id', 'value': [vpc_id]}) security_groups = describe_security_groups( context, filter=filter)['securityGroupInfo'] if not vpc_id: # TODO(andrey-mp): remove it when fitering by None will be implemented security_groups = [sg for sg in security_groups if sg.get('vpcId') is None] if security_groups: raise exception.InvalidGroupDuplicate(name=group_name) return _create_security_group(context, group_name, group_description, vpc_id) def _create_security_group(context, group_name, group_description, vpc_id=None, default=False): neutron = clients.neutron(context) with common.OnCrashCleaner() as cleaner: try: secgroup_body = ( {'security_group': {'name': group_name, 'description': group_description}}) os_security_group = neutron.create_security_group( secgroup_body)['security_group'] except neutron_exception.OverQuotaClient: raise exception.ResourceLimitExceeded(resource='security groups') cleaner.addCleanup(neutron.delete_security_group, os_security_group['id']) if vpc_id: # NOTE(Alex) Check if such vpc exists ec2utils.get_db_item(context, vpc_id) item = {'vpc_id': vpc_id, 'os_id': os_security_group['id']} if not default: security_group = db_api.add_item(context, 'sg', item) else: item['id'] = ec2utils.change_ec2_id_kind(vpc_id, 'sg') # NOTE(andrey-mp): try to add item with specific id # and catch exception if it exists security_group = db_api.restore_item(context, 'sg', item) return {'return': 'true', 'groupId': security_group['id']} def _create_default_security_group(context, vpc): # NOTE(Alex): OpenStack doesn't allow creation of another group # named 'default' hence vpc-id is used. try: sg_id = _create_security_group(context, vpc['id'], 'Default VPC security group', vpc['id'], default=True)['groupId'] except (exception.EC2DBDuplicateEntry, exception.InvalidVpcIDNotFound): # NOTE(andrey-mp): when this thread tries to recreate default group # but another thread tries to delete vpc we should pass vpc not found LOG.exception('Failed to create default security group.') return None return sg_id def delete_security_group(context, group_name=None, group_id=None, delete_default=False): if group_name is None and group_id is None: raise exception.MissingParameter(param='group id or name') security_group_engine.delete_group(context, group_name, group_id, delete_default) return True class SecurityGroupDescriber(common.TaggableItemsDescriber): KIND = 'sg' FILTER_MAP = {'description': 'groupDescription', 'group-id': 'groupId', 'group-name': 'groupName', 'ip-permission.cidr': ['ipPermissions', ['ipRanges', 'cidrIp']], 'ip-permission.from-port': ['ipPermissions', 'fromPort'], 'ip-permission.group-id': ['ipPermissions', ['groups', 'groupId']], 'ip-permission.group-name': ['ipPermissions', ['groups', 'groupName']], 'ip-permission.protocol': ['ipPermissions', 'ipProtocol'], 'ip-permission.to-port': ['ipPermissions', 'toPort'], 'ip-permission.user-id': ['ipPermissions', ['groups', 'userId']], 'owner-id': 'ownerId', 'vpc-id': 'vpcId', } def __init__(self, default_vpc_id): super(SecurityGroupDescriber, self).__init__() self.all_db_items = None self.default_vpc_id = default_vpc_id def format(self, item=None, os_item=None): return _format_security_group(item, os_item, self.all_db_items, self.os_items) def get_os_items(self): if self.all_db_items is None: self.all_db_items = db_api.get_items(self.context, 'sg') os_groups = security_group_engine.get_os_groups(self.context) if self.check_and_repair_default_groups(os_groups, self.all_db_items): self.all_db_items = db_api.get_items(self.context, 'sg') self.items = self.get_db_items() os_groups = security_group_engine.get_os_groups(self.context) for os_group in os_groups: os_group['name'] = _translate_group_name(self.context, os_group, self.all_db_items) return os_groups def check_and_repair_default_groups(self, os_groups, db_groups): vpcs = ec2utils.get_db_items(self.context, 'vpc', None) os_groups_dict = {g['name']: g['id'] for g in os_groups} db_groups_dict = {g['os_id']: g['vpc_id'] for g in db_groups} had_to_repair = False for vpc in vpcs: os_group = os_groups_dict.get(vpc['id']) if os_group: db_group = db_groups_dict.get(os_group) if db_group and db_group == vpc['id']: continue result = _create_default_security_group(self.context, vpc) if result: had_to_repair = True return had_to_repair def is_selected_item(self, context, os_item_name, item): if item and item['id'] in self.ids: return True if os_item_name in self.names: if not CONF.disable_ec2_classic: return (not item or not item['vpc_id']) else: return (self.default_vpc_id and item and item['vpc_id'] == self.default_vpc_id) return False def describe_security_groups(context, group_name=None, group_id=None, filter=None): default_vpc_id = None default_vpc = ec2utils.check_and_create_default_vpc(context) if default_vpc: default_vpc_id = default_vpc['id'] formatted_security_groups = SecurityGroupDescriber( default_vpc_id).describe(context, group_id, group_name, filter) return {'securityGroupInfo': formatted_security_groups} # TODO(Alex) cidr/ports/protocol/source_group should be possible # to pass in root set of parameters, not in ip_permissions as now only # supported, for authorize and revoke functions. # The new parameters appeared only in the very recent version of AWS doc. # API version 2014-06-15 didn't claim support of it. def authorize_security_group_ingress(context, group_id=None, group_name=None, ip_permissions=None): if group_name and not group_id and CONF.disable_ec2_classic: sg = describe_security_groups( context, group_name=[group_name])['securityGroupInfo'][0] group_id = sg['groupId'] group_name = None return _authorize_security_group(context, group_id, group_name, ip_permissions, 'ingress') def authorize_security_group_egress(context, group_id, ip_permissions=None): security_group = ec2utils.get_db_item(context, group_id) if not security_group.get('vpc_id'): raise exception.InvalidParameterValue(message=_('Only Amazon VPC ' 'security groups may be used with this operation.')) return _authorize_security_group(context, group_id, None, ip_permissions, 'egress') def _authorize_security_group(context, group_id, group_name, ip_permissions, direction): rules_bodies = _build_rules(context, group_id, group_name, ip_permissions, direction) for rule_body in rules_bodies: security_group_engine.authorize_security_group(context, rule_body) return True def _validate_parameters(protocol, from_port, to_port): if (not isinstance(protocol, int) and protocol not in ['tcp', 'udp', 'icmp']): raise exception.InvalidParameterValue( _('Invalid value for IP protocol. Unknown protocol.')) if (not isinstance(from_port, int) or not isinstance(to_port, int)): raise exception.InvalidParameterValue( _('Integer values should be specified for ports')) if protocol in ['tcp', 'udp', 6, 17]: if from_port == -1 or to_port == -1: raise exception.InvalidParameterValue( _('Must specify both from and to ports with TCP/UDP.')) if from_port > to_port: raise exception.InvalidParameterValue( _('Invalid TCP/UDP port range.')) if from_port < 0 or from_port > 65535: raise exception.InvalidParameterValue( _('TCP/UDP from port is out of range.')) if to_port < 0 or to_port > 65535: raise exception.InvalidParameterValue( _('TCP/UDP to port is out of range.')) elif protocol in ['icmp', 1]: if from_port < -1 or from_port > 255: raise exception.InvalidParameterValue( _('ICMP type is out of range.')) if to_port < -1 or to_port > 255: raise exception.InvalidParameterValue( _('ICMP code is out of range.')) def _build_rules(context, group_id, group_name, ip_permissions, direction): if group_name is None and group_id is None: raise exception.MissingParameter(param='group id or name') if ip_permissions is None: raise exception.MissingParameter(param='source group or cidr') os_security_group_id = security_group_engine.get_group_os_id(context, group_id, group_name) os_security_group_rule_bodies = [] if ip_permissions is None: ip_permissions = [] for rule in ip_permissions: os_security_group_rule_body = ( {'security_group_id': os_security_group_id, 'direction': direction, 'ethertype': 'IPv4'}) protocol = rule.get('ip_protocol', -1) from_port = rule.get('from_port', -1) to_port = rule.get('to_port', -1) _validate_parameters(protocol, from_port, to_port) if protocol != -1: os_security_group_rule_body['protocol'] = rule['ip_protocol'] if from_port != -1: os_security_group_rule_body['port_range_min'] = rule['from_port'] if to_port != -1: os_security_group_rule_body['port_range_max'] = rule['to_port'] # NOTE(Dmitry_Eremeev): Neutron behaviour changed. # If rule with full port range is created (1 - 65535), then Neutron # creates rule without ports specified. # If a rule with full port range must be deleted, then Neutron cannot # find a rule with this range in order to delete it, but it can find # a rule which has not ports in its properties. if ((from_port == 1) and (to_port in [255, 65535])): for item in ['port_range_min', 'port_range_max']: del os_security_group_rule_body[item] # TODO(Alex) AWS protocol claims support of multiple groups and cidrs, # however, neutron doesn't support it at the moment. # It's possible in the future to convert list values incoming from # REST API into several neutron rules and squeeze them back into one # for describing. # For now only 1 value is supported for either. if rule.get('groups'): os_security_group_rule_body['remote_group_id'] = ( security_group_engine.get_group_os_id( context, rule['groups'][0].get('group_id'), rule['groups'][0].get('group_name'))) elif rule.get('ip_ranges'): os_security_group_rule_body['remote_ip_prefix'] = ( rule['ip_ranges'][0]['cidr_ip']) validator.validate_cidr_with_ipv6( os_security_group_rule_body['remote_ip_prefix'], 'cidr_ip') else: raise exception.MissingParameter(param='source group or cidr') os_security_group_rule_bodies.append(os_security_group_rule_body) return os_security_group_rule_bodies def revoke_security_group_ingress(context, group_id=None, group_name=None, ip_permissions=None): return _revoke_security_group(context, group_id, group_name, ip_permissions, 'ingress') def revoke_security_group_egress(context, group_id, ip_permissions=None): security_group = ec2utils.get_db_item(context, group_id) if not security_group.get('vpc_id'): raise exception.InvalidParameterValue(message=_('Only Amazon VPC ' 'security groups may be used with this operation.')) return _revoke_security_group(context, group_id, None, ip_permissions, 'egress') def _are_identical_rules(rule1, rule2): def significant_values(rule): dict = {} for key, value in rule.items(): if (value is not None and value != -1 and value != '0.0.0.0/0' and key not in ['id', 'tenant_id', 'security_group_id', 'tags', 'description', 'revision', 'revision_number', 'created_at', 'updated_at', 'project_id']): dict[key] = str(value) return dict r1 = significant_values(rule1) r2 = significant_values(rule2) return r1 == r2 def _revoke_security_group(context, group_id, group_name, ip_permissions, direction): rules_bodies = _build_rules(context, group_id, group_name, ip_permissions, direction) if not rules_bodies: return True os_rules = security_group_engine.get_os_group_rules( context, rules_bodies[0]['security_group_id']) os_rules_to_delete = [] for rule_body in rules_bodies: for os_rule in os_rules: if _are_identical_rules(rule_body, os_rule): os_rules_to_delete.append(os_rule['id']) if len(os_rules_to_delete) != len(rules_bodies): security_group = ec2utils.get_db_item(context, group_id) if security_group.get('vpc_id'): raise exception.InvalidPermissionNotFound() return True for os_rule_id in os_rules_to_delete: security_group_engine.delete_os_group_rule(context, os_rule_id) return True def _translate_group_name(context, os_group, db_groups): # NOTE(Alex): This function translates VPC default group names # from vpc id 'vpc-xxxxxxxx' format to 'default'. It's supposed # to be called right after getting security groups from OpenStack # in order to avoid problems with incoming 'default' name value # in all of the subsequent handling (filtering, using in parameters...) if os_group['name'].startswith('vpc-') and db_groups: db_group = next((g for g in db_groups if g['os_id'] == os_group['id']), None) if db_group and db_group.get('vpc_id'): return DEFAULT_GROUP_NAME return os_group['name'] def _format_security_groups_ids_names(context): neutron = clients.neutron(context) os_security_groups = neutron.list_security_groups( tenant_id=context.project_id)['security_groups'] security_groups = db_api.get_items(context, 'sg') ec2_security_groups = {} for os_security_group in os_security_groups: security_group = next((g for g in security_groups if g['os_id'] == os_security_group['id']), None) if security_group is None: continue ec2_security_groups[os_security_group['id']] = ( {'groupId': security_group['id'], 'groupName': _translate_group_name(context, os_security_group, security_groups)}) return ec2_security_groups def _format_security_group(security_group, os_security_group, security_groups, os_security_groups): ec2_security_group = {} ec2_security_group['groupId'] = security_group['id'] if security_group.get('vpc_id'): ec2_security_group['vpcId'] = security_group['vpc_id'] ec2_security_group['ownerId'] = os_security_group['tenant_id'] ec2_security_group['groupName'] = os_security_group['name'] ec2_security_group['groupDescription'] = os_security_group['description'] ingress_permissions = [] egress_permissions = [] for os_rule in os_security_group.get('security_group_rules', []): # NOTE(Alex) We're skipping IPv6 rules because AWS doesn't support # them. if os_rule.get('ethertype', 'IPv4') == 'IPv6': continue # NOTE(Dmitry_Eremeev): Neutron behaviour changed. # If rule with full port range (except icmp protocol) is created # (1 - 65535), then Neutron creates rule without ports specified. # Ports passed for rule creation don't match ports in created rule. # That's why default values were changed to match full port # range (1 - 65535) if os_rule.get('protocol') in ["icmp", 1]: min_port = max_port = -1 else: min_port = 1 max_port = 65535 ec2_rule = {'ipProtocol': -1 if os_rule['protocol'] is None else os_rule['protocol'], 'fromPort': min_port if os_rule['port_range_min'] is None else os_rule['port_range_min'], 'toPort': max_port if os_rule['port_range_max'] is None else os_rule['port_range_max']} remote_group_id = os_rule['remote_group_id'] if remote_group_id is not None: ec2_remote_group = {} db_remote_group = next((g for g in security_groups if g['os_id'] == remote_group_id), None) if db_remote_group is not None: ec2_remote_group['groupId'] = db_remote_group['id'] else: # TODO(Alex) Log absence of remote_group pass os_remote_group = next((g for g in os_security_groups if g['id'] == remote_group_id), None) if os_remote_group is not None: ec2_remote_group['groupName'] = os_remote_group['name'] ec2_remote_group['userId'] = os_remote_group['tenant_id'] else: # TODO(Alex) Log absence of remote_group pass ec2_rule['groups'] = [ec2_remote_group] elif os_rule['remote_ip_prefix'] is not None: ec2_rule['ipRanges'] = [{'cidrIp': os_rule['remote_ip_prefix']}] if os_rule.get('direction') == 'egress': egress_permissions.append(ec2_rule) else: if security_group is None and os_rule['protocol'] is None: for protocol, min_port, max_port in (('icmp', -1, -1), ('tcp', 1, 65535), ('udp', 1, 65535)): ec2_rule['ipProtocol'] = protocol ec2_rule['fromPort'] = min_port ec2_rule['toPort'] = max_port ingress_permissions.append(copy.deepcopy(ec2_rule)) else: ingress_permissions.append(ec2_rule) ec2_security_group['ipPermissions'] = ingress_permissions ec2_security_group['ipPermissionsEgress'] = egress_permissions return ec2_security_group class SecurityGroupEngineNeutron(object): def delete_group(self, context, group_name=None, group_id=None, delete_default=False): neutron = clients.neutron(context) if group_name: sg = describe_security_groups( context, group_name=[group_name])['securityGroupInfo'][0] group_id = sg['groupId'] group_name = None security_group = ec2utils.get_db_item(context, group_id) try: if not delete_default: os_security_group = neutron.show_security_group( security_group['os_id']) if (os_security_group and os_security_group['security_group']['name'] == security_group['vpc_id']): raise exception.CannotDelete() neutron.delete_security_group(security_group['os_id']) except neutron_exception.Conflict as ex: # TODO(Alex): Instance ID is unknown here, report exception message # in its place - looks readable. raise exception.DependencyViolation( obj1_id=group_id, obj2_id=ex.message) except neutron_exception.NeutronClientException as ex: # TODO(Alex): do log error # TODO(Alex): adjust caught exception classes to catch: # the port doesn't exist pass db_api.delete_item(context, group_id) def get_os_groups(self, context): neutron = clients.neutron(context) return neutron.list_security_groups( tenant_id=context.project_id)['security_groups'] def authorize_security_group(self, context, rule_body): neutron = clients.neutron(context) try: os_security_group_rule = neutron.create_security_group_rule( {'security_group_rule': rule_body})['security_group_rule'] except neutron_exception.OverQuotaClient: raise exception.RulesPerSecurityGroupLimitExceeded() except neutron_exception.Conflict as ex: raise exception.InvalidPermissionDuplicate() def get_os_group_rules(self, context, os_id): neutron = clients.neutron(context) os_security_group = ( neutron.show_security_group(os_id)['security_group']) return os_security_group.get('security_group_rules') def delete_os_group_rule(self, context, os_id): neutron = clients.neutron(context) neutron.delete_security_group_rule(os_id) def get_group_os_id(self, context, group_id, group_name): if group_name and not group_id: os_group = self.get_os_group_by_name(context, group_name) return str(os_group['id']) return ec2utils.get_db_item(context, group_id, 'sg')['os_id'] def get_os_group_by_name(self, context, group_name, os_security_groups=None): if os_security_groups is None: neutron = clients.neutron(context) os_security_groups = ( neutron.list_security_groups()['security_groups']) os_group = next((g for g in os_security_groups if g['name'] == group_name), None) if os_group is None: raise exception.InvalidGroupNotFound(id=group_name) return os_group security_group_engine = get_security_group_engine()
# Copyright 2014 Open Source Robotics Foundation, 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 __future__ import print_function import argparse import os import sys import time try: from catkin_pkg.packages import find_packages from catkin_pkg.topological_order import topological_order_packages except ImportError as e: sys.exit( 'ImportError: "from catkin_pkg.topological_order import ' 'topological_order" failed: %s\nMake sure that you have installed ' '"catkin_pkg", and that it is up to date and on the PYTHONPATH.' % e ) from catkin_pkg.package import InvalidPackage from catkin_tools.argument_parsing import add_context_args from catkin_tools.argument_parsing import add_cmake_and_make_and_catkin_make_args from catkin_tools.argument_parsing import configure_make_args from catkin_tools.common import getcwd from catkin_tools.common import is_tty from catkin_tools.common import log from catkin_tools.common import find_enclosing_package from catkin_tools.context import Context from catkin_tools.execution.jobs import JobServer from catkin_tools.jobs.job import get_build_type from catkin_tools.metadata import find_enclosing_workspace from catkin_tools.metadata import get_metadata from catkin_tools.metadata import update_metadata from catkin_tools.resultspace import load_resultspace_environment from catkin_tools.terminal_color import set_color from .color import clr from .build import build_isolated_workspace from .build import determine_packages_to_be_built from .build import topological_order_packages from .build import verify_start_with_option # # Begin Hack # # TODO(wjwwood): remove this, once it is no longer needed. # argparse may not support mutually exclusive groups inside other groups, see: # http://bugs.python.org/issue10680 # Backup the original constructor backup__ArgumentGroup___init__ = argparse._ArgumentGroup.__init__ # Make a new constructor with the fix def fixed__ArgumentGroup___init__(self, container, title=None, description=None, **kwargs): backup__ArgumentGroup___init__(self, container, title, description, **kwargs) # Make sure this line is run, maybe redundant on versions which already have it self._mutually_exclusive_groups = container._mutually_exclusive_groups # Monkey patch in the fixed constructor argparse._ArgumentGroup.__init__ = fixed__ArgumentGroup___init__ # # End Hack # def prepare_arguments(parser): parser.description = """\ Build one or more packages in a catkin workspace. This invokes `CMake`, `make`, and optionally `make install` for either all or the specified packages in a catkin workspace. Arguments passed to this verb can temporarily override persistent options stored in the catkin profile config. If you want to save these options, use the --save-config argument. To see the current config, use the `catkin config` command.\ """ # Workspace / profile args add_context_args(parser) # Sub-commands add = parser.add_argument add('--dry-run', '-n', action='store_true', default=False, help='List the packages which will be built with the given arguments without building them.') # What packages to build pkg_group = parser.add_argument_group('Packages', 'Control which packages get built.') add = pkg_group.add_argument add('packages', metavar='PKGNAME', nargs='*', help='Workspace packages to build, package dependencies are built as well unless --no-deps is used. ' 'If no packages are given, then all the packages are built.') add('--this', dest='build_this', action='store_true', default=False, help='Build the package containing the current working directory.') add('--no-deps', action='store_true', default=False, help='Only build specified packages, not their dependencies.') add('--unbuilt', action='store_true', default=False, help='Build packages which have yet to be built.') start_with_group = pkg_group.add_mutually_exclusive_group() add = start_with_group.add_argument add('--start-with', metavar='PKGNAME', type=str, help='Build a given package and those which depend on it, skipping any before it.') add('--start-with-this', action='store_true', default=False, help='Similar to --start-with, starting with the package containing the current directory.') add = pkg_group.add_argument add('--continue-on-failure', '-c', action='store_true', default=False, help='Try to continue building packages whose dependencies built successfully even if some other requested ' 'packages fail to build.') # Build options build_group = parser.add_argument_group('Build', 'Control the build behavior.') add = build_group.add_argument add('--force-cmake', action='store_true', default=None, help='Runs cmake explicitly for each catkin package.') add('--pre-clean', action='store_true', default=None, help='Runs `make clean` before building each package.') add('--no-install-lock', action='store_true', default=None, help='Prevents serialization of the install steps, which is on by default to prevent file install collisions') config_group = parser.add_argument_group('Config', 'Parameters for the underlying build system.') add = config_group.add_argument add('--save-config', action='store_true', default=False, help='Save any configuration options in this section for the next build invocation.') add_cmake_and_make_and_catkin_make_args(config_group) # Behavior behavior_group = parser.add_argument_group('Interface', 'The behavior of the command-line interface.') add = behavior_group.add_argument add('--verbose', '-v', action='store_true', default=False, help='Print output from commands in ordered blocks once the command finishes.') add('--interleave-output', '-i', action='store_true', default=False, help='Prevents ordering of command output when multiple commands are running at the same time.') add('--no-status', action='store_true', default=False, help='Suppresses status line, useful in situations where carriage return is not properly supported.') add('--summarize', '--summary', '-s', action='store_true', default=None, help='Adds a build summary to the end of a build; defaults to on with --continue-on-failure, off otherwise') add('--no-summarize', '--no-summary', action='store_false', dest='summarize', help='explicitly disable the end of build summary') # Deprecated args now handled by main catkin command add('--no-color', action='store_true', help=argparse.SUPPRESS) add('--force-color', action='store_true', help=argparse.SUPPRESS) # Experimental args add('--mem-limit', default=None, help=argparse.SUPPRESS) def status_rate_type(rate): rate = float(rate) if rate < 0: raise argparse.ArgumentTypeError("must be greater than or equal to zero.") return rate add('--limit-status-rate', '--status-rate', type=status_rate_type, default=0.0, help='Limit the update rate of the status bar to this frequency. Zero means unlimited. ' 'Must be positive, default is 0.') add('--no-notify', action='store_true', default=False, help='Suppresses system pop-up notification.') return parser def dry_run(context, packages, no_deps, start_with): # Print Summary log(context.summary()) # Get all the packages in the context source space # Suppress warnings since this is a utility function workspace_packages = find_packages(context.source_space_abs, exclude_subspaces=True, warnings=[]) # Find list of packages in the workspace packages_to_be_built, packages_to_be_built_deps, all_packages = determine_packages_to_be_built( packages, context, workspace_packages) # Assert start_with package is in the workspace verify_start_with_option(start_with, packages, all_packages, packages_to_be_built + packages_to_be_built_deps) if not no_deps: # Extend packages to be built to include their deps packages_to_be_built.extend(packages_to_be_built_deps) # Also resort packages_to_be_built = topological_order_packages(dict(packages_to_be_built)) # Print packages log("Packages to be built:") max_name_len = str(max([len(pkg.name) for pth, pkg in packages_to_be_built])) prefix = clr('@{pf}' + ('------ ' if start_with else '- ') + '@|') for pkg_path, pkg in packages_to_be_built: build_type = get_build_type(pkg) if build_type == 'catkin' and 'metapackage' in [e.tagname for e in pkg.exports]: build_type = 'metapackage' if start_with and pkg.name == start_with: start_with = None log(clr("{prefix}@{cf}{name:<" + max_name_len + "}@| (@{yf}{build_type}@|)") .format(prefix=clr('@!@{kf}(skip)@| ') if start_with else prefix, name=pkg.name, build_type=build_type)) log("Total packages: " + str(len(packages_to_be_built))) def main(opts): # Set color options if (opts.force_color or is_tty(sys.stdout)) and not opts.no_color: set_color(True) else: set_color(False) # Context-aware args if opts.build_this or opts.start_with_this: # Determine the enclosing package try: ws_path = find_enclosing_workspace(getcwd()) # Suppress warnings since this won't necessaraly find all packages # in the workspace (it stops when it finds one package), and # relying on it for warnings could mislead people. this_package = find_enclosing_package( search_start_path=getcwd(), ws_path=ws_path, warnings=[]) except (InvalidPackage, RuntimeError): this_package = None # Handle context-based package building if opts.build_this: if this_package: opts.packages += [this_package] else: sys.exit( "[build] Error: In order to use --this, the current directory must be part of a catkin package.") # If --start--with was used without any packages and --this was specified, start with this package if opts.start_with_this: if this_package: opts.start_with = this_package else: sys.exit( "[build] Error: In order to use --this, the current directory must be part of a catkin package.") if opts.no_deps and not opts.packages and not opts.unbuilt: sys.exit(clr("[build] @!@{rf}Error:@| With --no-deps, you must specify packages to build.")) # Load the context ctx = Context.load(opts.workspace, opts.profile, opts, append=True) # Initialize the build configuration make_args, makeflags, cli_flags, jobserver = configure_make_args(ctx.make_args, ctx.use_internal_make_jobserver) # Set the jobserver memory limit if jobserver and opts.mem_limit: log(clr("@!@{pf}EXPERIMENTAL: limit memory to '%s'@|" % str(opts.mem_limit))) # At this point psuitl will be required, check for it and bail out if not set try: import psutil # noqa except ImportError as exc: log("Could not import psutil, but psutil is required when using --mem-limit.") log("Please either install psutil or avoid using --mem-limit.") sys.exit("Exception: {0}".format(exc)) JobServer.set_max_mem(opts.mem_limit) ctx.make_args = make_args # Load the environment of the workspace to extend if ctx.extend_path is not None: try: load_resultspace_environment(ctx.extend_path) except IOError as exc: log(clr("[build] @!@{rf}Error:@| Unable to extend workspace from \"%s\": %s" % (ctx.extend_path, exc.message))) return 1 # Display list and leave the file system untouched if opts.dry_run: # TODO: Add unbuilt dry_run(ctx, opts.packages, opts.no_deps, opts.start_with) return # Check if the context is valid before writing any metadata if not ctx.source_space_exists(): print(clr("[build] @!@{rf}Error:@| Unable to find source space `%s`") % ctx.source_space_abs) return 1 # Always save the last context under the build verb update_metadata(ctx.workspace, ctx.profile, 'build', ctx.get_stored_dict()) build_metadata = get_metadata(ctx.workspace, ctx.profile, 'build') if build_metadata.get('needs_force', False): opts.force_cmake = True update_metadata(ctx.workspace, ctx.profile, 'build', {'needs_force': False}) # Save the context as the configuration if opts.save_config: Context.save(ctx) start = time.time() # Get parallel toplevel jobs try: parallel_jobs = int(opts.parallel_jobs) except TypeError: parallel_jobs = None # Set VERBOSE environment variable if opts.verbose: os.environ['VERBOSE'] = '1' return build_isolated_workspace( ctx, packages=opts.packages, start_with=opts.start_with, no_deps=opts.no_deps, unbuilt=opts.unbuilt, n_jobs=parallel_jobs, force_cmake=opts.force_cmake, pre_clean=opts.pre_clean, force_color=opts.force_color, quiet=not opts.verbose, interleave_output=opts.interleave_output, no_status=opts.no_status, limit_status_rate=opts.limit_status_rate, lock_install=not opts.no_install_lock, no_notify=opts.no_notify, continue_on_failure=opts.continue_on_failure, summarize_build=opts.summarize # Can be True, False, or None )
""" Odnoklassniki.ru OAuth2 and IFRAME application support If you are using OAuth2 authentication, * Take a look to: http://dev.odnoklassniki.ru/wiki/display/ok/The+OAuth+2.0+Protocol * You need to register OAuth application here: http://dev.odnoklassniki.ru/wiki/pages/viewpage.action?pageId=13992188 elif you're building iframe application, * Take a look to: http://dev.odnoklassniki.ru/wiki/display/ok/ Odnoklassniki.ru+Third+Party+Platform * You need to register your iframe application here: http://dev.odnoklassniki.ru/wiki/pages/viewpage.action?pageId=5668937 * You need to sign a public offer and do some bureaucracy if you want to be listed in application registry Then setup your application according manual and use information from registration mail to set settings values. """ from urllib import urlencode, unquote from urllib2 import Request from hashlib import md5 try: import json as simplejson except ImportError: try: import simplejson except ImportError: from django.utils import simplejson from django import forms from django.contrib.auth import authenticate from social_auth.backends import OAuthBackend, BaseOAuth2, BaseAuth, \ SocialAuthBackend from social_auth.exceptions import AuthFailed from social_auth.utils import log, dsa_urlopen, backend_setting ODNOKLASSNIKI_API_SERVER = 'http://api.odnoklassniki.ru/' class OdnoklassnikiBackend(OAuthBackend): '''Odnoklassniki authentication backend''' name = 'odnoklassniki' EXTRA_DATA = [('refresh_token', 'refresh_token'), ('expires_in', 'expires')] def get_user_id(self, details, response): '''Return user unique id provided by Odnoklassniki''' return response['uid'] def get_user_details(self, response): '''Return user details from Odnoklassniki request''' return { 'username': response['uid'], 'email': '', 'fullname': unquote(response['name']), 'first_name': unquote(response['first_name']), 'last_name': unquote(response['last_name']) } class OdnoklassnikiMixin(object): def get_settings(self): client_key = backend_setting(self, self.SETTINGS_KEY_NAME) client_secret = backend_setting(self, self.SETTINGS_SECRET_NAME) public_key = backend_setting(self, self.SETTINGS_PUBLIC_NAME) return client_key, client_secret, public_key class OdnoklassnikiOAuth2(BaseOAuth2, OdnoklassnikiMixin): '''Odnoklassniki OAuth2 support''' AUTH_BACKEND = OdnoklassnikiBackend AUTHORIZATION_URL = 'http://www.odnoklassniki.ru/oauth/authorize' ACCESS_TOKEN_URL = 'http://api.odnoklassniki.ru/oauth/token.do' SETTINGS_KEY_NAME = 'ODNOKLASSNIKI_OAUTH2_CLIENT_KEY' SETTINGS_SECRET_NAME = 'ODNOKLASSNIKI_OAUTH2_CLIENT_SECRET' SETTINGS_PUBLIC_NAME = 'ODNOKLASSNIKI_OAUTH2_APP_KEY' def get_scope(self): return backend_setting(self, 'ODNOKLASSNIKI_OAUTH2_EXTRA_SCOPE', []) def user_data(self, access_token, *args, **kwargs): '''Return user data from Odnoklassniki REST API''' data = {'access_token': access_token, 'method': 'users.getCurrentUser'} client_key, client_secret, public_key = self.get_settings() return odnoklassniki_api(data, ODNOKLASSNIKI_API_SERVER, public_key, client_secret, 'oauth') def odnoklassniki_oauth_sig(data, client_secret): '''Calculates signature of request data access_token value must be included Algorithm is described at http://dev.odnoklassniki.ru/wiki/pages/viewpage.action?pageId=12878032, search for "little bit different way" ''' suffix = md5('{0:s}{1:s}'.format(data['access_token'], client_secret)).hexdigest() check_list = sorted(['{0:s}={1:s}'.format(key, value) for key, value in data.items() if key != 'access_token']) return md5(''.join(check_list) + suffix).hexdigest() def odnoklassniki_iframe_sig(data, client_secret_or_session_secret): '''Calculates signature as described at: http://dev.odnoklassniki.ru/wiki/display/ok/ Authentication+and+Authorization If API method requires session context, request is signed with session secret key. Otherwise it is signed with application secret key ''' param_list = sorted(['{0:s}={1:s}'.format(key, value) for key, value in data.items()]) return md5(''.join(param_list) + client_secret_or_session_secret).hexdigest() def odnoklassniki_api(data, api_url, public_key, client_secret, request_type='oauth'): ''' Calls Odnoklassniki REST API method http://dev.odnoklassniki.ru/wiki/display/ok/Odnoklassniki+Rest+API ''' data.update({ 'application_key': public_key, 'format': 'JSON' }) if request_type == 'oauth': data['sig'] = odnoklassniki_oauth_sig(data, client_secret) elif request_type == 'iframe_session': data['sig'] = odnoklassniki_iframe_sig(data, data['session_secret_key']) elif request_type == 'iframe_nosession': data['sig'] = odnoklassniki_iframe_sig(data, client_secret) else: msg = 'Unknown request type {0}. How should it be signed?' raise AuthFailed(msg.format(request_type)) params = urlencode(data) request = Request('{0}fb.do?{1}'.format(api_url, params)) try: return simplejson.loads(dsa_urlopen(request).read()) except (TypeError, KeyError, IOError, ValueError, IndexError): log('error', 'Could not load data from Odnoklassniki.', exc_info=True, extra=dict(data=params)) return None class OdnoklassnikiIframeForm(forms.Form): logged_user_id = forms.IntegerField() api_server = forms.CharField() application_key = forms.CharField() session_key = forms.CharField() session_secret_key = forms.CharField() authorized = forms.IntegerField() apiconnection = forms.CharField() refplace = forms.CharField(required=False) referer = forms.CharField(required=False) auth_sig = forms.CharField() sig = forms.CharField() custom_args = forms.CharField(required=False) def __init__(self, auth, *args, **kwargs): self.auth = auth super(OdnoklassnikiIframeForm, self).__init__(*args, **kwargs) def get_auth_sig(self): secret_key = backend_setting(self.auth, 'ODNOKLASSNIKI_APP_SECRET') hash_source = '{0:d}{1:s}{2:s}'.format( self.cleaned_data['logged_user_id'], self.cleaned_data['session_key'], secret_key ) return md5(hash_source).hexdigest() def clean_auth_sig(self): correct_key = self.get_auth_sig() key = self.cleaned_data['auth_sig'].lower() if correct_key != key: raise forms.ValidationError('Wrong authorization key') return self.cleaned_data['auth_sig'] def get_response(self): fields = ('logged_user_id', 'api_server', 'application_key', 'session_key', 'session_secret_key', 'authorized', 'apiconnection', ) response = {} for fieldname in self.fields.keys(): if fieldname in fields: response[fieldname] = self.cleaned_data[fieldname] return response class OdnoklassnikiAppBackend(SocialAuthBackend): '''Odnoklassniki iframe app authentication backend''' name = 'odnoklassnikiapp' def get_user_id(self, details, response): '''Return unique user id provided by Odnoklassniki''' return response['uid'] def extra_data(self, user, uid, response, details): return dict([(key, value) for key, value in response.items() if key in response['extra_data_list']]) def get_user_details(self, response): return {'username': response['uid'], 'email': '', 'fullname': unquote(response['name']), 'first_name': unquote(response['first_name']), 'last_name': unquote(response['last_name'])} class OdnoklassnikiApp(BaseAuth, OdnoklassnikiMixin): '''Odnoklassniki iframe app authentication class''' SETTINGS_KEY_NAME = 'ODNOKLASSNIKI_APP_KEY' SETTINGS_SECRET_NAME = 'ODNOKLASSNIKI_APP_SECRET' SETTINGS_PUBLIC_NAME = 'ODNOKLASSNIKI_APP_PUBLIC_KEY' AUTH_BACKEND = OdnoklassnikiAppBackend def auth_complete(self, request, user, *args, **kwargs): form = OdnoklassnikiIframeForm(auth=self, data=request.GET) if not form.is_valid(): raise AuthFailed('Cannot authorize: malformed parameters') else: response = form.get_response() extra_user_data = backend_setting( self, 'ODNOKLASSNIKI_APP_EXTRA_USER_DATA_LIST', ()) base_fields = ('uid', 'first_name', 'last_name', 'name') fields = base_fields + extra_user_data data = { 'method': 'users.getInfo', 'uids': '{0}'.format(response['logged_user_id']), 'fields': ','.join(fields), } client_key, client_secret, public_key = self.get_settings() details = odnoklassniki_api(data, response['api_server'], public_key, client_secret, 'iframe_nosession') if len(details) == 1 and 'uid' in details[0]: details = details[0] auth_data_fields = backend_setting( self, 'ODNOKLASSNIKI_APP_EXTRA_AUTH_DATA_LIST', ('api_server', 'apiconnection', 'session_key', 'session_secret_key', 'authorized') ) for field in auth_data_fields: details[field] = response[field] details['extra_data_list'] = fields + auth_data_fields kwargs.update({ 'auth': self, 'response': details, self.AUTH_BACKEND.name: True }) else: raise AuthFailed('Cannot get user details: API error') return authenticate(*args, **kwargs) @property def uses_redirect(self): ''' Odnoklassniki API for iframe application does not require redirects ''' return False # Backend definition BACKENDS = { 'odnoklassniki': OdnoklassnikiOAuth2, 'odnoklassnikiapp': OdnoklassnikiApp }
# 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. ''' Adapted from https://github.com/tornadomeet/ResNet/blob/master/symbol_resnet.py (Original author Wei Wu) by Antti-Pekka Hynninen "Flexible Layout" (fl) version created by Dick Carter. Implementing the original resnet ILSVRC 2015 winning network from: Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. "Deep Residual Learning for Image Recognition" ''' import mxnet as mx import numpy as np import random # used by group_bn initialization from mxnet.base import check_call, _LIB, c_array import ctypes from mpi4py import MPI # this is a dummy list to collect initialization records to guarantee they # won't be destroied by garabge collector anti_gc=[] # FIXME: evntually to be moved into FW def bn_group_to_sync_depth(bn_group): #this is log2 array to determine the number of required sync steps per bn_group bn2sync=[0,0,1,1,2,2,2,2,3] sync_depth = bn2sync[bn_group] return sync_depth def handler_bytes(): return 64 # FIXME: add FW function returning a real size measurement # Transform a symbol from one layout to another, or do nothing if they have the same layout def transform_layout(data, from_layout, to_layout): supported_layouts = ['NCHW', 'NHWC'] if from_layout not in supported_layouts: raise ValueError('Not prepared to handle layout: {}'.format(from_layout)) if to_layout not in supported_layouts: raise ValueError('Not prepared to handle layout: {}'.format(to_layout)) # Insert transpose if from_layout and to_layout don't match if from_layout == 'NCHW' and to_layout == 'NHWC': return mx.sym.transpose(data, axes=(0, 2, 3, 1)) elif from_layout == 'NHWC' and to_layout == 'NCHW': return mx.sym.transpose(data, axes=(0, 3, 1, 2)) else: return data # A BatchNorm wrapper that responds to the input layout def batchnorm(rank, data, io_layout, batchnorm_layout, bn_group, local_gpus, local_comm, **kwargs): # Transpose as needed to batchnorm_layout transposed_as_needed = transform_layout(data, io_layout, batchnorm_layout) bn_axis = 3 if batchnorm_layout == 'NHWC' else 1 xbuf_ptr = (ctypes.c_void_p * local_gpus)() if bn_group>1: sync_depth = bn_group_to_sync_depth(bn_group) if local_comm is not None: handler = np.zeros(handler_bytes(),dtype=np.byte) check_call(_LIB.MXInitXBufSingle(rank, sync_depth, xbuf_ptr, handler.ctypes.data_as(ctypes.c_void_p))) handlers = np.asarray([np.zeros(handler_bytes(),dtype=np.byte)]*local_gpus) local_comm.Allgather([handler, handler_bytes(), MPI.BYTE], [handlers, handler_bytes(), MPI.BYTE]) (_LIB.MXOpenIpcHandles(rank, local_gpus, sync_depth, xbuf_ptr, handlers.ctypes.data_as(ctypes.c_void_p))) else: check_call(_LIB.MXInitXBuf(local_gpus, sync_depth, xbuf_ptr)) anti_gc.append(xbuf_ptr) batchnormed = mx.sym.BatchNorm(data=transposed_as_needed, axis=bn_axis, bn_group=bn_group, xbuf_ptr=ctypes.addressof(xbuf_ptr), **kwargs) # Transpose back to i/o layout as needed return transform_layout(batchnormed, batchnorm_layout, io_layout) # A BatchNormAddRelu wrapper that responds to the input layout def batchnorm_add_relu(rank, data, addend, io_layout, batchnorm_layout, bn_group, local_gpus, local_comm, **kwargs): # Transpose as needed to batchnorm_layout transposed_data_as_needed = transform_layout(data, io_layout, batchnorm_layout) transposed_addend_as_needed = transform_layout(addend, io_layout, batchnorm_layout) bn_axis = 3 if batchnorm_layout == 'NHWC' else 1 xbuf_ptr = (ctypes.c_void_p * local_gpus)() if bn_group>1: sync_depth = bn_group_to_sync_depth(bn_group) if local_comm is not None: handler = np.zeros(handler_bytes(),dtype=np.byte) check_call(_LIB.MXInitXBufSingle(rank, sync_depth, xbuf_ptr, handler.ctypes.data_as(ctypes.c_void_p))) handlers = np.asarray([np.zeros(handler_bytes(),dtype=np.byte)]*local_gpus) local_comm.Allgather([handler, handler_bytes(), MPI.BYTE], [handlers, handler_bytes(), MPI.BYTE]) (_LIB.MXOpenIpcHandles(rank, local_gpus, sync_depth, xbuf_ptr, handlers.ctypes.data_as(ctypes.c_void_p))) else: check_call(_LIB.MXInitXBuf(local_gpus, sync_depth, xbuf_ptr)) anti_gc.append(xbuf_ptr) batchnormed = mx.sym.BatchNormAddRelu(data=transposed_data_as_needed, addend=transposed_addend_as_needed, axis=bn_axis, bn_group=bn_group, xbuf_ptr=ctypes.addressof(xbuf_ptr), **kwargs) # Transpose back to i/o layout as needed return transform_layout(batchnormed, batchnorm_layout, io_layout) # A Pooling wrapper that responds to the input layout def pooling(data, io_layout, pooling_layout, **kwargs): # Pooling kernel, as specified by pooling_layout, may be in conflict with i/o layout. transposed_as_needed = transform_layout(data, io_layout, pooling_layout) pooled = mx.sym.Pooling(data=transposed_as_needed, layout=pooling_layout, **kwargs) # Transpose back to i/o layout as needed return transform_layout(pooled, pooling_layout, io_layout) # Assumption is that data comes in and out in the 'conv_layout' format. # If this format is different from the 'batchnorm_layout' format, then the batchnorm() routine # will introduce transposes on both sides of the mx.sym.BatchNorm symbol def residual_unit(rank, data, num_filter, stride, dim_match, name, bottle_neck=True, workspace=256, memonger=False, conv_layout='NCHW', batchnorm_layout='NCHW', verbose=False, cudnn_bn_off=False, bn_eps=2e-5, bn_mom=0.9, conv_algo=-1, fuse_bn_relu=False, fuse_bn_add_relu=False, cudnn_tensor_core_only=False, bn_group=1, local_gpus=None, local_comm=None): """Return ResNet Unit symbol for building ResNet Parameters ---------- data : str Input data num_filter : int Number of output channels bnf : int Bottle neck channels factor with regard to num_filter stride : tuple Stride used in convolution dim_match : Boolean True means channel number between input and output is the same, otherwise means differ name : str Base name of the operators workspace : int Workspace used in convolution operator """ act = 'relu' if fuse_bn_relu else None if bottle_neck: conv1 = mx.sym.Convolution(data=data, num_filter=int(num_filter*0.25), kernel=(1,1), stride=(1,1), pad=(0,0), no_bias=True, workspace=workspace, name=name + '_conv1', layout=conv_layout, cudnn_algo_verbose=verbose, cudnn_algo_fwd=conv_algo, cudnn_algo_bwd_data=conv_algo, cudnn_algo_bwd_filter=conv_algo, cudnn_tensor_core_only=cudnn_tensor_core_only) bn1 = batchnorm(rank, data=conv1, io_layout=conv_layout, batchnorm_layout=batchnorm_layout, fix_gamma=False, eps=bn_eps, momentum=bn_mom, name=name + '_bn1', cudnn_off=cudnn_bn_off, act_type=act, bn_group=bn_group, local_gpus=local_gpus, local_comm=local_comm) act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1') if not fuse_bn_relu else bn1 conv2 = mx.sym.Convolution(data=act1, num_filter=int(num_filter*0.25), kernel=(3,3), stride=stride, pad=(1,1), no_bias=True, workspace=workspace, name=name + '_conv2', layout=conv_layout, cudnn_algo_verbose=verbose, cudnn_algo_fwd=conv_algo, cudnn_algo_bwd_data=conv_algo, cudnn_algo_bwd_filter=conv_algo, cudnn_tensor_core_only=cudnn_tensor_core_only) bn2 = batchnorm(rank, data=conv2, io_layout=conv_layout, batchnorm_layout=batchnorm_layout, fix_gamma=False, eps=bn_eps, momentum=bn_mom, name=name + '_bn2', cudnn_off=cudnn_bn_off, act_type=act, bn_group=bn_group, local_gpus=local_gpus, local_comm=local_comm) act2 = mx.sym.Activation(data=bn2, act_type='relu', name=name + '_relu2') if not fuse_bn_relu else bn2 conv3 = mx.sym.Convolution(data=act2, num_filter=num_filter, kernel=(1,1), stride=(1,1), pad=(0,0), no_bias=True, workspace=workspace, name=name + '_conv3', layout=conv_layout, cudnn_algo_verbose=verbose, cudnn_algo_fwd=conv_algo, cudnn_algo_bwd_data=conv_algo, cudnn_algo_bwd_filter=conv_algo, cudnn_tensor_core_only=cudnn_tensor_core_only) if dim_match: shortcut = data else: conv1sc = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True, workspace=workspace, name=name+'_conv1sc', layout=conv_layout, cudnn_algo_verbose=verbose, cudnn_algo_fwd=conv_algo, cudnn_algo_bwd_data=conv_algo, cudnn_algo_bwd_filter=conv_algo, cudnn_tensor_core_only=cudnn_tensor_core_only) if bn_group>1: # a work arround to enforce strict ordering of bn layers # a more performant solution using a dummy imput/input would eliminate the need # for redundant math operations shortcut = batchnorm(rank, data=conv1sc+conv3*0 , io_layout=conv_layout, batchnorm_layout=batchnorm_layout, fix_gamma=False, eps=bn_eps, momentum=bn_mom, name=name + '_bn_sc', cudnn_off=cudnn_bn_off, bn_group=bn_group, local_gpus=local_gpus, local_comm=local_comm) else: shortcut = batchnorm(rank, data=conv1sc , io_layout=conv_layout, batchnorm_layout=batchnorm_layout, fix_gamma=False, eps=bn_eps, momentum=bn_mom, name=name + '_bn_sc', cudnn_off=cudnn_bn_off, bn_group=bn_group, local_gpus=local_gpus, local_comm=local_comm) if memonger: shortcut._set_attr(mirror_stage='True') if fuse_bn_add_relu: return batchnorm_add_relu(rank, data=conv3, addend=shortcut, io_layout=conv_layout, batchnorm_layout=batchnorm_layout, fix_gamma=False, eps=bn_eps, momentum=bn_mom, name=name + '_bn3', cudnn_off=cudnn_bn_off, bn_group=bn_group, local_gpus=local_gpus, local_comm=local_comm) else: bn3 = batchnorm(rank, data=conv3, io_layout=conv_layout, batchnorm_layout=batchnorm_layout, fix_gamma=False, eps=bn_eps, momentum=bn_mom, name=name + '_bn3', cudnn_off=cudnn_bn_off, bn_group=bn_group, local_gpus=local_gpus, local_comm=local_comm) return mx.sym.Activation(data=bn3 + shortcut, act_type='relu', name=name + '_relu3') else: raise NotImplementedError def resnet(rank, units, num_stages, filter_list, num_classes, image_shape, bottle_neck=True, workspace=256, dtype='float32', memonger=False, input_layout='NCHW', conv_layout='NCHW', batchnorm_layout='NCHW', pooling_layout='NCHW', verbose=False, cudnn_bn_off=False, bn_eps=2e-5, bn_mom=0.9, conv_algo=-1, fuse_bn_relu=False, fuse_bn_add_relu=False, force_tensor_core=False, use_dali=True, label_smoothing = 0.0, bn_group=1, local_gpus=None, local_comm=None): """Return ResNet symbol of Parameters ---------- units : list Number of units in each stage num_stages : int Number of stage filter_list : list Channel size of each stage num_classes : int Ouput size of symbol dataset : str Dataset type, only cifar10 and imagenet supports workspace : int Workspace used in convolution operator dtype : str Precision (float32 or float16) memonger : boolean Activates "memory monger" to reduce the model's memory footprint input_layout : str interpretation (e.g. NCHW vs NHWC) of data provided by the i/o pipeline (may introduce transposes if in conflict with 'layout' above) conv_layout : str interpretation (e.g. NCHW vs NHWC) of data for convolution operation. batchnorm_layout : str directs which kernel performs the batchnorm (may introduce transposes if in conflict with 'conv_layout' above) pooling_layout : str directs which kernel performs the pooling (may introduce transposes if in conflict with 'conv_layout' above) """ act = 'relu' if fuse_bn_relu else None num_unit = len(units) assert(num_unit == num_stages) data = mx.sym.Variable(name='data') if not use_dali: # double buffering of data if dtype == 'float32': data = mx.sym.identity(data=data, name='id') else: if dtype == 'float16': data = mx.sym.Cast(data=data, dtype=np.float16) (nchannel, height, width) = image_shape # Insert transpose as needed to get the input layout to match the desired processing layout data = transform_layout(data, input_layout, conv_layout) if height <= 32: # such as cifar10 body = mx.sym.Convolution(data=data, num_filter=filter_list[0], kernel=(3, 3), stride=(1,1), pad=(1, 1), no_bias=True, name="conv0", workspace=workspace, layout=conv_layout, cudnn_algo_verbose=verbose, cudnn_algo_fwd=conv_algo, cudnn_algo_bwd_data=conv_algo, cudnn_algo_bwd_filter=conv_algo, cudnn_tensor_core_only=force_tensor_core) # Is this BatchNorm supposed to be here? body = batchnorm(data=body, io_layout=conv_layout, batchnorm_layout=batchnorm_layout, fix_gamma=False, eps=bn_eps, momentum=bn_mom, name='bn0', cudnn_off=cudnn_bn_off) else: # often expected to be 224 such as imagenet body = mx.sym.Convolution(data=data, num_filter=filter_list[0], kernel=(7, 7), stride=(2,2), pad=(3, 3), no_bias=True, name="conv0", workspace=workspace, layout=conv_layout, cudnn_algo_verbose=verbose, cudnn_algo_fwd=conv_algo, cudnn_algo_bwd_data=conv_algo, cudnn_algo_bwd_filter=conv_algo, cudnn_tensor_core_only=force_tensor_core) body = batchnorm(rank, data=body, io_layout=conv_layout, batchnorm_layout=batchnorm_layout, fix_gamma=False, eps=bn_eps, momentum=bn_mom, name='bn0', cudnn_off=cudnn_bn_off, act_type=act, bn_group=bn_group, local_gpus=local_gpus, local_comm=local_comm) if not fuse_bn_relu: body = mx.sym.Activation(data=body, act_type='relu', name='relu0') body = pooling(data=body, io_layout=conv_layout, pooling_layout=pooling_layout, kernel=(3, 3), stride=(2, 2), pad=(1, 1), pool_type='max') for i in range(num_stages): body = residual_unit(rank, body, filter_list[i+1], (1 if i==0 else 2, 1 if i==0 else 2), False, name='stage%d_unit%d' % (i + 1, 1), bottle_neck=bottle_neck, workspace=workspace, memonger=memonger, conv_layout=conv_layout, batchnorm_layout=batchnorm_layout, verbose=verbose, cudnn_bn_off=cudnn_bn_off, bn_eps=bn_eps, bn_mom=bn_mom, conv_algo=conv_algo, fuse_bn_relu=fuse_bn_relu, fuse_bn_add_relu=fuse_bn_add_relu, cudnn_tensor_core_only=force_tensor_core, bn_group=bn_group, local_gpus=local_gpus, local_comm=local_comm) for j in range(units[i]-1): body = residual_unit(rank, body, filter_list[i+1], (1,1), True, name='stage%d_unit%d' % (i + 1, j + 2), bottle_neck=bottle_neck, workspace=workspace, memonger=memonger, conv_layout=conv_layout, batchnorm_layout=batchnorm_layout, verbose=verbose, cudnn_bn_off=cudnn_bn_off, bn_eps = bn_eps, bn_mom=bn_mom, conv_algo=conv_algo, fuse_bn_relu=fuse_bn_relu, fuse_bn_add_relu=fuse_bn_add_relu, cudnn_tensor_core_only=force_tensor_core, bn_group=bn_group, local_gpus=local_gpus, local_comm=local_comm) # Although kernel is not used here when global_pool=True, we should put one pool1 = pooling(data=body, io_layout=conv_layout, pooling_layout=pooling_layout, global_pool=True, kernel=(7, 7), pool_type='avg', name='pool1') flat = mx.sym.Flatten(data=pool1) fc1 = mx.sym.FullyConnected(data=flat, num_hidden=num_classes, name='fc1', cublas_algo_verbose=verbose) if dtype == 'float16': fc1 = mx.sym.Cast(data=fc1, dtype=np.float32) ########################################################################## # MXNet computes Cross Entropy loss gradients without explicitly computing # the value of loss function. # Take a look here: # https://mxnet.incubator.apache.org/api/python/symbol/symbol.html#mxnet.symbol.SoftmaxOutput # for further details ########################################################################## return mx.sym.SoftmaxOutput(data=fc1, name='softmax', smooth_alpha=label_smoothing) def get_symbol(num_classes, num_layers, image_shape, conv_workspace=1024, dtype='float32', input_layout='NCHW', conv_layout='NCHW', batchnorm_layout='NCHW', pooling_layout='NCHW', verbose=False, seed=None, cudnn_bn_off=False, batchnorm_eps=2e-5, batchnorm_mom=0.9, conv_algo=-1, fuse_bn_relu=False, fuse_bn_add_relu=False, force_tensor_core=False, use_dali=True, label_smoothing = 0.0, **kwargs): """ Adapted from https://github.com/tornadomeet/ResNet/blob/master/symbol_resnet.py (Original author Wei Wu) by Antti-Pekka Hynninen Implementing the original resnet ILSVRC 2015 winning network from: Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. "Deep Residual Learning for Image Recognition" """ image_shape = [int(l) for l in image_shape.split(',')] (nchannel, height, width) = image_shape if height <= 28: num_stages = 3 if (num_layers-2) % 9 == 0 and num_layers >= 164: per_unit = [(num_layers-2)//9] filter_list = [16, 64, 128, 256] bottle_neck = True elif (num_layers-2) % 6 == 0 and num_layers < 164: per_unit = [(num_layers-2)//6] filter_list = [16, 16, 32, 64] bottle_neck = False else: raise ValueError("no experiments done on num_layers {}, you can do it yourself".format(num_layers)) units = per_unit * num_stages else: if num_layers >= 50: filter_list = [64, 256, 512, 1024, 2048] bottle_neck = True else: filter_list = [64, 64, 128, 256, 512] bottle_neck = False num_stages = 4 if num_layers == 18: units = [2, 2, 2, 2] elif num_layers == 34: units = [3, 4, 6, 3] elif num_layers == 50: units = [3, 4, 6, 3] elif num_layers == 101: units = [3, 4, 23, 3] elif num_layers == 152: units = [3, 8, 36, 3] elif num_layers == 200: units = [3, 24, 36, 3] elif num_layers == 269: units = [3, 30, 48, 8] else: raise ValueError("no experiments done on num_layers {}, you can do it yourself".format(num_layers)) # group bn gpu_per_process = len(kwargs.get('gpus').split(',')) # here local refers to current node local_gpus = 0 local_comm = None bn_group = kwargs.get('bn_group') if bn_group>1: if gpu_per_process>1: # assumption is that this is kvstore case local_gpus = gpu_per_process raise ValueError("While the infrastructure is there, group_bn is currently not supported for device=kvstore. Cancel this exception to try.") else: global_comm = MPI.COMM_WORLD local_comm = global_comm.Split_type(MPI.COMM_TYPE_SHARED) local_gpus=local_comm.Get_size() # FIXME: use kwargs through return resnet(rank = kwargs.get('local_rank'), units = units, num_stages = num_stages, filter_list = filter_list, num_classes = num_classes, image_shape = image_shape, bottle_neck = bottle_neck, workspace = conv_workspace, dtype = dtype, input_layout = input_layout, conv_layout = conv_layout, batchnorm_layout = batchnorm_layout, pooling_layout = pooling_layout, verbose = verbose, cudnn_bn_off = cudnn_bn_off, bn_eps = batchnorm_eps, bn_mom = batchnorm_mom, conv_algo = conv_algo, fuse_bn_relu = fuse_bn_relu, fuse_bn_add_relu = fuse_bn_add_relu, force_tensor_core = force_tensor_core, use_dali = use_dali, label_smoothing = label_smoothing, bn_group = bn_group, local_gpus = local_gpus, local_comm = local_comm)
''' whooshalchemy flask extension ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Adds whoosh indexing capabilities to SQLAlchemy models for Flask applications. :copyright: (c) 2012 by Karl Gyllstrom :license: BSD (see LICENSE.txt) ''' from __future__ import with_statement from __future__ import absolute_import import flask.ext.sqlalchemy as flask_sqlalchemy import sqlalchemy from whoosh.qparser import OrGroup from whoosh.qparser import AndGroup from whoosh.qparser import MultifieldParser from whoosh.analysis import StemmingAnalyzer import whoosh.index from whoosh.fields import Schema #from whoosh.fields import ID, TEXT, KEYWORD, STORED import heapq import os __searchable__ = '__searchable__' try: unicode except NameError: unicode = str DEFAULT_WHOOSH_INDEX_NAME = 'whoosh_index' class _QueryProxy(flask_sqlalchemy.BaseQuery): # We're replacing the model's ``query`` field with this proxy. The main # thing this proxy does is override the __iter__ method so that results are # returned in the order of the whoosh score to reflect text-based ranking. def __init__(self, entities, session=None): super(_QueryProxy, self).__init__(entities, session) self._modelclass = self._mapper_zero().class_ self._primary_key_name = self._modelclass.whoosh_primary_key self._whoosh_searcher = self._modelclass.pure_whoosh # Stores whoosh results from query. If ``None``, indicates that no # whoosh query was performed. self._whoosh_rank = None def __iter__(self): ''' Reorder ORM-db results according to Whoosh relevance score. ''' super_iter = super(_QueryProxy, self).__iter__() if self._whoosh_rank is None or self._order_by is not False: # Whoosh search hasn't been run or caller has explicitly asked # for results to be sorted, so behave as normal (no Whoosh # relevance score sorting). return super_iter super_rows = list(super_iter) # Iterate through the values and re-order by whoosh relevance. ordered_by_whoosh_rank = [] for row in super_rows: # Push items onto heap, where sort value is the rank provided by # Whoosh if hasattr(row, self._primary_key_name): heapq.heappush(ordered_by_whoosh_rank, (self._whoosh_rank[unicode(getattr(row, self._primary_key_name))], row)) else: # PK column not found in result row return iter(super_rows) def _inner(): while ordered_by_whoosh_rank: yield heapq.heappop(ordered_by_whoosh_rank)[1] return _inner() def whoosh_search(self, query, limit=None, fields=None, or_=False): ''' Execute text query on database. Results have a text-based match to the query, ranked by the scores from the underlying Whoosh index. By default, the search is executed on all of the indexed fields as an OR conjunction. For example, if a model has 'title' and 'content' indicated as ``__searchable__``, a query will be checked against both fields, returning any instance whose title or content are a content match for the query. To specify particular fields to be checked, populate the ``fields`` parameter with the desired fields. By default, results will only be returned if they contain all of the query terms (AND). To switch to an OR grouping, set the ``or_`` parameter to ``True``. ''' if not isinstance(query, unicode): query = unicode(query) results = self._whoosh_searcher(query, limit, fields, or_) if not results: # We don't want to proceed with empty results because we get a # stderr warning from sqlalchemy when executing 'in_' on empty set. # However we cannot just return an empty list because it will not # be a query. # XXX is this efficient? # explicitly set text('null') to avoid a warning in output return self.filter(sqlalchemy.text('null')) result_set = set() result_ranks = {} for rank, result in enumerate(results): pk = result[self._primary_key_name] result_set.add(pk) result_ranks[pk] = rank f = self.filter(getattr(self._modelclass, self._primary_key_name).in_(result_set)) f._whoosh_rank = result_ranks return f class _Searcher(object): ''' Assigned to a Model class as ``pure_search``, which enables text-querying to whoosh hit list. Also used by ``query.whoosh_search``''' def __init__(self, primary, indx): self.primary_key_name = primary self._index = indx self.searcher = indx.searcher() self._all_fields = list(set(indx.schema._fields.keys()) - set([self.primary_key_name])) def __call__(self, query, limit=None, fields=None, or_=False): if fields is None: fields = self._all_fields group = OrGroup if or_ else AndGroup parser = MultifieldParser(fields, self._index.schema, group=group) return self._index.searcher().search(parser.parse(query), limit=limit) def whoosh_index(app, model): ''' Create whoosh index for ``model``, if one does not exist. If the index exists it is opened and cached. ''' # gets the whoosh index for this model, creating one if it does not exist. # A dict of model -> whoosh index is added to the ``app`` variable. if not hasattr(app, 'whoosh_indexes'): app.whoosh_indexes = {} return app.whoosh_indexes.get(model.__name__, _create_index(app, model)) def _get_analyzer(app, model): analyzer = getattr(model, '__analyzer__', None) if not analyzer and app.config.get('WHOOSH_ANALYZER'): analyzer = app.config['WHOOSH_ANALYZER'] if not analyzer: analyzer = StemmingAnalyzer() return analyzer def _create_index(app, model): # a schema is created based on the fields of the model. Currently we only # support primary key -> whoosh.ID, and sqlalchemy.(String, Unicode, Text) # -> whoosh.TEXT. if not app.config.get('WHOOSH_BASE'): # XXX todo: is there a better approach to handle the absenSe of a # config value for whoosh base? Should we throw an exception? If # so, this exception will be thrown in the after_commit function, # which is probably not ideal. app.config['WHOOSH_BASE'] = DEFAULT_WHOOSH_INDEX_NAME # we index per model. wi = os.path.join(app.config.get('WHOOSH_BASE'), model.__name__) analyzer = _get_analyzer(app, model) schema, primary_key = _get_whoosh_schema_and_primary_key(model, analyzer) if whoosh.index.exists_in(wi): indx = whoosh.index.open_dir(wi) else: if not os.path.exists(wi): os.makedirs(wi) indx = whoosh.index.create_in(wi, schema) app.whoosh_indexes[model.__name__] = indx model.pure_whoosh = _Searcher(primary_key, indx) model.whoosh_primary_key = primary_key # change the query class of this model to our own model.query_class = _QueryProxy return indx def _get_whoosh_schema_and_primary_key(model, analyzer): schema = {} primary = None searchable = set(model.__searchable__) for field in model.__table__.columns: if field.primary_key: schema[field.name] = whoosh.fields.ID(stored=True, unique=True) primary = field.name if field.name in searchable and isinstance(field.type, (sqlalchemy.types.Text, sqlalchemy.types.String, sqlalchemy.types.Unicode)): schema[field.name] = whoosh.fields.TEXT(analyzer=analyzer) return Schema(**schema), primary def _after_flush(app, changes): # Any db updates go through here. We check if any of these models have # ``__searchable__`` fields, indicating they need to be indexed. With these # we update the whoosh index for the model. If no index exists, it will be # created here; this could impose a penalty on the initial commit of a # model. bytype = {} # sort changes by type so we can use per-model writer for change in changes: update = change[1] in ('update', 'insert') if hasattr(change[0].__class__, __searchable__): bytype.setdefault(change[0].__class__.__name__, []).append((update, change[0])) for model, values in bytype.items(): index = whoosh_index(app, values[0][1].__class__) with index.writer() as writer: primary_field = values[0][1].pure_whoosh.primary_key_name searchable = values[0][1].__searchable__ for update, v in values: if update: attrs = {} for key in searchable: try: attrs[key] = unicode(getattr(v, key)) except AttributeError: raise AttributeError('{0} does not have {1} field {2}' .format(model, __searchable__, key)) attrs[primary_field] = unicode(getattr(v, primary_field)) writer.update_document(**attrs) else: writer.delete_by_term(primary_field, unicode(getattr(v, primary_field))) flask_sqlalchemy.models_committed.connect(_after_flush)
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Module to draw an html gantt chart from logfile produced by callback_log.log_nodes_cb() """ # Import packages import json from dateutil import parser import datetime import random from collections import OrderedDict # Pandas try: import pandas as pd except ImportError: print('Pandas not found; in order for full functionality of this module '\ 'install the pandas package') pass def create_event_dict(start_time, nodes_list): ''' Function to generate a dictionary of event (start/finish) nodes from the nodes list Parameters ---------- start_time : datetime.datetime a datetime object of the pipeline start time nodes_list : list a list of the node dictionaries that were run in the pipeline Returns ------- events : dictionary a dictionary where the key is the timedelta from the start of the pipeline execution to the value node it accompanies ''' # Import packages import copy events = {} for node in nodes_list: # Format node fields estimated_threads = int(node.get('num_threads'), 1) estimated_memory_gb = float(node.get('estimated_memory_gb', 1.0)) runtime_threads = int(node.get('runtime_threads'), 0) runtime_memory_gb = float(node.get('runtime_memory_gb', 0.0)) # Init and format event-based nodes node['estimated_threads'] = estimated_threads node['estimated_memory_gb'] = estimated_memory_gb node['runtime_threads'] = runtime_threads node['runtime_memory_gb'] = runtime_memory_gb start_node = node finish_node = copy.deepcopy(node) start_node['event'] = 'start' finish_node['event'] = 'finish' # Get dictionary key start_delta = (node['start'] - start_time).total_seconds() finish_delta = (node['finish'] - start_time).total_seconds() # Populate dictionary if events.has_key(start_delta) or events.has_key(finish_delta): err_msg = 'Event logged twice or events started at exact same time!' raise KeyError(err_msg) events[start_delta] = start_node events[finish_delta] = finish_node # Return events dictionary return events def log_to_dict(logfile): ''' Function to extract log node dictionaries into a list of python dictionaries and return the list as well as the final node Parameters ---------- logfile : string path to the json-formatted log file generated from a nipype workflow execution Returns ------- nodes_list : list a list of python dictionaries containing the runtime info for each nipype node ''' # Init variables #keep track of important vars nodes_list = [] #all the parsed nodes unifinished_nodes = [] #all start nodes that dont have a finish yet with open(logfile, 'r') as content: #read file separating each line content = content.read() lines = content.split('\n') for l in lines: #try to parse each line and transform in a json dict. #if the line has a bad format, just skip node = None try: node = json.loads(l) except ValueError: pass if not node: continue #if it is a start node, add to unifinished nodes if 'start' in node: node['start'] = parser.parse(node['start']) unifinished_nodes.append(node) #if it is end node, look in uninished nodes for matching start #remove from unifinished list and add to node list elif 'finish' in node: node['finish'] = parser.parse(node['finish']) #because most nodes are small, we look backwards in the unfinished list for s in range(len(unifinished_nodes)): aux = unifinished_nodes[s] #found the end for node start, copy over info if aux['id'] == node['id'] and aux['name'] == node['name'] \ and aux['start'] < node['finish']: node['start'] = aux['start'] node['duration'] = \ (node['finish'] - node['start']).total_seconds() unifinished_nodes.remove(aux) nodes_list.append(node) break #finished parsing #assume nodes without finish didn't finish running. #set their finish to last node run last_node = nodes_list[-1] for n in unifinished_nodes: n['finish'] = last_node['finish'] n['duration'] = (n['finish'] - n['start']).total_seconds() nodes_list.append(n) # Return list of nodes return nodes_list def calculate_resource_timeseries(events, resource): ''' Given as event dictionary, calculate the resources used as a timeseries Parameters ---------- events : dictionary a dictionary of event-based node dictionaries of the workflow execution statistics resource : string the resource of interest to return the time-series of; e.g. 'runtime_memory_gb', 'estimated_threads', etc Returns ------- time_series : pandas Series a pandas Series object that contains timestamps as the indices and the resource amount as values ''' # Init variables res = OrderedDict() all_res = 0.0 # Iterate through the events for tdelta, event in sorted(events.items()): if event['event'] == "start": if resource in event and event[resource] != 'Unkown': all_res += float(event[resource]) current_time = event['start']; elif event['event'] == "finish": if resource in event and event[resource] != 'Unkown': all_res -= float(event[resource]) current_time = event['finish']; res[current_time] = all_res # Formulate the pandas timeseries time_series = pd.Series(data=res.values(), index=res.keys()) # Downsample where there is only value-diff ts_diff = time_series.diff() time_series = time_series[ts_diff!=0] # Return the new time series return time_series def draw_lines(start, total_duration, minute_scale, scale): ''' Function to draw the minute line markers and timestamps Parameters ---------- start : datetime.datetime obj start time for first minute line marker total_duration : float total duration of the workflow execution (in seconds) minute_scale : integer the scale, in minutes, at which to plot line markers for the gantt chart; for example, minute_scale=10 means there are lines drawn at every 10 minute interval from start to finish scale : integer scale factor in pixel spacing between minute line markers Returns ------- result : string the html-formatted string for producing the minutes-based time line markers ''' # Init variables result = '' next_line = 220 next_time = start num_lines = int((total_duration/60) / minute_scale) + 2 # Iterate through the lines and create html line markers string for line in range(num_lines): # Line object new_line = "<hr class='line' width='98%%' style='top:%dpx;'>" % next_line result += new_line # Time digits time = "<p class='time' style='top:%dpx;'> %02d:%02d </p>" % \ (next_line-20, next_time.hour, next_time.minute) result += time # Increment line spacing and digits next_line += minute_scale * scale next_time += datetime.timedelta(minutes=minute_scale) # Return html string for time line markers return result def draw_nodes(start, nodes_list, cores, minute_scale, space_between_minutes, colors): ''' Function to return the html-string of the node drawings for the gantt chart Parameters ---------- start : datetime.datetime obj start time for first node nodes_list : list a list of the node dictionaries cores : integer the number of cores given to the workflow via the 'n_procs' plugin arg total_duration : float total duration of the workflow execution (in seconds) minute_scale : integer the scale, in minutes, at which to plot line markers for the gantt chart; for example, minute_scale=10 means there are lines drawn at every 10 minute interval from start to finish space_between_minutes : integer scale factor in pixel spacing between minute line markers colors : list a list of colors to choose from when coloring the nodes in the gantt chart Returns ------- result : string the html-formatted string for producing the minutes-based time line markers ''' # Init variables result = '' scale = float(space_between_minutes/float(minute_scale)) space_between_minutes = float(space_between_minutes/scale) end_times = [datetime.datetime(start.year, start.month, start.day, start.hour, start.minute, start.second) \ for core in range(cores)] # For each node in the pipeline for node in nodes_list: # Get start and finish times node_start = node['start'] node_finish = node['finish'] # Calculate an offset and scale duration offset = ((node_start - start).total_seconds() / 60) * scale * \ space_between_minutes + 220 # Scale duration scale_duration = (node['duration'] / 60) * scale * space_between_minutes if scale_duration < 5: scale_duration = 5 scale_duration -= 2 # Left left = 60 for core in range(len(end_times)): if end_times[core] < node_start: left += core * 30 end_times[core] = datetime.datetime(node_finish.year, node_finish.month, node_finish.day, node_finish.hour, node_finish.minute, node_finish.second) break # Get color for node object color = random.choice(colors) if 'error' in node: color = 'red' # Setup dictionary for node html string insertion node_dict = {'left' : left, 'offset' : offset, 'scale_duration' : scale_duration, 'color' : color, 'node_name' : node['name'], 'node_dur' : node['duration']/60.0, 'node_start' : node_start.strftime("%Y-%m-%d %H:%M:%S"), 'node_finish' : node_finish.strftime("%Y-%m-%d %H:%M:%S")} # Create new node string new_node = "<div class='node' style='left:%(left)spx;top:%(offset)spx;"\ "height:%(scale_duration)spx;background-color:%(color)s;'"\ "title='%(node_name)s\nduration:%(node_dur)s\n"\ "start:%(node_start)s\nend:%(node_finish)s'></div>" % \ node_dict # Append to output result result += new_node # Return html string for nodes return result def draw_resource_bar(start_time, finish_time, time_series, space_between_minutes, minute_scale, color, left, resource): ''' ''' # Memory header result = "<p class='time' style='top:198px;left:%dpx;'>%s</p>" \ % (left, resource) # Image scaling factors scale = float(space_between_minutes/float(minute_scale)) space_between_minutes = float(space_between_minutes/scale) # Iterate through time series ts_len = len(time_series) for idx, (ts_start, amount) in enumerate(time_series.iteritems()): if idx < ts_len-1: ts_end = time_series.index[idx+1] else: ts_end = finish_time # Calculate offset from start at top offset = ((ts_start-start_time).total_seconds() / 60.0) * scale * \ space_between_minutes + 220 # Scale duration duration_mins = (ts_end-ts_start).total_seconds() / 60.0 height = duration_mins * scale * \ space_between_minutes if height < 5: height = 5 height -= 2 # Bar width is proportional to resource amount width = amount * 20 if resource.lower() == 'memory': label = '%.3f GB' % amount else: label = '%d threads' % amount # Setup dictionary for bar html string insertion bar_dict = {'color' : color, 'height' : height, 'width' : width, 'offset': offset, 'left' : left, 'label' : label, 'duration' : duration_mins, 'start' : ts_start.strftime('%Y-%m-%d %H:%M:%S'), 'finish' : ts_end.strftime('%Y-%m-%d %H:%M:%S')} bar_html = "<div class='bar' style='background-color:%(color)s;"\ "height:%(height).3fpx;width:%(width).3fpx;"\ "left:%(left)dpx; top:%(offset).3fpx;'"\ "title='%(label)s\nduration:%(duration).3f\n"\ "start:%(start)s\nend:%(finish)s'></div>" # Add another bar to html line result += bar_html % bar_dict # Return bar-formatted html string return result def generate_gantt_chart(logfile, cores, minute_scale=10, space_between_minutes=50, colors=["#7070FF", "#4E4EB2", "#2D2D66", "#9B9BFF"]): ''' Generates a gantt chart in html showing the workflow execution based on a callback log file. This script was intended to be used with the MultiprocPlugin. The following code shows how to set up the workflow in order to generate the log file: Parameters ---------- logfile : string filepath to the callback log file to plot the gantt chart of cores : integer the number of cores given to the workflow via the 'n_procs' plugin arg minute_scale : integer (optional); default=10 the scale, in minutes, at which to plot line markers for the gantt chart; for example, minute_scale=10 means there are lines drawn at every 10 minute interval from start to finish space_between_minutes : integer (optional); default=50 scale factor in pixel spacing between minute line markers colors : list (optional) a list of colors to choose from when coloring the nodes in the gantt chart Returns ------- None the function does not return any value but writes out an html file in the same directory as the callback log path passed in Usage ----- # import logging # import logging.handlers # from nipype.pipeline.plugins.callback_log import log_nodes_cb # log_filename = 'callback.log' # logger = logging.getLogger('callback') # logger.setLevel(logging.DEBUG) # handler = logging.FileHandler(log_filename) # logger.addHandler(handler) # #create workflow # workflow = ... # workflow.run(plugin='MultiProc', # plugin_args={'n_procs':8, 'memory':12, 'status_callback': log_nodes_cb}) # generate_gantt_chart('callback.log', 8) ''' #add the html header html_string = '''<!DOCTYPE html> <head> <style> #content{ width:99%; height:100%; position:absolute; } .node{ background-color:#7070FF; border-radius: 5px; position:absolute; width:20px; white-space:pre-wrap; } .line{ position: absolute; color: #C2C2C2; opacity: 0.5; margin: 0px; } .time{ position: absolute; font-size: 16px; color: #666666; margin: 0px; } .bar{ position: absolute; height: 1px; opacity: 0.7; } .dot{ position: absolute; width: 1px; height: 1px; background-color: red; } .label { width:20px; height:20px; opacity: 0.7; display: inline-block; } </style> </head> <body> <div id="content"> <div style="display:inline-block;"> ''' close_header = ''' </div> <div style="display:inline-block;margin-left:60px;vertical-align: top;"> <p><span><div class="label" style="background-color:#90BBD7;"></div> Estimated Resource</span></p> <p><span><div class="label" style="background-color:#03969D;"></div> Actual Resource</span></p> <p><span><div class="label" style="background-color:#f00;"></div> Failed Node</span></p> </div> ''' # Read in json-log to get list of node dicts nodes_list = log_to_dict(logfile) # Create the header of the report with useful information start_node = nodes_list[0] last_node = nodes_list[-1] duration = (last_node['finish'] - start_node['start']).total_seconds() # Get events based dictionary of node run stats events = create_event_dict(start_node['start'], nodes_list) # Summary strings of workflow at top html_string += '<p>Start: ' + start_node['start'].strftime("%Y-%m-%d %H:%M:%S") + '</p>' html_string += '<p>Finish: ' + last_node['finish'].strftime("%Y-%m-%d %H:%M:%S") + '</p>' html_string += '<p>Duration: ' + "{0:.2f}".format(duration/60) + ' minutes</p>' html_string += '<p>Nodes: ' + str(len(nodes_list))+'</p>' html_string += '<p>Cores: ' + str(cores) + '</p>' html_string += close_header # Draw nipype nodes Gantt chart and runtimes html_string += draw_lines(start_node['start'], duration, minute_scale, space_between_minutes) html_string += draw_nodes(start_node['start'], nodes_list, cores, minute_scale, space_between_minutes, colors) # Get memory timeseries estimated_mem_ts = calculate_resource_timeseries(events, 'estimated_memory_gb') runtime_mem_ts = calculate_resource_timeseries(events, 'runtime_memory_gb') # Plot gantt chart resource_offset = 120 + 30*cores html_string += draw_resource_bar(start_node['start'], last_node['finish'], estimated_mem_ts, space_between_minutes, minute_scale, '#90BBD7', resource_offset*2+120, 'Memory') html_string += draw_resource_bar(start_node['start'], last_node['finish'], runtime_mem_ts, space_between_minutes, minute_scale, '#03969D', resource_offset*2+120, 'Memory') # Get threads timeseries estimated_threads_ts = calculate_resource_timeseries(events, 'estimated_threads') runtime_threads_ts = calculate_resource_timeseries(events, 'runtime_threads') # Plot gantt chart html_string += draw_resource_bar(start_node['start'], last_node['finish'], estimated_threads_ts, space_between_minutes, minute_scale, '#90BBD7', resource_offset, 'Threads') html_string += draw_resource_bar(start_node['start'], last_node['finish'], runtime_threads_ts, space_between_minutes, minute_scale, '#03969D', resource_offset, 'Threads') #finish html html_string+= ''' </div> </body>''' #save file html_file = open(logfile + '.html', 'wb') html_file.write(html_string) html_file.close()
# Copyright 2015 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. from __future__ import absolute_import from __future__ import unicode_literals from builtins import str import mock from oauth2client.client import AccessTokenCredentials import unittest import google.datalab import google.datalab.bigquery import google.datalab.utils class TestCases(unittest.TestCase): def _check_name_parts(self, dataset): parsed_name = dataset._name_parts self.assertEqual('test', parsed_name[0]) self.assertEqual('requestlogs', parsed_name[1]) self.assertEqual('test.requestlogs', dataset._full_name) self.assertEqual('test.requestlogs', str(dataset)) def test_parse_full_name(self): dataset = TestCases._create_dataset('test.requestlogs') self._check_name_parts(dataset) def test_parse_local_name(self): dataset = TestCases._create_dataset('requestlogs') self._check_name_parts(dataset) def test_parse_dict_full_name(self): dataset = TestCases._create_dataset({'project_id': 'test', 'dataset_id': 'requestlogs'}) self._check_name_parts(dataset) def test_parse_dict_local_name(self): dataset = TestCases._create_dataset({'dataset_id': 'requestlogs'}) self._check_name_parts(dataset) def test_parse_named_tuple_name(self): dataset = TestCases._create_dataset(google.datalab.bigquery._utils.DatasetName('test', 'requestlogs')) self._check_name_parts(dataset) def test_parse_tuple_full_name(self): dataset = TestCases._create_dataset(('test', 'requestlogs')) self._check_name_parts(dataset) def test_parse_tuple_local(self): dataset = TestCases._create_dataset(('requestlogs')) self._check_name_parts(dataset) def test_parse_array_full_name(self): dataset = TestCases._create_dataset(['test', 'requestlogs']) self._check_name_parts(dataset) def test_parse_array_local(self): dataset = TestCases._create_dataset(['requestlogs']) self._check_name_parts(dataset) def test_parse_invalid_name(self): with self.assertRaises(Exception): TestCases._create_dataset('today@') @mock.patch('google.datalab.bigquery._api.Api.datasets_get') def test_dataset_exists(self, mock_api_datasets_get): mock_api_datasets_get.return_value = '' dataset = TestCases._create_dataset('test.requestlogs') self.assertTrue(dataset.exists()) mock_api_datasets_get.side_effect = google.datalab.utils.RequestException(404, None) dataset._info = None self.assertFalse(dataset.exists()) @mock.patch('google.datalab.bigquery._api.Api.datasets_insert') @mock.patch('google.datalab.bigquery._api.Api.datasets_get') def test_datasets_create_fails(self, mock_api_datasets_get, mock_api_datasets_insert): mock_api_datasets_get.side_effect = google.datalab.utils.RequestException(None, 404) mock_api_datasets_insert.return_value = {} ds = TestCases._create_dataset('requestlogs') with self.assertRaises(Exception): ds.create() @mock.patch('google.datalab.bigquery._api.Api.datasets_insert') @mock.patch('google.datalab.bigquery._api.Api.datasets_get') def test_datasets_create_succeeds(self, mock_api_datasets_get, mock_api_datasets_insert): mock_api_datasets_get.side_effect = google.datalab.utils.RequestException(404, None) mock_api_datasets_insert.return_value = {'selfLink': None} ds = TestCases._create_dataset('requestlogs') self.assertEqual(ds, ds.create()) @mock.patch('google.datalab.bigquery._api.Api.datasets_insert') @mock.patch('google.datalab.bigquery._api.Api.datasets_get') def test_datasets_create_redundant(self, mock_api_datasets_get, mock_api_datasets_insert): ds = TestCases._create_dataset('requestlogs', {}) mock_api_datasets_get.return_value = None mock_api_datasets_insert.return_value = {} self.assertEqual(ds, ds.create()) @mock.patch('google.datalab.bigquery._api.Api.datasets_get') @mock.patch('google.datalab.bigquery._api.Api.datasets_delete') def test_datasets_delete_succeeds(self, mock_api_datasets_delete, mock_api_datasets_get): mock_api_datasets_get.return_value = '' mock_api_datasets_delete.return_value = None ds = TestCases._create_dataset('requestlogs') self.assertIsNone(ds.delete()) @mock.patch('google.datalab.bigquery._api.Api.datasets_get') @mock.patch('google.datalab.bigquery._api.Api.datasets_delete') def test_datasets_delete_fails(self, mock_api_datasets_delete, mock_api_datasets_get): mock_api_datasets_delete.return_value = None mock_api_datasets_get.side_effect = google.datalab.utils.RequestException(404, None) ds = TestCases._create_dataset('requestlogs') with self.assertRaises(Exception): ds.delete() @mock.patch('google.datalab.bigquery._api.Api.tables_list') def test_tables_list(self, mock_api_tables_list): mock_api_tables_list.return_value = { 'tables': [ { 'type': 'TABLE', 'tableReference': {'projectId': 'p', 'datasetId': 'd', 'tableId': 't1'} }, { 'type': 'TABLE', 'tableReference': {'projectId': 'p', 'datasetId': 'd', 'tableId': 't2'} }, ] } ds = TestCases._create_dataset('requestlogs') tables = [table for table in ds] self.assertEqual(2, len(tables)) self.assertEqual('`p.d.t1`', tables[0]._repr_sql_()) self.assertEqual('`p.d.t2`', tables[1]._repr_sql_()) @mock.patch('google.datalab.bigquery.Dataset._get_info') @mock.patch('google.datalab.bigquery._api.Api.datasets_list') def test_datasets_list(self, mock_api_datasets_list, mock_dataset_get_info): mock_api_datasets_list.return_value = { 'datasets': [ {'datasetReference': {'projectId': 'p', 'datasetId': 'd1'}}, {'datasetReference': {'projectId': 'p', 'datasetId': 'd2'}}, ] } mock_dataset_get_info.return_value = {} datasets = [dataset for dataset in google.datalab.bigquery.Datasets(TestCases._create_context())] self.assertEqual(2, len(datasets)) self.assertEqual('p.d1', str(datasets[0])) self.assertEqual('p.d2', str(datasets[1])) @mock.patch('google.datalab.bigquery._api.Api.tables_list') @mock.patch('google.datalab.bigquery._api.Api.datasets_get') @mock.patch('google.datalab.bigquery._api.Api.datasets_update') def test_datasets_update(self, mock_api_datasets_update, mock_api_datasets_get, mock_api_tables_list): mock_api_tables_list.return_value = { 'tables': [ {'type': 'TABLE', 'tableReference': {'projectId': 'p', 'datasetId': 'd', 'tableId': 't1'}}, {'type': 'TABLE', 'tableReference': {'projectId': 'p', 'datasetId': 'd', 'tableId': 't2'}}, ] } info = {'friendlyName': 'casper', 'description': 'ghostly logs'} mock_api_datasets_get.return_value = info ds = TestCases._create_dataset('requestlogs') new_friendly_name = 'aziraphale' new_description = 'demon duties' ds.update(new_friendly_name, new_description) name, info = mock_api_datasets_update.call_args[0] self.assertEqual(ds.name, name) self.assertEqual(new_friendly_name, ds.friendly_name) self.assertEqual(new_description, ds.description) @staticmethod def _create_context(): project_id = 'test' creds = AccessTokenCredentials('test_token', 'test_ua') return google.datalab.Context(project_id, creds) @staticmethod def _create_dataset(name, metadata=None): # Patch get_info so we don't have to mock it everywhere else. orig = google.datalab.bigquery.Dataset._get_info google.datalab.bigquery.Dataset._get_info = mock.Mock(return_value=metadata) ds = google.datalab.bigquery.Dataset(name, context=TestCases._create_context()) google.datalab.bigquery.Dataset._get_info = orig return ds
# -*- coding: utf-8 -*- # # 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.utils import native import flask_login from flask_login import login_required, current_user, logout_user # noqa: F401 from flask import flash from wtforms import Form, PasswordField, StringField from wtforms.validators import InputRequired from ldap3 import Server, Connection, Tls, set_config_parameter, LEVEL, SUBTREE import ssl from flask import url_for, redirect from airflow import models from airflow import configuration from airflow.configuration import AirflowConfigException from airflow.utils.db import provide_session import traceback import re from airflow.utils.log.logging_mixin import LoggingMixin login_manager = flask_login.LoginManager() login_manager.login_view = 'airflow.login' # Calls login() below login_manager.login_message = None log = LoggingMixin().log class AuthenticationError(Exception): pass class LdapException(Exception): pass def get_ldap_connection(dn=None, password=None): try: cacert = configuration.conf.get("ldap", "cacert") except AirflowConfigException: pass try: ignore_malformed_schema = configuration.conf.get("ldap", "ignore_malformed_schema") except AirflowConfigException: pass if ignore_malformed_schema: set_config_parameter('IGNORE_MALFORMED_SCHEMA', ignore_malformed_schema) tls_configuration = Tls(validate=ssl.CERT_REQUIRED, ca_certs_file=cacert) server = Server(configuration.conf.get("ldap", "uri"), use_ssl=True, tls=tls_configuration) conn = Connection(server, native(dn), native(password)) if not conn.bind(): log.error("Cannot bind to ldap server: %s ", conn.last_error) raise AuthenticationError("Cannot bind to ldap server") return conn def group_contains_user(conn, search_base, group_filter, user_name_attr, username): search_filter = '(&({0}))'.format(group_filter) if not conn.search(native(search_base), native(search_filter), attributes=[native(user_name_attr)]): log.warning("Unable to find group for %s %s", search_base, search_filter) else: for entry in conn.entries: if username.lower() in map(lambda attr: attr.lower(), getattr(entry, user_name_attr).values): return True return False def groups_user(conn, search_base, user_filter, user_name_att, username): search_filter = "(&({0})({1}={2}))".format(user_filter, user_name_att, username) try: memberof_attr = configuration.conf.get("ldap", "group_member_attr") except Exception: memberof_attr = "memberOf" res = conn.search(native(search_base), native(search_filter), attributes=[native(memberof_attr)]) if not res: log.info("Cannot find user %s", username) raise AuthenticationError("Invalid username or password") if conn.response and memberof_attr not in conn.response[0]["attributes"]: log.warning("""Missing attribute "%s" when looked-up in Ldap database. The user does not seem to be a member of a group and therefore won't see any dag if the option filter_by_owner=True and owner_mode=ldapgroup are set""", memberof_attr) return [] user_groups = conn.response[0]["attributes"][memberof_attr] regex = re.compile("cn=([^,]*).*", re.IGNORECASE) groups_list = [] try: groups_list = [regex.search(i).group(1) for i in user_groups] except IndexError: log.warning("Parsing error when retrieving the user's group(s)." " Check if the user belongs to at least one group" " or if the user's groups name do not contain special characters") return groups_list class LdapUser(models.User): def __init__(self, user): self.user = user self.ldap_groups = [] # Load and cache superuser and data_profiler settings. conn = get_ldap_connection(configuration.conf.get("ldap", "bind_user"), configuration.conf.get("ldap", "bind_password")) superuser_filter = None data_profiler_filter = None try: superuser_filter = configuration.conf.get("ldap", "superuser_filter") except AirflowConfigException: pass if not superuser_filter: self.superuser = True log.debug("Missing configuration for superuser settings or empty. Skipping.") else: self.superuser = group_contains_user(conn, configuration.conf.get("ldap", "basedn"), superuser_filter, configuration.conf.get("ldap", "user_name_attr"), user.username) try: data_profiler_filter = configuration.conf.get("ldap", "data_profiler_filter") except AirflowConfigException: pass if not data_profiler_filter: self.data_profiler = True log.debug("Missing configuration for data profiler settings or empty. " "Skipping.") else: self.data_profiler = group_contains_user( conn, configuration.conf.get("ldap", "basedn"), data_profiler_filter, configuration.conf.get("ldap", "user_name_attr"), user.username ) # Load the ldap group(s) a user belongs to try: self.ldap_groups = groups_user( conn, configuration.conf.get("ldap", "basedn"), configuration.conf.get("ldap", "user_filter"), configuration.conf.get("ldap", "user_name_attr"), user.username ) except AirflowConfigException: log.debug("Missing configuration for ldap settings. Skipping") @staticmethod def try_login(username, password): conn = get_ldap_connection(configuration.conf.get("ldap", "bind_user"), configuration.conf.get("ldap", "bind_password")) search_filter = "(&({0})({1}={2}))".format( configuration.conf.get("ldap", "user_filter"), configuration.conf.get("ldap", "user_name_attr"), username ) search_scope = LEVEL if configuration.conf.has_option("ldap", "search_scope"): if configuration.conf.get("ldap", "search_scope") == "SUBTREE": search_scope = SUBTREE else: search_scope = LEVEL # todo: BASE or ONELEVEL? res = conn.search(native(configuration.conf.get("ldap", "basedn")), native(search_filter), search_scope=native(search_scope)) # todo: use list or result? if not res: log.info("Cannot find user %s", username) raise AuthenticationError("Invalid username or password") entry = conn.response[0] conn.unbind() if 'dn' not in entry: # The search filter for the user did not return any values, so an # invalid user was used for credentials. raise AuthenticationError("Invalid username or password") try: conn = get_ldap_connection(entry['dn'], password) except KeyError: log.error(""" Unable to parse LDAP structure. If you're using Active Directory and not specifying an OU, you must set search_scope=SUBTREE in airflow.cfg. %s """ % traceback.format_exc()) raise LdapException( "Could not parse LDAP structure. " "Try setting search_scope in airflow.cfg, or check logs" ) if not conn: log.info("Password incorrect for user %s", username) raise AuthenticationError("Invalid username or password") @property def is_active(self): """Required by flask_login""" return True @property def is_authenticated(self): """Required by flask_login""" return True @property def is_anonymous(self): """Required by flask_login""" return False def get_id(self): """Returns the current user id as required by flask_login""" return self.user.get_id() def data_profiling(self): """Provides access to data profiling tools""" return self.data_profiler def is_superuser(self): """Access all the things""" return self.superuser @login_manager.user_loader @provide_session def load_user(userid, session=None): log.debug("Loading user %s", userid) if not userid or userid == 'None': return None user = session.query(models.User).filter(models.User.id == int(userid)).first() return LdapUser(user) @provide_session def login(self, request, session=None): if current_user.is_authenticated: flash("You are already logged in") return redirect(url_for('admin.index')) username = None password = None form = LoginForm(request.form) if request.method == 'POST' and form.validate(): username = request.form.get("username") password = request.form.get("password") if not username or not password: return self.render('airflow/login.html', title="Airflow - Login", form=form) try: LdapUser.try_login(username, password) log.info("User %s successfully authenticated", username) user = session.query(models.User).filter( models.User.username == username).first() if not user: user = models.User( username=username, is_superuser=False) session.add(user) session.commit() session.merge(user) flask_login.login_user(LdapUser(user)) session.commit() return redirect(request.args.get("next") or url_for("admin.index")) except (LdapException, AuthenticationError) as e: if type(e) == LdapException: flash(e, "error") else: flash("Incorrect login details") return self.render('airflow/login.html', title="Airflow - Login", form=form) class LoginForm(Form): username = StringField('Username', [InputRequired()]) password = PasswordField('Password', [InputRequired()])
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # # Copyright 2011, Piston Cloud Computing, Inc. # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Utility methods to resize, repartition, and modify disk images. Includes injection of SSH PGP keys into authorized_keys file. """ import os import random import tempfile if os.name != 'nt': import crypt from nova import exception from nova.openstack.common import cfg from nova.openstack.common import jsonutils from nova.openstack.common import log as logging from nova import paths from nova import utils from nova.virt.disk.mount import api as mount from nova.virt.disk.vfs import api as vfs from nova.virt import images LOG = logging.getLogger(__name__) disk_opts = [ cfg.StrOpt('injected_network_template', default=paths.basedir_def('nova/virt/interfaces.template'), help='Template file for injected network'), # NOTE(yamahata): ListOpt won't work because the command may include a # comma. For example: # # mkfs.ext3 -O dir_index,extent -E stride=8,stripe-width=16 # --label %(fs_label)s %(target)s # # list arguments are comma separated and there is no way to # escape such commas. # cfg.MultiStrOpt('virt_mkfs', default=[ 'default=mkfs.ext3 -L %(fs_label)s -F %(target)s', 'linux=mkfs.ext3 -L %(fs_label)s -F %(target)s', 'windows=mkfs.ntfs' ' --force --fast --label %(fs_label)s %(target)s', # NOTE(yamahata): vfat case #'windows=mkfs.vfat -n %(fs_label)s %(target)s', ], help='mkfs commands for ephemeral device. ' 'The format is <os_type>=<mkfs command>'), ] CONF = cfg.CONF CONF.register_opts(disk_opts) _MKFS_COMMAND = {} _DEFAULT_MKFS_COMMAND = None for s in CONF.virt_mkfs: # NOTE(yamahata): mkfs command may includes '=' for its options. # So item.partition('=') doesn't work here os_type, mkfs_command = s.split('=', 1) if os_type: _MKFS_COMMAND[os_type] = mkfs_command if os_type == 'default': _DEFAULT_MKFS_COMMAND = mkfs_command def mkfs(os_type, fs_label, target): mkfs_command = (_MKFS_COMMAND.get(os_type, _DEFAULT_MKFS_COMMAND) or '') % locals() if mkfs_command: utils.execute(*mkfs_command.split()) def resize2fs(image, check_exit_code=False, run_as_root=False): utils.execute('e2fsck', '-fp', image, check_exit_code=check_exit_code, run_as_root=run_as_root) utils.execute('resize2fs', image, check_exit_code=check_exit_code, run_as_root=run_as_root) def get_disk_size(path): """Get the (virtual) size of a disk image :param path: Path to the disk image :returns: Size (in bytes) of the given disk image as it would be seen by a virtual machine. """ return images.qemu_img_info(path).virtual_size def extend(image, size): """Increase image to size.""" virt_size = get_disk_size(image) if virt_size >= size: return utils.execute('qemu-img', 'resize', image, size) # NOTE(vish): attempts to resize filesystem resize2fs(image) def can_resize_fs(image, size, use_cow=False): """Check whether we can resize contained file system.""" LOG.debug(_('Checking if we can resize image %(image)s. ' 'size=%(size)s, CoW=%(use_cow)s'), locals()) # Check that we're increasing the size virt_size = get_disk_size(image) if virt_size >= size: LOG.debug(_('Cannot resize filesystem %s to a smaller size.'), image) return False # Check the image is unpartitioned if use_cow: try: fs = vfs.VFS.instance_for_image(image, 'qcow2', None) fs.setup() fs.teardown() except exception.NovaException, e: LOG.debug(_('Unable to mount image %(image)s with ' 'error %(error)s. Cannot resize.'), {'image': image, 'error': e}) return False else: # For raw, we can directly inspect the file system try: utils.execute('e2label', image) except exception.ProcessExecutionError, e: LOG.debug(_('Unable to determine label for image %(image)s with ' 'error %(errror)s. Cannot resize.'), {'image': image, 'error': e}) return False return True def bind(src, target, instance_name): """Bind device to a filesystem.""" if src: utils.execute('touch', target, run_as_root=True) utils.execute('mount', '-o', 'bind', src, target, run_as_root=True) def unbind(target): if target: utils.execute('umount', target, run_as_root=True) class _DiskImage(object): """Provide operations on a disk image file.""" tmp_prefix = 'openstack-disk-mount-tmp' def __init__(self, image, partition=None, use_cow=False, mount_dir=None): # These passed to each mounter self.image = image self.partition = partition self.mount_dir = mount_dir self.use_cow = use_cow # Internal self._mkdir = False self._mounter = None self._errors = [] if mount_dir: device = self._device_for_path(mount_dir) if device: self._reset(device) @staticmethod def _device_for_path(path): device = None path = os.path.realpath(path) with open("/proc/mounts", 'r') as ifp: for line in ifp: fields = line.split() if fields[1] == path: device = fields[0] break return device def _reset(self, device): """Reset internal state for a previously mounted directory.""" self._mounter = mount.Mount.instance_for_device(self.image, self.mount_dir, self.partition, device) mount_name = os.path.basename(self.mount_dir or '') self._mkdir = mount_name.startswith(self.tmp_prefix) @property def errors(self): """Return the collated errors from all operations.""" return '\n--\n'.join([''] + self._errors) def mount(self): """Mount a disk image, using the object attributes. The first supported means provided by the mount classes is used. True, or False is returned and the 'errors' attribute contains any diagnostics. """ if self._mounter: raise exception.NovaException(_('image already mounted')) if not self.mount_dir: self.mount_dir = tempfile.mkdtemp(prefix=self.tmp_prefix) self._mkdir = True imgfmt = "raw" if self.use_cow: imgfmt = "qcow2" mounter = mount.Mount.instance_for_format(self.image, self.mount_dir, self.partition, imgfmt) if mounter.do_mount(): self._mounter = mounter else: LOG.debug(mounter.error) self._errors.append(mounter.error) return bool(self._mounter) def umount(self): """Unmount a disk image from the file system.""" try: if self._mounter: self._mounter.do_umount() self._mounter = None finally: if self._mkdir: os.rmdir(self.mount_dir) # Public module functions def inject_data(image, key=None, net=None, metadata=None, admin_password=None, files=None, partition=None, use_cow=False, mandatory=()): """Inject the specified items into a disk image. If an item name is not specified in the MANDATORY iterable, then a warning is logged on failure to inject that item, rather than raising an exception. it will mount the image as a fully partitioned disk and attempt to inject into the specified partition number. If PARTITION is not specified the image is mounted as a single partition. Returns True if all requested operations completed without issue. Raises an exception if a mandatory item can't be injected. """ LOG.debug(_("Inject data image=%(image)s key=%(key)s net=%(net)s " "metadata=%(metadata)s admin_password=ha-ha-not-telling-you " "files=%(files)s partition=%(partition)s use_cow=%(use_cow)s") % locals()) fmt = "raw" if use_cow: fmt = "qcow2" try: fs = vfs.VFS.instance_for_image(image, fmt, partition) fs.setup() except Exception as e: # If a mandatory item is passed to this function, # then reraise the exception to indicate the error. for inject in mandatory: inject_val = locals()[inject] if inject_val: raise LOG.warn(_('Ignoring error injecting data into image ' '(%(e)s)') % locals()) return False try: return inject_data_into_fs(fs, key, net, metadata, admin_password, files, mandatory) finally: fs.teardown() def setup_container(image, container_dir, use_cow=False): """Setup the LXC container. It will mount the loopback image to the container directory in order to create the root filesystem for the container. """ img = _DiskImage(image=image, use_cow=use_cow, mount_dir=container_dir) if not img.mount(): LOG.error(_("Failed to mount container filesystem '%(image)s' " "on '%(target)s': %(errors)s") % {"image": img, "target": container_dir, "errors": img.errors}) raise exception.NovaException(img.errors) def teardown_container(container_dir): """Teardown the container rootfs mounting once it is spawned. It will umount the container that is mounted, and delete any linked devices. """ try: img = _DiskImage(image=None, mount_dir=container_dir) img.umount() except Exception, exn: LOG.exception(_('Failed to unmount container filesystem: %s'), exn) def inject_data_into_fs(fs, key, net, metadata, admin_password, files, mandatory=()): """Injects data into a filesystem already mounted by the caller. Virt connections can call this directly if they mount their fs in a different way to inject_data. If an item name is not specified in the MANDATORY iterable, then a warning is logged on failure to inject that item, rather than raising an exception. Returns True if all requested operations completed without issue. Raises an exception if a mandatory item can't be injected. """ status = True for inject in ('key', 'net', 'metadata', 'admin_password', 'files'): inject_val = locals()[inject] inject_func = globals()['_inject_%s_into_fs' % inject] if inject_val: try: inject_func(inject_val, fs) except Exception as e: if inject in mandatory: raise LOG.warn(_('Ignoring error injecting %(inject)s into image ' '(%(e)s)') % locals()) status = False return status def _inject_files_into_fs(files, fs): for (path, contents) in files: _inject_file_into_fs(fs, path, contents) def _inject_file_into_fs(fs, path, contents, append=False): LOG.debug(_("Inject file fs=%(fs)s path=%(path)s append=%(append)s") % locals()) if append: fs.append_file(path, contents) else: fs.replace_file(path, contents) def _inject_metadata_into_fs(metadata, fs): LOG.debug(_("Inject metadata fs=%(fs)s metadata=%(metadata)s") % locals()) metadata = dict([(m['key'], m['value']) for m in metadata]) _inject_file_into_fs(fs, 'meta.js', jsonutils.dumps(metadata)) def _setup_selinux_for_keys(fs, sshdir): """Get selinux guests to ensure correct context on injected keys.""" if not fs.has_file(os.path.join("etc", "selinux")): return rclocal = os.path.join('etc', 'rc.local') rc_d = os.path.join('etc', 'rc.d') if not fs.has_file(rclocal) and fs.has_file(rc_d): rclocal = os.path.join(rc_d, 'rc.local') # Note some systems end rc.local with "exit 0" # and so to append there you'd need something like: # utils.execute('sed', '-i', '${/^exit 0$/d}' rclocal, run_as_root=True) restorecon = [ '\n', '# Added by Nova to ensure injected ssh keys have the right context\n', 'restorecon -RF %s 2>/dev/null || :\n' % sshdir, ] if not fs.has_file(rclocal): restorecon.insert(0, '#!/bin/sh') _inject_file_into_fs(fs, rclocal, ''.join(restorecon), append=True) fs.set_permissions(rclocal, 0700) def _inject_key_into_fs(key, fs): """Add the given public ssh key to root's authorized_keys. key is an ssh key string. fs is the path to the base of the filesystem into which to inject the key. """ LOG.debug(_("Inject key fs=%(fs)s key=%(key)s") % locals()) sshdir = os.path.join('root', '.ssh') fs.make_path(sshdir) fs.set_ownership(sshdir, "root", "root") fs.set_permissions(sshdir, 0700) keyfile = os.path.join(sshdir, 'authorized_keys') key_data = ''.join([ '\n', '# The following ssh key was injected by Nova', '\n', key.strip(), '\n', ]) _inject_file_into_fs(fs, keyfile, key_data, append=True) _setup_selinux_for_keys(fs, sshdir) def _inject_net_into_fs(net, fs): """Inject /etc/network/interfaces into the filesystem rooted at fs. net is the contents of /etc/network/interfaces. """ LOG.debug(_("Inject key fs=%(fs)s net=%(net)s") % locals()) netdir = os.path.join('etc', 'network') fs.make_path(netdir) fs.set_ownership(netdir, "root", "root") fs.set_permissions(netdir, 0744) netfile = os.path.join('etc', 'network', 'interfaces') _inject_file_into_fs(fs, netfile, net) def _inject_admin_password_into_fs(admin_passwd, fs): """Set the root password to admin_passwd admin_password is a root password fs is the path to the base of the filesystem into which to inject the key. This method modifies the instance filesystem directly, and does not require a guest agent running in the instance. """ # The approach used here is to copy the password and shadow # files from the instance filesystem to local files, make any # necessary changes, and then copy them back. LOG.debug(_("Inject admin password fs=%(fs)s " "admin_passwd=ha-ha-not-telling-you") % locals()) admin_user = 'root' fd, tmp_passwd = tempfile.mkstemp() os.close(fd) fd, tmp_shadow = tempfile.mkstemp() os.close(fd) passwd_path = os.path.join('etc', 'passwd') shadow_path = os.path.join('etc', 'shadow') passwd_data = fs.read_file(passwd_path) shadow_data = fs.read_file(shadow_path) new_shadow_data = _set_passwd(admin_user, admin_passwd, passwd_data, shadow_data) fs.replace_file(shadow_path, new_shadow_data) def _generate_salt(): salt_set = ('abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' '0123456789./') salt = 16 * ' ' return ''.join([random.choice(salt_set) for c in salt]) def _set_passwd(username, admin_passwd, passwd_data, shadow_data): """set the password for username to admin_passwd The passwd_file is not modified. The shadow_file is updated. if the username is not found in both files, an exception is raised. :param username: the username :param encrypted_passwd: the encrypted password :param passwd_file: path to the passwd file :param shadow_file: path to the shadow password file :returns: nothing :raises: exception.NovaException(), IOError() """ if os.name == 'nt': raise exception.NovaException(_('Not implemented on Windows')) # encryption algo - id pairs for crypt() algos = {'SHA-512': '$6$', 'SHA-256': '$5$', 'MD5': '$1$', 'DES': ''} salt = _generate_salt() # crypt() depends on the underlying libc, and may not support all # forms of hash. We try md5 first. If we get only 13 characters back, # then the underlying crypt() didn't understand the '$n$salt' magic, # so we fall back to DES. # md5 is the default because it's widely supported. Although the # local crypt() might support stronger SHA, the target instance # might not. encrypted_passwd = crypt.crypt(admin_passwd, algos['MD5'] + salt) if len(encrypted_passwd) == 13: encrypted_passwd = crypt.crypt(admin_passwd, algos['DES'] + salt) p_file = passwd_data.split("\n") s_file = shadow_data.split("\n") # username MUST exist in passwd file or it's an error found = False for entry in p_file: split_entry = entry.split(':') if split_entry[0] == username: found = True break if not found: msg = _('User %(username)s not found in password file.') raise exception.NovaException(msg % username) # update password in the shadow file.It's an error if the # the user doesn't exist. new_shadow = list() found = False for entry in s_file: split_entry = entry.split(':') if split_entry[0] == username: split_entry[1] = encrypted_passwd found = True new_entry = ':'.join(split_entry) new_shadow.append(new_entry) if not found: msg = _('User %(username)s not found in shadow file.') raise exception.NovaException(msg % username) return "\n".join(new_shadow)
# Copyright 2014 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 telemetry.page import page as page_module from telemetry import story class KeyDesktopSitesPage(page_module.Page): def __init__(self, url, page_set): super(KeyDesktopSitesPage, self).__init__( url=url, page_set=page_set, credentials_path = 'data/credentials.json') self.archive_data_file = 'data/key_desktop_sites.json' def RunPageInteractions(self, action_runner): with action_runner.CreateGestureInteraction('ScrollAction'): action_runner.ScrollPage() class FacebookPage(KeyDesktopSitesPage): def __init__(self, page_set): super(FacebookPage, self).__init__( url='http://facebook.com', page_set=page_set) self.credentials = 'facebook' class GmailPage(KeyDesktopSitesPage): def __init__(self, page_set): super(GmailPage, self).__init__( url='https://mail.google.com/mail/', page_set=page_set) self.scrollable_element_function = ''' function(callback) { gmonkey.load('2.0', function(api) { callback(api.getScrollableElement()); }); }''' self.credentials = 'google' def RunPageInteractions(self, action_runner): with action_runner.CreateGestureInteraction('ScrollAction'): action_runner.ScrollPage() action_runner.WaitForJavaScriptCondition( 'window.gmonkey !== undefined && ' 'document.getElementById("gb") !== null') class GoogleCalendarPage(KeyDesktopSitesPage): def __init__(self, page_set): super(GoogleCalendarPage, self).__init__( url='https://www.google.com/calendar/', page_set=page_set) self.scrollable_element_function = ''' function(callback) { callback(document.getElementById('scrolltimedeventswk')); }''' self.credentials = 'google' class GoogleDrivePage(KeyDesktopSitesPage): def __init__(self, page_set): super(GoogleDrivePage, self).__init__( url='https://drive.google.com', page_set=page_set) self.scrollable_element_function = ''' function(callback) { callback(document.getElementsByClassName('doclistview-list')[0]); }''' self.credentials = 'google' def RunPageInteractions(self, action_runner): with action_runner.CreateGestureInteraction('ScrollAction'): action_runner.ScrollPage() action_runner.WaitForJavaScriptCondition( 'document.getElementsByClassName("doclistview-list").length') class GoogleDocPage(KeyDesktopSitesPage): def __init__(self, page_set): super(GoogleDocPage, self).__init__( # pylint: disable=C0301 url='https://docs.google.com/a/google.com/document/d/1XMAtPiVFZfItsMUOYl39v5YA8bcSPe4LDrVO25OdsCU/edit', page_set=page_set) self.scrollable_element_function = ''' function(callback) { callback(document.getElementsByClassName('kix-appview-editor')[0]); }''' self.credentials = 'google' def RunPageInteractions(self, action_runner): with action_runner.CreateGestureInteraction('ScrollAction'): action_runner.ScrollPage() action_runner.WaitForJavaScriptCondition( 'document.getElementsByClassName("kix-appview-editor").length') class KeyDesktopSitesPageSet(story.StorySet): """ Sites of Interest """ def __init__(self): super(KeyDesktopSitesPageSet, self).__init__( archive_data_file='data/key_desktop_sites.json', cloud_storage_bucket=story.PARTNER_BUCKET) self.AddUserStory(FacebookPage(self)) self.AddUserStory(GmailPage(self)) self.AddUserStory(GoogleCalendarPage(self)) self.AddUserStory(GoogleDrivePage(self)) self.AddUserStory(GoogleDocPage(self)) urls_list = [ 'http://www.google.com/nexus/5/#/', 'http://youtube.com', 'http://twitter.com/nbc', 'http://bbc.co.uk', 'http://imdb.com', 'http://espn.go.com', 'http://cnn.com', 'http://bbc.co.uk/news/', 'http://weather.com', 'http://livejournal.com', 'http://deviantart.com', 'http://foxnews.com', 'http://nbcnews.com', 'http://scribd.com', 'http://movies.yahoo.com', 'http://tv.yahoo.com', 'http://pandora.com', 'http://tmz.com', 'http://hulu.com', 'http://abcnews.go.com', 'http://youtube.com/videos', 'http://ndtv.com', 'http://money.cnn.com', 'http://msn.foxsports.com', 'http://cbsnews.com', 'http://wired.com', 'http://cnbc.com', 'http://sportsillustrated.cnn.com', 'http://home.disney.go.com', 'http://urbandictionary.com', 'http://rottentomatoes.com', 'http://foodnetwork.com', 'http://npr.org', 'http://gawker.com', 'http://last.fm', 'http://sky.com', 'http://eonline.com', 'http://egotastic.com', 'http://copyscape.com', 'http://mtv.com', 'http://ultimate-guitar.com', 'http://comcast.com', 'http://cbc.ca', 'http://fanfiction.net', 'http://discovery.com', 'http://deezer.com', 'http://metrolyrics.com', 'http://foxnews.com/entertainment/', 'http://cartoonnetwork.com', 'http://paypal.com', 'http://finance.yahoo.com', 'http://alibaba.com', 'http://bankofamerica.com', 'http://www.chase.com/', 'http://wellsfargo.com', 'http://skype.com', 'http://online.wsj.com', 'http://indeed.com', 'http://samsung.com', 'http://reuters.com', 'http://ups.com', 'http://forbes.com', 'http://clickbank.com', 'http://target.com', 'http://att.com', 'http://cj.com', 'http://constantcontact.com', 'http://ezinearticles.com', 'http://shutterstock.com', 'http://americanexpress.com', 'http://freelancer.com', 'http://istockphoto.com', 'http://fedex.com', 'http://verizonwireless.com', 'http://capitalone.com', 'http://bloomberg.com', 'http://monster.com', 'http://hdfcbank.com', 'http://fotolia.com', 'http://thesun.co.uk', 'http://zillow.com', 'http://nokia.com', 'http://tradedoubler.com', 'http://icicibank.com', 'http://123rf.com', 'http://elance.com', 'http://icbc.com.cn', 'http://news.cnet.com', 'http://verizon.com', 'http://careerbuilder.com', 'http://sears.com', 'http://getresponse.com', 'http://sitesell.com', 'http://manta.com', 'http://www.blogger.com/', 'http://avg.com', 'http://google.com/analytics/', 'http://go.com', 'http://flickr.com', 'http://aol.com', 'http://thepiratebay.se', 'http://zedo.com', 'http://about.com', 'http://stackoverflow.com', 'http://godaddy.com', 'http://mediafire.com', 'http://wordpress.org', 'http://adwords.google.com', 'http://imgur.com', 'http://4shared.com', 'http://vimeo.com', 'http://play.google.com/', 'http://badoo.com', 'http://aweber.com', 'http://mozilla.org', 'http://www.stumbleupon.com/stumbler/chimacintosh', 'http://www.google.com/adsense/', 'http://my.yahoo.com', 'http://sourceforge.net', 'http://answers.com', 'http://wordpress.org/extend/plugins/', 'http://photobucket.com', 'http://clicksor.com', 'http://google.com/reader/', 'http://store.apple.com', 'http://wikia.com', 'http://statcounter.com', 'http://fiverr.com', 'http://slideshare.net', 'http://salesforce.com', 'http://myspace.com', 'http://hootsuite.com', 'http://domaintools.com', 'http://rediff.com', 'http://soundcloud.com', 'http://download.cnet.com', 'http://archive.org', 'http://filestube.com', 'http://developers.facebook.com', 'http://hostgator.com', 'http://battle.net', 'http://pch.com', 'http://ign.com', 'http://pogo.com', 'http://miniclip.com', 'http://888.com', 'http://gamespot.com', 'http://steampowered.com', 'http://gamefaqs.com', 'http://xbox.com', 'http://games.yahoo.com', 'http://betfair.com', 'http://kongregate.com', 'http://ea.com', 'http://leagueoflegends.com', 'http://roblox.com', 'http://williamhill.com', 'http://playstation.com', 'http://wowhead.com', 'http://king.com', 'http://minecraft.net', 'http://chess.com', 'http://minecraftwiki.net', 'http://addictinggames.com', 'http://mmo-champion.com', 'http://runescape.com', 'http://travian.com', 'http://zone.msn.com', 'http://ubi.com', 'http://calottery.com', 'http://freeonlinegames.com', 'http://games.com', 'http://n4g.com', 'http://nvidia.com', 'http://callofduty.com', 'http://us.playstation.com', 'http://bet-at-home.com', 'http://gametrailers.com', 'http://teamliquid.net', 'http://nick.com/games/', 'http://planetminecraft.com', 'http://nintendo.com', 'http://popcap.com', 'http://gamehouse.com', 'http://curse.com', 'http://bulbagarden.net', 'http://rockstargames.com', 'http://partycasino.com', 'http://square-enix.com', 'http://perfectworld.com', 'http://nih.gov', 'http://webmd.com', 'http://ncbi.nlm.nih.gov/pubmed/', 'http://focusoncrohnsdisease.com', 'http://mayoclinic.com', 'http://mercola.com', 'http://drugs.com', 'http://menshealth.com', 'http://nlm.nih.gov/medlineplus/', 'http://weightwatchers.com', 'http://cdc.gov', 'http://caloriecount.about.com', 'http://patents.uspto.gov', 'http://psychologytoday.com', 'http://nhs.uk', 'http://medscape.com', 'http://foxnews.com/health/', 'http://who.int', 'http://healthboards.com', 'http://self.com', 'http://health.com', 'http://kidshealth.org', 'http://fda.gov', 'http://netdoctor.co.uk', 'http://prevention.com', 'http://makeupalley.com', 'http://stevepavlina.com', 'http://realage.com', 'http://fitnessmagazine.com', 'http://healthcentral.com', 'http://rxlist.com', 'http://vitals.com', 'http://totalbeauty.com', 'http://nuance.com', 'http://telegraph.co.uk/health/', 'http://drbatras.com', 'http://emedtv.com', 'http://bmj.com', 'http://medcohealth.com', 'http://webmd.com/skin-problems-and-treatments/default.htm', 'http://tums.ac.ir', 'http://apa.org', 'http://cancer.org', 'http://healthguru.com', 'http://earthclinic.com', 'http://curezone.com', 'http://beauty.about.com', 'http://www.kaiserpermanente.org/', 'http://drweil.com', 'http://24hourfitness.com', 'http://ehow.com', 'http://yelp.com', 'http://groupon.com/san-francisco', 'http://engadget.com', 'http://gsmarena.com', 'http://reviews.cnet.com', 'http://allrecipes.com', 'http://autos.yahoo.com', 'http://shopping.yahoo.com', 'http://gizmodo.com', 'http://marketwatch.com', 'http://babycenter.com', 'http://nextag.com', 'http://fixya.com', 'http://dpreview.com', 'http://tomshardware.com', 'http://theverge.com', 'http://instructables.com', 'http://cafemom.com', 'http://google.com/products', 'http://bbb.org', 'http://shopping.com', 'http://irs.gov', 'http://kbb.com', 'http://retailmenot.com', 'http://edmunds.com', 'http://mobile9.com', 'http://bankrate.com', 'http://fatwallet.com', 'http://fool.com', 'http://hgtv.com', 'http://coupons.com', 'http://apartmenttherapy.com', 'http://phonearena.com', 'http://shopzilla.com', 'http://marthastewart.com', 'http://consumerreports.org', 'http://pricegrabber.com', 'http://epinions.com', 'http://cooks.com', 'http://bhg.com', 'http://mouthshut.com', 'http://travel.state.gov', 'http://realsimple.com', 'http://opendns.com', 'http://gardenweb.com', 'http://blu-ray.com', 'http://thesaurus.com', 'http://espncricinfo.com', 'http://weebly.com', 'http://bbc.co.uk/sport/0/football/', 'http://y8.com', 'http://xe.com/ucc/', 'http://timeanddate.com', 'http://soccernet.espn.go.com', 'http://howstuffworks.com', 'http://en.wikipedia.org/wiki/Main_Page', 'http://reverso.net', 'http://timeanddate.com/worldclock/', 'http://sitepoint.com', 'http://usopen.org', 'http://stardoll.com', 'http://london2012.com', 'http://lego.com', 'http://000webhost.com', 'http://fifa.com', 'http://uefa.com', 'http://nick.com', 'http://girlsgogames.com', 'http://pbskids.org', 'http://thestar.com', 'http://dynamicdrive.com', 'http://nickjr.com', 'http://manutd.com', 'http://earthquake.usgs.gov', 'http://khanacademy.org', 'http://barbie.com', 'http://sciencedaily.com', 'http://gocomics.com', 'http://webdeveloper.com', 'http://www2.warnerbros.com', 'http://jpl.nasa.gov', 'http://yola.com', 'http://bom.gov.au', 'http://nationalpost.com', 'http://booking.com', 'http://tripadvisor.com', 'http://agoda.com', 'http://xe.com', 'http://expedia.com', 'http://metacafe.com', 'http://priceline.com', 'http://southwest.com', 'http://cracked.com', 'http://kayak.com', 'http://travelocity.com', 'http://united.com', 'http://delta.com', 'http://ryanair.com', 'http://lonelyplanet.com', 'http://orbitz.com', 'http://aa.com', 'http://easyjet.com', 'http://hilton.com', 'http://travel.yahoo.com', 'http://marriott.com', 'http://couchsurfing.org', 'http://hotwire.com', 'http://autoblog.com', 'http://lufthansa.com', 'http://theonion.com', 'http://britishairways.com', 'http://travelzoo.com', 'http://ebaumsworld.com', 'http://emirates.com', 'http://venere.com', 'http://wikitravel.org', 'http://jal.co.jp', 'http://collegehumor.com', 'http://ford.com', 'http://vrbo.com', 'http://opentable.com', 'http://hyatt.com', 'http://klm.com', 'http://airberlin.com', 'http://usairways.com', 'http://skyscanner.net', 'http://timeout.com', 'http://homeaway.com', 'http://lonelyplanet.com/thorntree/', 'http://virgin-atlantic.com', 'http://news.yahoo.com', 'http://huffingtonpost.com', 'http://news.google.com', 'http://reddit.com', 'http://guardian.co.uk', 'http://timesofindia.indiatimes.com', 'http://washingtonpost.com', 'http://usatoday.com', 'http://drudgereport.com', 'http://latimes.com', 'http://wunderground.com', 'http://accuweather.com', 'http://examiner.com', 'http://news.com.au', 'http://time.com', 'http://alarabiya.net', 'http://businessweek.com', 'http://smh.com.au', 'http://weather.yahoo.com', 'http://foxnews.com/politics/', 'http://economictimes.indiatimes.com', 'http://nationalgeographic.com', 'http://ft.com', 'http://nypost.com', 'http://sfgate.com', 'http://topix.com', 'http://hindustantimes.com', 'http://chicagotribune.com', 'http://newsmax.com', 'http://breitbart.com', 'http://economist.com', 'http://theatlantic.com', 'http://prweb.com', 'http://theglobeandmail.com', 'http://answers.yahoo.com', 'http://wiki.answers.com', 'http://wordreference.com', 'http://thefreedictionary.com', 'http://dict.leo.org', 'http://w3.org', 'http://nlm.nih.gov', 'http://goodreads.com', 'http://mapquest.com', 'http://yellowpages.com', 'http://wiktionary.org', 'http://dict.cc', 'http://bing.com/maps/', 'http://whitepages.com', 'http://m-w.com', 'http://classmates.com', 'http://blackboard.com', 'http://justanswer.com', 'http://mit.edu', 'http://medterms.com', 'http://stanford.edu', 'http://brainyquote.com', 'http://harvard.edu', 'http://superpages.com', 'http://mylife.com', 'http://en.wiktionary.org', 'http://investopedia.com', 'http://lumosity.com', 'http://phoenix.edu', 'http://berkeley.edu', 'http://ecollege.com', 'http://ed.gov', 'http://yellowpages.sulekha.com', 'http://wisegeek.com', 'http://utexas.edu', 'http://wwp.greenwichmeantime.com', 'http://cornell.edu', 'http://psu.edu', 'http://maps.yahoo.com', 'http://linkedin.com/answers', 'http://yahoo.co.jp', 'http://translate.google.com', 'http://noaa.gov', 'http://ncbi.nlm.nih.gov', 'http://nhc.noaa.gov', 'http://ted.com', 'http://jma.go.jp', 'http://usgs.gov', 'http://care2.com', 'http://sciencedirect.com', 'http://intellicast.com', 'http://guardian.co.uk/technology', 'http://nature.com', 'http://wunderground.com/tropical/', 'http://ieee.org', 'http://elsevier.com', 'http://usda.gov', 'http://redorbit.com', 'http://scientificamerican.com', 'http://nps.gov', 'http://metoffice.gov.uk', 'http://space.com', 'http://foreignpolicy.com', 'http://bbc.co.uk/news/technology/', 'http://newscientist.com', 'http://livescience.com', 'http://jstor.org', 'http://mnn.com', 'http://foxnews.com/scitech/', 'http://census.gov', 'http://epa.gov', 'http://bls.gov', 'http://metric-conversions.org', 'http://news.nationalgeographic.com/index.rss', 'http://bbc.co.uk/news/science_and_environment/', 'http://colorado.edu', 'http://popsci.com', 'http://amazon.com', 'http://ebay.com', 'http://netflix.com', 'http://amazon.co.uk', 'http://walmart.com', 'http://ikea.com', 'http://bestbuy.com', 'http://multiply.com', 'http://newegg.com', 'http://homedepot.com', 'http://macys.com', 'http://livingsocial.com', 'http://gap.com', 'http://bodybuilding.com', 'http://kohls.com', 'http://barnesandnoble.com', 'http://lowes.com', 'http://zappos.com', 'http://overstock.com', 'http://legacy.com', 'http://staples.com', 'http://shutterfly.com', 'http://nike.com', 'http://nordstrom.com', 'http://pixmania.com', 'http://costco.com', 'http://bhphotovideo.com', 'http://hm.com', 'http://ticketmaster.com', 'http://jcpenney.com', 'http://walgreens.com', 'http://qvc.com', 'http://autotrader.com', 'http://tigerdirect.com', 'http://trademe.co.nz', 'http://sony.com', 'http://directv.com', 'http://buy.com', 'http://victoriassecret.com', 'http://cars.com', 'http://gamestop.com', 'http://cvs.com', 'http://dealextreme.com', 'http://cafepress.com', 'http://6pm.com', 'http://facebook.com/home.php#!/OccupyAirForce', 'http://deviantart.com/#catpath=anthro', 'http://shine.yahoo.com', 'http://match.com', 'http://siteadvisor.com', 'http://digg.com', 'http://hi5.com', 'http://ancestry.com', 'http://sulekha.com', 'http://europa.eu', 'http://biblegateway.com', 'http://slate.com', 'http://correios.com.br', 'http://wonderwall.msn.com', 'http://change.org', 'http://state.gov', 'http://salon.com', 'http://askmen.com', 'http://infowars.com', 'http://wnd.com', 'http://ec.europa.eu', 'http://justjared.com', 'http://sheknows.com', 'http://slashdot.org', 'http://newgrounds.com', 'http://weeklystandard.com', 'http://royalmail.com', 'http://snopes.com', 'http://lds.org', 'http://dailykos.com', 'http://complex.com', 'http://avaaz.org', 'http://aarp.org', 'http://theregister.co.uk', 'http://creativecommons.org', 'http://jw.org', 'http://peoplesmart.com', 'http://uspto.gov', 'http://uscis.gov', 'http://whitehouse.gov', 'http://townhall.com', 'http://sec.gov', 'http://sports.yahoo.com', 'http://nfl.com', 'http://mlb.mlb.com', 'http://cbssports.com', 'http://bleacherreport.com', 'http://livescore.com', 'http://espn.go.com/nfl/', 'http://sports.yahoo.com/nfl', 'http://espn.go.com/mlb/', 'http://premierleague.com', 'http://skysports.com', 'http://sports.yahoo.com/mlb', 'http://games.espn.go.com/frontpage', 'http://uk.eurosport.yahoo.com', 'http://baseball.fantasysports.yahoo.com', 'http://baseball.fantasysports.yahoo.com/b1', 'http://skysports.com/football/', 'http://nba.com', 'http://hattrick.org', 'http://wwe.com', 'http://telegraph.co.uk/sport/', 'http://rivals.com', 'http://sports.yahoo.com/fantasy', 'http://espn.go.com/nba/', 'http://scout.com', 'http://msn.foxsports.com/nfl', 'http://sports.yahoo.com/nfl/players/', 'http://guardian.co.uk/football', 'http://rotoworld.com', 'http://nascar.com', 'http://arsenal.com', 'http://formula1.com', 'http://yardbarker.com', 'http://pgatour.com', 'http://rei.com', 'http://liverpoolfc.tv', 'http://deadspin.com', 'http://sbnation.com', 'https://www.google.com', 'https://www.google.com/search?q=barack%20obama', 'https://maps.google.com', 'http://reader.google.com', 'https://plus.google.com/110031535020051778989/posts/2wP4KPPBMG8', 'https://plus.google.com/110031535020051778989/photos', 'http://googleblog.blogspot.com/', 'https://chrome.google.com/webstore/category/home', 'http://staff.tumblr.com/', 'http://mashable.com/', 'http://www.buzzfeed.com/celebrity', 'http://www.thedailybeast.com/', 'http://www.theverge.com/', 'http://techcrunch.com/', 'http://www.engadget.com/', 'http://gizmodo.com/', 'http://thinkprogress.org/?mobile=nc', 'http://gawker.com/', 'http://arstechnica.com/', 'http://boingboing.net/category/featured/', 'http://thenextweb.com/', 'http://politicalticker.blogs.cnn.com/', 'http://deadspin.com/', 'http://news.yahoo.com/', 'http://www.cnn.com/', 'http://www.nbcnews.com/', 'http://www.bbc.co.uk/news/', 'http://www.reddit.com/', 'http://my.yahoo.com/', 'http://www.foxnews.com/', 'http://www.guardiannews.com/uk-home', 'http://timesofindia.indiatimes.com/', 'http://online.wsj.com/home-page', 'http://www.forbes.com/home_usa/', 'http://www.washingtonpost.com/', 'http://www.usatoday.com/', 'http://drudgereport.com/', 'http://abcnews.go.com/', 'http://www.latimes.com/', 'http://www.bloomberg.com/', 'http://money.cnn.com/', 'http://www.news.com.au/', 'http://www.cbsnews.com/', 'http://www.examiner.com/', 'http://www.cnbc.com/', 'http://www.alarabiya.net/default.html', 'http://www.time.com/time/', 'http://www.foxnews.com/politics/index.html', 'http://www.smh.com.au/', 'http://www.businessweek.com/', 'http://www.nationalgeographic.com/', # pylint: disable=C0301 'http://www.wunderground.com/cgi-bin/findweather/getForecast?query=94035&sp=KCAMOUNT24', # pylint: disable=C0301 'http://www.accuweather.com/en/search-locations?zipcode=mountain%20view,%20ca', 'http://www.weather.com/weather/right-now/Mountain+View+CA+94043', # pylint: disable=C0301 'http://weather.yahoo.com/united-states/california/mountain-view-12797130/', 'http://www.yr.no/place/Norway/Oslo/Oslo/Oslo/', 'http://www.metoffice.gov.uk/', 'http://www.intellicast.com/Local/Weather.aspx?location=USCA0746', # pylint: disable=C0301 'http://www.shutterstock.com/cat.mhtml?searchterm=google&search_group=&lang=en&search_source=search_form', 'http://www.flickr.com/search/?q=monkeys&f=hp', # pylint: disable=C0301 'http://www.flickr.com/photos/davidgutierrez/sets/72157604615916402/?page=3', # pylint: disable=C0301 'http://www.flickr.com/photos/davidgutierrez/sets/72157604615916402/show/with/4403158307/', 'http://www.apple.com/iphone/', 'http://www.taobao.com/index_global.php', 'http://hootsuite.com/', 'http://www.android.com/', 'https://www.change.org/', 'http://www.nytimes.com/skimmer/#/Technology', 'http://www.glennbeck.com/', 'http://www.pengyou.com/mobile?from=loginAndroid', 'http://en.wikipedia.org/wiki/Cat', 'http://en.wikipedia.org/wiki/British_Royal_Family', 'http://9gag.com/gag/5202885', 'http://www.wowwiki.com/World_of_Warcraft:_Mists_of_Pandaria', 'http://twitter.github.com/bootstrap/', # pylint: disable=C0301 'http://reviews.cnet.com/8301-13727_7-57431192-263/disable-elastic-scrolling-in-os-x/', 'http://mlb.com', 'http://thenounproject.com/zh-cn/', 'http://allrecipes.com/recipe/chicken-pot-pie-ix/', 'http://www.gamespot.com/', 'http://valleywag.com/', # pylint: disable=C0301 'http://gawker.com/5939683/based-on-a-true-story-is-a-rotten-lie-i-hope-you-never-believe', 'http://www.imdb.com/title/tt0910970/', 'http://www.html5rocks.com/en/', # pylint: disable=C0301 'http://athome.kimvallee.com/2010/03/why-to-splurge-on-a-high-end-dishwasher/', ('http://mlb.mlb.com/mlb/gameday/index.jsp?gid=2012_08_31_sfnmlb_chnmlb_1' '&mode=wrap#gid=2012_08_31_sfnmlb_chnmlb_1&mode=box'), 'http://nytimes.com', 'http://arstechnica.com', 'http://pinterest.com', 'http://www.theregister.co.uk/', 'http://forum.xda-developers.com/', 'http://maps.google.com', 'https://www.google.com/search?num=10&hl=en&site=&tbm=isch&q=cats', 'http://code.google.com/p/chromium/issues/list', ('http://code.google.com/p/chromium/issues/detail?id=142038' '&q=black%20screen%20amd&colspec=ID%20Pri%20Mstone%20ReleaseBlock%20OS' '%20Area%20Feature%20Status%20Owner%20Summary'), 'http://mlb.mlb.com/index.jsp', 'http://www.nfl.com/', 'http://airbnb.github.com/infinity/demo-on.html', 'http://habrahabr.ru/post/149892/#habracut' ] for url in urls_list: self.AddUserStory(KeyDesktopSitesPage(url, self))
#!/usr/bin/python # # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER # # Copyright (c) 2016, Juniper Networks, Inc. All rights reserved. # # # The contents of this file are subject to the terms of the BSD 3 clause # License (the "License"). You may not use this file except in compliance # with the License. # # You can obtain a copy of the license at # https://github.com/Juniper/warp17/blob/master/LICENSE. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from this # software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # File name: # warp17_xlate_gen.py # # Description: # protoc plugin which will generate a translation layer between protoc-c # generated structures and what WARP17 needs. # # Author: # Dumitru Ceara, Eelco Chaudron # # Initial Created: # 01/15/2016 # # Notes: # # import sys sys.path.append('./generated/py/') import re from google.protobuf.compiler import plugin_pb2 as plugin from google.protobuf.descriptor_pb2 import FieldDescriptorProto from warp17_common_pb2 import warp17_xlate_tpg from warp17_xlate_walker import * XLATE_H = '.xlate.h' XLATE_C = '.xlate.c' def cstringify(str): return str.replace('-', '_').replace('.', '_').upper() def uncamel(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() def extract_name(name): (_, _, result) = name.partition('.') if result is None: raise Warp17ParseException('Invalid name: ' + str(name)) return result def extract_field_name(field): return extract_name(field.type_name) def line(s): return s + '\n' def gen_h_guard_name(filename): return 'H_WARP17_RPC_GEN__' + cstringify(filename) + '_' def gen_guard_begin(guard_name): return line('#ifndef ' + guard_name) + \ line('#define ' + guard_name) def gen_guard_end(guard_name): return line(line('#endif /* ' + guard_name + ' */')) def gen_h_include(filename): return line(line('#include "' + filename + '"')) def gen_standard_includes(): return \ line('#include <stdbool.h>') + \ line('#include <stdint.h>') + \ line('#include <string.h>') + \ line('#include <errno.h>') + \ line('#include <rte_malloc.h>') def gen_name(name): return 'tpg_' + uncamel(name) + '_s' def gen_fwname(name): return 'tpg_' + uncamel(name) + '_t' def gen_protoc_name_init(name): return '(' + name + ')' + uncamel(name).upper() + '__INIT' def gen_xlate_protoc_name(name): return 'tpg_xlate_protoc_' + name def gen_xlate_tpg_name(name): return 'tpg_xlate_tpg_' + name def gen_xlate_tpg_union_name(name): return 'tpg_xlate_tpg_union_' + name def gen_xlate_free_name(name): return 'tpg_xlate_free_' + name def gen_xlate_tpg_free_name(name): return 'tpg_xlate_tpg_free_' + name def gen_xlate_default_name(name): return 'tpg_xlate_default_' + name def gen_sig(name, ret_type, decls): return ret_type + ' ' + name + '(' + ', '.join(decls) + ')' def gen_xlate_sig(name, ret_type, in_name, out_name): return gen_sig(name, ret_type, [gen_decl('const ' + in_name + '*', 'in'), gen_decl(out_name + '*', 'out')]) def gen_xlate_protoc_sig(name): return gen_xlate_sig(gen_xlate_protoc_name(name), 'int', name, gen_fwname(name)) def gen_xlate_tpg_sig(name): return gen_xlate_sig(gen_xlate_tpg_name(name), 'int', gen_fwname(name), name) def gen_xlate_tpg_union_sig(name): return gen_xlate_sig(gen_xlate_tpg_union_name(name), 'int', gen_fwname(name), name) def gen_xlate_free_sig(name): return gen_sig(gen_xlate_free_name(name), 'void', [gen_decl(name + '*', 'ptr')]) def gen_xlate_tpg_free_sig(name): return gen_sig(gen_xlate_tpg_free_name(name), 'void', [gen_decl(gen_fwname(name) + '*', 'ptr')]) def gen_xlate_default_sig(name): return gen_sig(gen_xlate_default_name(name), 'void', [gen_decl(gen_fwname(name) + '*', 'out')]) def gen_xlate_protoc_h(item): return line(line(gen_xlate_protoc_sig(item.name) + ';')) def gen_xlate_tpg_h(item): return line(line(gen_xlate_tpg_sig(item.name) + ';')) def gen_xlate_tpg_union_h(item): return line(line(gen_xlate_tpg_union_sig(item.name) + ';')) def gen_xlate_free_h(item): return line(line(gen_xlate_free_sig(item.name) + ';')) def gen_xlate_tpg_free_h(item): return line(line(gen_xlate_tpg_free_sig(item.name) + ';')) def gen_xlate_default_h(item): return line(line(gen_xlate_default_sig(item.name) + ';')) def gen_xlate_h(item): return gen_xlate_protoc_h(item) + \ gen_xlate_tpg_h(item) + \ gen_xlate_tpg_union_h(item) + \ gen_xlate_free_h(item) + \ gen_xlate_tpg_free_h(item) + \ gen_xlate_default_h(item) def gen_xlate_guard_name(name): return 'TPG_XLATE_' + cstringify(name) def xlate_gen_guard_begin(name): return line('#ifndef ' + name) def xlate_gen_guard_end(name): return line('#endif /* ' + name + ' */') def gen_message_type(field): return gen_fwname(extract_field_name(field)) def is_type_ptr(t): return t == FieldDescriptorProto.TYPE_BYTES or \ t == FieldDescriptorProto.TYPE_STRING def is_type_str(t): return t == FieldDescriptorProto.TYPE_STRING def gen_type(field): type_str = { FieldDescriptorProto.TYPE_BOOL : 'bool', FieldDescriptorProto.TYPE_BYTES : 'char *', FieldDescriptorProto.TYPE_DOUBLE : 'double', FieldDescriptorProto.TYPE_ENUM : gen_message_type(field), FieldDescriptorProto.TYPE_FIXED32 : 'uint32_t', FieldDescriptorProto.TYPE_FIXED64 : 'uint64_t', FieldDescriptorProto.TYPE_FLOAT : 'float', FieldDescriptorProto.TYPE_INT32 : 'int32_t', FieldDescriptorProto.TYPE_INT64 : 'int64_t', FieldDescriptorProto.TYPE_MESSAGE : gen_message_type(field), FieldDescriptorProto.TYPE_SFIXED32 : 'int32_t', FieldDescriptorProto.TYPE_SFIXED64 : 'int64_t', FieldDescriptorProto.TYPE_SINT32 : 'int32_t', FieldDescriptorProto.TYPE_SINT64 : 'int64_t', FieldDescriptorProto.TYPE_STRING : 'char *', FieldDescriptorProto.TYPE_UINT32 : 'uint32_t', FieldDescriptorProto.TYPE_UINT64 : 'uint64_t' }.get(field.type); if type_str is None: raise Warp17ParseException('Unsupported type: ' + str(field)) return type_str def gen_constant_define(name, val): return line('#define ' + name + ' ' + val) def gen_struct_begin(item): return line('typedef struct ' + gen_name(item.name) + ' {') def gen_struct_end(item): return line(line('} ' + gen_fwname(item.name) + ';')) def gen_union_begin(name): return line('\tunion {') def gen_union_end(name): return line('\t} ' + name + ';') def gen_decl(decl_type, decl_name): return decl_type + ' ' + decl_name def gen_var_decl(var_type, var_name, initializer=None): if initializer is None: return gen_decl(var_type, var_name) + ';' return gen_decl(var_type, var_name) + ' = ' + initializer + ';' def gen_return(err = None): if err is None: return line('return;') return line('return ' + '-' + err + ';') def gen_assign(dest, src): return line(dest + ' = ' + src + ';') def gen_if(cond, true_inst, false_inst = None): output = \ [line('if (' + cond + ') {')] + \ ['\t' + inst for inst in true_inst] + \ [line('}')] if not false_inst is None: output += \ [line('else {')] + \ ['\t' + inst for inst in false_inst] + \ [line('}')] return output def gen_for(var, start, end, body_inst = None): return \ [line('for (' + var + ' = ' + start + '; ' + \ var + ' < ' + end + '; ' + \ var + '++) {')] + \ ['\t' + inst for inst in body_inst] + \ [line('}')] def gen_fcall(fname, fargs): return fname + '(' + ', '.join(fargs) + ')' def gen_fcall_stmt(fname, fargs): return line(gen_fcall(fname, fargs) + ';') def gen_sizeof(name): return gen_fcall('sizeof', [name]) def gen_alloc(var, size): return gen_assign(var, gen_fcall('rte_zmalloc', ['"TPG_RPC_GEN"', str(size), '0'])) def gen_alloc_err(var): return gen_if('!' + var, true_inst = [gen_return('ENOMEM')]) def gen_free(var): return line ('if (' + var + ') ' + gen_fcall('rte_free', [var]) + ';') def gen_min(a, b): return '((' + a + ') <= (' + b + ') ? (' + a + ') : (' + b + '))' ############################################################################### # XLATE HDR ############################################################################### def hdr_f_enter(proto_file, prefix): return [ gen_guard_begin(gen_h_guard_name(prefix)), gen_standard_includes(), gen_h_include(prefix + '.pb-c.h') ] def hdr_f_leave(proto_file, prefix): return [ gen_guard_end(gen_h_guard_name(prefix)) ] def hdr_e_constants(item): return [ gen_constant_define(v.name, str(v.number)) for v in item.value ] def hdr_e_process(item): return [ line(line('typedef ' + \ gen_decl(item.name, gen_fwname(item.name)) + ';')) ] def hdr_m_enter(item): return [gen_struct_begin(item)] def hdr_u_enter(item, union_name, union_anon): return [gen_union_begin(union_name)] def hdr_u_leave(union_name, union_anon): return [gen_union_end(union_name if not union_anon else '')] def hdr_m_gen_required_field(item, field, field_name): return [line(gen_type(field) + ' ' + field_name + ';')] def hdr_m_gen_optional_field(item, field, field_name): if is_type_ptr(field.type): return hdr_m_gen_required_field(item, field, field_name) if field.type == FieldDescriptorProto.TYPE_MESSAGE: return [line(gen_var_decl(gen_message_type(field) + '*', field_name))] return \ [line(gen_var_decl('bool', 'has_' + field_name)), line(gen_var_decl(gen_type(field), field_name))] def hdr_m_gen_repeated_field(item, field, field_name, array_size): return [ \ line(gen_var_decl('uint32_t', field_name + '_count')), line(gen_var_decl(gen_type(field), field_name + '[' + array_size + ']')) ] def hdr_m_gen_union_field(item, field, field_name, array_size): return ['\t' + l for l in hdr_m_gen_required_field(item, field, field_name)] def hdr_m_gen_field(item, field, field_name, array_size): if field.label == FieldDescriptorProto.LABEL_REQUIRED: return hdr_m_gen_required_field(item, field, field_name) elif field.label == FieldDescriptorProto.LABEL_OPTIONAL: return hdr_m_gen_optional_field(item, field, field_name) elif field.label == FieldDescriptorProto.LABEL_REPEATED: return hdr_m_gen_repeated_field(item, field, field_name, array_size) def hdr_m_field(item, field, field_name, union_name, union_anon, array_size): if not union_name is None: return ['\t' + l for l in hdr_m_gen_union_field(item, field, field_name, array_size)] else: return ['\t' + l for l in hdr_m_gen_field(item, field, field_name, array_size)] def hdr_m_leave(item): return [ gen_struct_end(item), gen_xlate_h(item) ] ############################################################################### # XLATE PROTOC ############################################################################### def gen_msg_protoc_xlate(type_name, dst, src): type_name = extract_name(type_name) return gen_fcall_stmt(gen_xlate_protoc_name(type_name), [src, dst]) def xlate_protoc_f_enter(proto_file, prefix): return [gen_h_include(proto_file.name + XLATE_H)] def xlate_protoc_m_enter(item): return [ \ xlate_gen_guard_begin(gen_xlate_guard_name(item.name)), line(gen_xlate_protoc_sig(item.name)), line('{'), line('\t' + gen_var_decl('uint32_t', 'i')), line(''), line('\t(void)i;') ] def xlate_protoc_m_gen_msg_required(item, field, field_name): type_name = field.type_name[1:] return gen_if('in->' + field.name + ' != NULL', true_inst = [gen_msg_protoc_xlate(field.type_name, '&out->' + field_name, 'in->' + field.name)], false_inst = [gen_fcall_stmt(gen_xlate_default_name(type_name), ['&out->' + field_name])]) def xlate_protoc_m_gen_scalar_required(item, field, field_name): if is_type_str(field.type): #TODO: we strdup but we never free! return [gen_assign('out->' + field_name, gen_fcall('strdup', ['in->' + field.name]))] return [gen_assign('out->' + field_name, 'in->' + field.name)] def xlate_protoc_m_gen_required(item, field, field_name): if field.type == FieldDescriptorProto.TYPE_MESSAGE: return xlate_protoc_m_gen_msg_required(item, field, field_name) return xlate_protoc_m_gen_scalar_required(item, field, field_name) def xlate_protoc_m_gen_msg_optional(item, field, field_name, union_name, union_anon): if union_anon or not union_name is None: if not union_anon and not union_name is None: field_name = union_name + '.' + field_name return gen_if('in->' + field.name + ' != NULL', true_inst = [gen_msg_protoc_xlate(field.type_name, '&out->' + field_name, 'in->' + field.name)]) return gen_if('in->' + field.name + ' != NULL', true_inst = [gen_alloc('out->' + field_name, gen_sizeof('*out->' + field_name))] + \ gen_alloc_err('out->' + field_name) + \ [gen_msg_protoc_xlate(field.type_name, 'out->' + field_name, 'in->' + field.name)], false_inst = [gen_assign('out->' + field_name, 'NULL')]) def xlate_protoc_m_gen_scalar_optional(item, field, field_name, union_name, union_anon): if not union_anon and not union_name is None: field_name = union_name + '.' + field_name assign_default = None if field.default_value: if is_type_str(field.type): #TODO: we strdup but we never free! assign_default = [gen_assign('out->' + field_name, gen_fcall('strdup', [field.default_value]))] elif union_name is None: assign_default = [gen_assign('out->' + field_name, field.default_value)] if is_type_ptr(field.type): if is_type_str(field.type): #TODO: we strdup but we never free! assign_inst = [gen_assign('out->' + field_name, gen_fcall('strdup', ['in->' + field.name]))] else: assign_inst = [gen_assign('out->' + field_name, 'in->' + field.name)] return gen_if('in->' + field.name + ' != NULL', true_inst = assign_inst, false_inst = assign_default) output = [] if union_name is None: output += [gen_assign('out->has_' + field_name, 'in->has_' + field.name)] output += gen_if('in->has_' + field.name, true_inst = [gen_assign('out->' + field_name, 'in->' + field.name)], false_inst = assign_default) return output def xlate_protoc_m_gen_optional(item, field, field_name, union_name, union_anon): if field.type == FieldDescriptorProto.TYPE_MESSAGE: return xlate_protoc_m_gen_msg_optional(item, field, field_name, union_name, union_anon) return xlate_protoc_m_gen_scalar_optional(item, field, field_name, union_name, union_anon) def xlate_protoc_m_gen_msg_repeated(item, field, field_name, array_size): return gen_for('i', '0', gen_min('in->n_' + field.name, array_size), body_inst = [gen_msg_protoc_xlate(field.type_name, '&out->' + field_name + '[i]', 'in->' + field.name + '[i]')]) def xlate_protoc_m_gen_scalar_repeated(item, field, field_name, array_size): if is_type_ptr(field.type): raise Warp17ParseException('Error: repeated pointer types ' + \ 'not supported: ' + field.name) return gen_for('i', '0', 'in->n_' + field.name, body_inst = [gen_assign('out->' + field_name + '[i]', 'in->' + field.name + '[i]')]) def xlate_protoc_m_gen_repeated(item, field, field_name, array_size): output = [gen_assign('out->' + field_name + '_count', gen_min('in->n_' + field.name, array_size))] if field.type == FieldDescriptorProto.TYPE_MESSAGE: output += xlate_protoc_m_gen_msg_repeated(item, field, field_name, array_size) else: output += xlate_protoc_m_gen_scalar_repeated(item, field, field_name, array_size) return output def xlate_protoc_m_field(item, field, field_name, union_name, union_anon, array_size): if field.label == FieldDescriptorProto.LABEL_REQUIRED: return ['\t' + l for l in xlate_protoc_m_gen_required(item, field, field_name)] elif field.label == FieldDescriptorProto.LABEL_OPTIONAL: return ['\t' + l for l in xlate_protoc_m_gen_optional(item, field, field_name, union_name, union_anon)] elif field.label == FieldDescriptorProto.LABEL_REPEATED: return ['\t' + l for l in xlate_protoc_m_gen_repeated(item, field, field_name, array_size)] else: raise Warp17ParseException('Error: Unexpected label type: ' + field.name) def xlate_protoc_m_leave(item): return [ \ line('\t' + gen_return('0')), line('}'), xlate_gen_guard_end(gen_xlate_guard_name(item.name)) + '\n', '\n' ] ############################################################################### # XLATE TPG ############################################################################### def gen_msg_tpg_xlate(type_name, dst, src): type_name = extract_name(type_name) return gen_fcall(gen_xlate_tpg_name(type_name), [src, dst]) def gen_msg_tpg_xlate_stmt(type_name, dst, src): return line(gen_msg_tpg_xlate(type_name, dst, src) + ';') def gen_msg_tpg_union_xlate(type_name, dst, src): return gen_fcall(gen_xlate_tpg_union_name(type_name), [src, dst]) def gen_msg_tpg_union_xlate_stmt(type_name, dst, src): return line(gen_msg_tpg_union_xlate(type_name, dst, src) + ';') def gen_xlate_tpg_init(item): return gen_assign('*out', gen_protoc_name_init(item.name)) def xlate_tpg_m_enter(item): if not item.options.Extensions[warp17_xlate_tpg]: return [] return [ xlate_gen_guard_begin(gen_xlate_guard_name(item.name)), line(gen_xlate_tpg_sig(item.name)), line('{'), line('\t' + gen_var_decl('uint32_t', 'i')), line('\t' + gen_var_decl('int', 'err')), line(''), line('\t(void)i;'), line('\t(void)err;'), '\t' + gen_xlate_tpg_init(item) ] def xlate_tpg_u_enter(item, union_name, union_anon): if not item.options.Extensions[warp17_xlate_tpg]: return [] return [gen_assign('err', gen_msg_tpg_union_xlate(item.name, 'out', 'in'))] + \ gen_if('err != 0', true_inst = ['\t' + gen_return('err')]) def xlate_tpg_m_gen_msg_required(item, field, field_name): return \ [gen_alloc('out->' + field.name, gen_sizeof('*out->' + field.name))] + \ gen_alloc_err('out->' + field.name) + \ [gen_msg_tpg_xlate_stmt(field.type_name, 'out->' + field.name, '&in->' + field_name)] def xlate_tpg_m_gen_scalar_required(item, field, field_name): return [ gen_assign('out->' + field_name, 'in->' + field.name) ] def xlate_tpg_m_gen_required(item, field, field_name): if field.type == FieldDescriptorProto.TYPE_MESSAGE: return xlate_tpg_m_gen_msg_required(item, field, field_name) return xlate_tpg_m_gen_scalar_required(item, field, field_name) def xlate_tpg_m_gen_optional(item, field, field_name, union_name, union_anon): # Can't translate unions. The user has to provide a function for that.. if not union_name is None: return [] if is_type_ptr(field.type): return xlate_tpg_m_gen_required(item, field, field_name) if field.type == FieldDescriptorProto.TYPE_MESSAGE: return gen_if('in->' + field_name + ' != NULL', true_inst = [gen_alloc('out->' + field.name, gen_sizeof('*out->' + field.name))] + \ gen_alloc_err('out->' + field.name) + \ [gen_msg_tpg_xlate_stmt(field.type_name, 'out->' + field.name, 'in->' + field_name)]) return gen_if('in->has_' + field_name, true_inst = [gen_assign('out->' + field.name, 'in->' + field_name), gen_assign('out->has_' + field.name, 'in->has_' + field_name)]) def xlate_tpg_m_gen_msg_repeated(item, field, field_name, array_size): return gen_for('i', '0', 'in->' + field_name + '_count', body_inst = \ [gen_alloc('out->' + field.name + '[i]', gen_sizeof('*out->' + field.name + '[i]'))] + \ gen_alloc_err('out->' + field.name + '[i]') + \ [gen_msg_tpg_xlate_stmt(field.type_name, 'out->' + field.name + '[i]', '&in->' + field_name + '[i]')]) def xlate_tpg_m_gen_scalar_repeated(item, field, field_name, array_size): return gen_for('i', '0', 'in->' + field_name + '_count', body_inst = [gen_assign('out->' + field.name + '[i]', 'in->' + field_name + '[i]')]) def xlate_tpg_m_gen_repeated(item, field, field_name, array_size): output = [gen_alloc('out->' + field.name, array_size + ' * ' + gen_sizeof('*out->' + field.name))] output += gen_alloc_err('out->' + field.name) output += [gen_assign('out->n_' + field.name, 'in->' + field_name + '_count')] if field.type == FieldDescriptorProto.TYPE_MESSAGE: output += xlate_tpg_m_gen_msg_repeated(item, field, field_name, array_size) else: output += xlate_tpg_m_gen_scalar_repeated(item, field, field_name, array_size) return output def xlate_tpg_m_field(item, field, field_name, union_name, union_anon, array_size): if not item.options.Extensions[warp17_xlate_tpg]: return [] if field.label == FieldDescriptorProto.LABEL_REQUIRED: return ['\t' + l for l in xlate_tpg_m_gen_required(item, field, field_name)] elif field.label == FieldDescriptorProto.LABEL_OPTIONAL: return ['\t' + l for l in xlate_tpg_m_gen_optional(item, field, field_name, union_name, union_anon)] elif field.label == FieldDescriptorProto.LABEL_REPEATED: return ['\t' + l for l in xlate_tpg_m_gen_repeated(item, field, field_name, array_size)] else: raise Warp17ParseException('Error: Unexpected label type: ' + field.name) def xlate_tpg_m_leave(item): if not item.options.Extensions[warp17_xlate_tpg]: return [] return [ \ '\t' + gen_return('0'), line('}'), xlate_gen_guard_end(gen_xlate_guard_name(item.name)) + '\n', '\n' ] ############################################################################### # XLATE Free ############################################################################### def xlate_free_m_enter(item): return [ xlate_gen_guard_begin(gen_xlate_guard_name(item.name)), line(gen_xlate_free_sig(item.name)), line('{'), line('\t' + gen_var_decl('uint32_t', 'i')), line(''), line('\t(void)i;'), line('\t(void)ptr;') ] def xlate_free_m_msg_repeated(item, field, field_name, array_size): type_name = field.type_name[1:] return gen_for('i', '0', 'ptr->n_' + field.name, body_inst = gen_if('ptr->' + field.name + '[i]', true_inst=[gen_fcall_stmt(gen_xlate_free_name(type_name), ['ptr->' + field.name + '[i]']), gen_fcall_stmt('rte_free', ['ptr->' + field.name + '[i]'])])) def xlate_free_m_scalar_repeated(item, field, field_name, array_size): return [] def xlate_free_m_repeated(item, field, field_name, array_size): if field.type == FieldDescriptorProto.TYPE_MESSAGE: output = xlate_free_m_msg_repeated(item, field, field_name, array_size) else: output = xlate_free_m_scalar_repeated(item, field, field_name, array_size) return output + [ gen_free('ptr->' + field.name) ] def xlate_free_m_optional(item, field, field_name): if field.type != FieldDescriptorProto.TYPE_MESSAGE: return [] return [ gen_free('ptr->' + field.name) ] def xlate_free_m_field(item, field, field_name, union_name, union_anon, array_size): if field.label == FieldDescriptorProto.LABEL_REPEATED: return ['\t' + l for l in xlate_free_m_repeated(item, field, field_name, array_size)] if field.label == FieldDescriptorProto.LABEL_OPTIONAL: return ['\t' + l for l in xlate_free_m_optional(item, field, field_name)] return [] def xlate_free_m_leave(item): return [ line('}'), xlate_gen_guard_end(gen_xlate_guard_name(item.name)), '\n' ] ############################################################################### # XLATE TPG Free ############################################################################### def xlate_tpg_free_m_enter(item): return [ xlate_gen_guard_begin(gen_xlate_guard_name(item.name)), line(gen_xlate_tpg_free_sig(item.name)), line('{'), line('\t' + gen_var_decl('uint32_t', 'i')), line(''), line('\t(void)i;'), line('\t(void)ptr;') ] def xlate_tpg_free_m_msg_repeated(item, field, field_name, array_size): type_name = field.type_name[1:] return gen_for('i', '0', 'ptr->' + field.name + '_count', body_inst = [gen_fcall_stmt(gen_xlate_tpg_free_name(type_name), ['&ptr->' + field.name + '[i]'])]) def xlate_tpg_free_m_scalar_repeated(item, field, field_name, array_size): return [] def xlate_tpg_free_m_repeated(item, field, field_name, array_size): if field.type == FieldDescriptorProto.TYPE_MESSAGE: return xlate_tpg_free_m_msg_repeated(item, field, field_name, array_size) else: return xlate_tpg_free_m_scalar_repeated(item, field, field_name, array_size) def xlate_tpg_free_m_optional(item, field, field_name, union_name, union_anon): if field.type != FieldDescriptorProto.TYPE_MESSAGE: return [] if not union_name is None or union_anon: return [] return [ gen_free('ptr->' + field.name) ] def xlate_tpg_free_m_field(item, field, field_name, union_name, union_anon, array_size): if field.label == FieldDescriptorProto.LABEL_REPEATED: return ['\t' + l for l in xlate_tpg_free_m_repeated(item, field, field_name, array_size)] if field.label == FieldDescriptorProto.LABEL_OPTIONAL: return ['\t' + l for l in xlate_tpg_free_m_optional(item, field, field_name, union_name, union_anon)] return [] def xlate_tpg_free_m_leave(item): return [ line('}'), xlate_gen_guard_end(gen_xlate_guard_name(item.name)), '\n' ] ############################################################################### # XLATE Default ############################################################################### def xlate_default_m_enter(item): return [ xlate_gen_guard_begin(gen_xlate_guard_name(item.name)), line(gen_xlate_default_sig(item.name)), line('{'), line('\t' + gen_var_decl(item.name, 'defaults', initializer=gen_protoc_name_init(item.name))), line(''), line('\t' + gen_xlate_protoc_name(item.name) + '(&defaults, out);') ] def xlate_default_m_leave(item): return [ line('}'), xlate_gen_guard_end(gen_xlate_guard_name(item.name)), '\n' ] ############################################################################### # main ############################################################################### def generate(request, response): for proto_file in request.proto_file: filename = proto_file.name if not filename.startswith('warp17'): continue (prefix, _, _) = filename.rpartition('.proto') if prefix is None: raise Warp17ParseException( 'Error: Unexpected proto filename format: ' + filename) f_hdr = response.file.add() f_hdr.name = filename + XLATE_H hdr_ops = WalkerOps(f_enter = hdr_f_enter, f_leave = hdr_f_leave, e_constants = hdr_e_constants, e_process = hdr_e_process, u_enter = hdr_u_enter, u_leave = hdr_u_leave, m_enter = hdr_m_enter, m_field = hdr_m_field, m_leave = hdr_m_leave) f_hdr.content = ''.join(xlate_file_walk(proto_file, hdr_ops)) f_c = response.file.add() f_c.name = filename + XLATE_C xlate_protoc_ops = WalkerOps(f_enter = xlate_protoc_f_enter, m_enter = xlate_protoc_m_enter, m_field = xlate_protoc_m_field, m_leave = xlate_protoc_m_leave) f_c.content = ''.join(xlate_file_walk(proto_file, xlate_protoc_ops)) xlate_tpg_ops = WalkerOps(m_enter = xlate_tpg_m_enter, u_enter = xlate_tpg_u_enter, m_field = xlate_tpg_m_field, m_leave = xlate_tpg_m_leave) f_c.content += ''.join(xlate_file_walk(proto_file, xlate_tpg_ops)) xlate_free_ops = WalkerOps(m_enter = xlate_free_m_enter, m_field = xlate_free_m_field, m_leave = xlate_free_m_leave) f_c.content += ''.join(xlate_file_walk(proto_file, xlate_free_ops)) xlate_tpg_free_ops = WalkerOps(m_enter = xlate_tpg_free_m_enter, m_field = xlate_tpg_free_m_field, m_leave = xlate_tpg_free_m_leave) f_c.content += ''.join(xlate_file_walk(proto_file, xlate_tpg_free_ops)) xlate_default_ops = WalkerOps(m_enter = xlate_default_m_enter, m_leave = xlate_default_m_leave) f_c.content += ''.join(xlate_file_walk(proto_file, xlate_default_ops)) if __name__ == '__main__': # Read request message from stdin data = sys.stdin.read() # Parse request request = plugin.CodeGeneratorRequest() request.ParseFromString(data) response = plugin.CodeGeneratorResponse() generate(request, response) sys.stdout.write(response.SerializeToString())
# coding: utf-8 """ No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: 1.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from datetime import datetime from pprint import pformat from six import iteritems import re class BuildConfigurationSetRest(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_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. """ swagger_types = { 'id': 'int', 'name': 'str', 'product_version_id': 'int', 'build_configuration_ids': 'list[int]' } attribute_map = { 'id': 'id', 'name': 'name', 'product_version_id': 'productVersionId', 'build_configuration_ids': 'buildConfigurationIds' } def __init__(self, id=None, name=None, product_version_id=None, build_configuration_ids=None): """ BuildConfigurationSetRest - a model defined in Swagger """ self._id = None self._name = None self._product_version_id = None self._build_configuration_ids = None if id is not None: self.id = id if name is not None: self.name = name if product_version_id is not None: self.product_version_id = product_version_id if build_configuration_ids is not None: self.build_configuration_ids = build_configuration_ids @property def id(self): """ Gets the id of this BuildConfigurationSetRest. :return: The id of this BuildConfigurationSetRest. :rtype: int """ return self._id @id.setter def id(self, id): """ Sets the id of this BuildConfigurationSetRest. :param id: The id of this BuildConfigurationSetRest. :type: int """ self._id = id @property def name(self): """ Gets the name of this BuildConfigurationSetRest. :return: The name of this BuildConfigurationSetRest. :rtype: str """ return self._name @name.setter def name(self, name): """ Sets the name of this BuildConfigurationSetRest. :param name: The name of this BuildConfigurationSetRest. :type: str """ self._name = name @property def product_version_id(self): """ Gets the product_version_id of this BuildConfigurationSetRest. :return: The product_version_id of this BuildConfigurationSetRest. :rtype: int """ return self._product_version_id @product_version_id.setter def product_version_id(self, product_version_id): """ Sets the product_version_id of this BuildConfigurationSetRest. :param product_version_id: The product_version_id of this BuildConfigurationSetRest. :type: int """ self._product_version_id = product_version_id @property def build_configuration_ids(self): """ Gets the build_configuration_ids of this BuildConfigurationSetRest. :return: The build_configuration_ids of this BuildConfigurationSetRest. :rtype: list[int] """ return self._build_configuration_ids @build_configuration_ids.setter def build_configuration_ids(self, build_configuration_ids): """ Sets the build_configuration_ids of this BuildConfigurationSetRest. :param build_configuration_ids: The build_configuration_ids of this BuildConfigurationSetRest. :type: list[int] """ self._build_configuration_ids = build_configuration_ids def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() 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() )) elif isinstance(value, datetime): result[attr] = str(value.date()) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, BuildConfigurationSetRest): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
import argparse import os import sys import time import numpy as np import torch from torch.autograd import Variable from torch.optim import Adam from torch.utils.data import DataLoader from torchvision import datasets from torchvision import transforms import utils from transformer_net import TransformerNet from vgg16 import Vgg16 def train(args): np.random.seed(args.seed) torch.manual_seed(args.seed) if args.cuda: torch.cuda.manual_seed(args.seed) kwargs = {'num_workers': 0, 'pin_memory': False} else: kwargs = {} transform = transforms.Compose([transforms.Scale(args.image_size), transforms.CenterCrop(args.image_size), transforms.ToTensor(), transforms.Lambda(lambda x: x.mul(255))]) train_dataset = datasets.ImageFolder(args.dataset, transform) train_loader = DataLoader(train_dataset, batch_size=args.batch_size, **kwargs) transformer = TransformerNet() optimizer = Adam(transformer.parameters(), args.lr) mse_loss = torch.nn.MSELoss() vgg = Vgg16() utils.init_vgg16(args.vgg_model_dir) vgg.load_state_dict(torch.load(os.path.join(args.vgg_model_dir, "vgg16.weight"))) if args.cuda: transformer.cuda() vgg.cuda() style = utils.tensor_load_rgbimage(args.style_image, size=args.style_size) style = style.repeat(args.batch_size, 1, 1, 1) style = utils.preprocess_batch(style) if args.cuda: style = style.cuda() style_v = Variable(style, volatile=True) utils.subtract_imagenet_mean_batch(style_v) features_style = vgg(style_v) gram_style = [utils.gram_matrix(y) for y in features_style] for e in range(args.epochs): transformer.train() agg_content_loss = 0. agg_style_loss = 0. count = 0 for batch_id, (x, _) in enumerate(train_loader): n_batch = len(x) count += n_batch optimizer.zero_grad() x = Variable(utils.preprocess_batch(x)) if args.cuda: x = x.cuda() y = transformer(x) xc = Variable(x.data.clone(), volatile=True) utils.subtract_imagenet_mean_batch(y) utils.subtract_imagenet_mean_batch(xc) features_y = vgg(y) features_xc = vgg(xc) f_xc_c = Variable(features_xc[1].data, requires_grad=False) content_loss = args.content_weight * mse_loss(features_y[1], f_xc_c) style_loss = 0. for m in range(len(features_y)): gram_s = Variable(gram_style[m].data, requires_grad=False) gram_y = utils.gram_matrix(features_y[m]) style_loss += args.style_weight * mse_loss(gram_y, gram_s[:n_batch, :, :]) total_loss = content_loss + style_loss total_loss.backward() optimizer.step() agg_content_loss += content_loss.data[0] agg_style_loss += style_loss.data[0] if (batch_id + 1) % args.log_interval == 0: mesg = "{}\tEpoch {}:\t[{}/{}]\tcontent: {:.6f}\tstyle: {:.6f}\ttotal: {:.6f}".format( time.ctime(), e + 1, count, len(train_dataset), agg_content_loss / (batch_id + 1), agg_style_loss / (batch_id + 1), (agg_content_loss + agg_style_loss) / (batch_id + 1) ) print(mesg) # save model transformer.eval() transformer.cpu() save_model_filename = "epoch_" + str(args.epochs) + "_" + str(time.ctime()).replace(' ', '_') + "_" + str( args.content_weight) + "_" + str(args.style_weight) + ".model" save_model_path = os.path.join(args.save_model_dir, save_model_filename) torch.save(transformer, save_model_path) print("\nDone, trained model saved at", save_model_path) def check_paths(args): try: if not os.path.exists(args.vgg_model_dir): os.makedirs(args.vgg_model_dir) if not os.path.exists(args.save_model_dir): os.makedirs(args.save_model_dir) except OSError as e: print(e) sys.exit(1) def stylize(args): content_image = utils.tensor_load_rgbimage(args.content_image, scale=args.content_scale) content_image = content_image.unsqueeze(0) if args.cuda: content_image = content_image.cuda() content_image = Variable(utils.preprocess_batch(content_image)) style_model = torch.load(args.model) if args.cuda: style_model.cuda() output = style_model(content_image) utils.tensor_save_bgrimage(output.data[0], args.output_image, args.cuda) def main(): main_arg_parser = argparse.ArgumentParser(description="parser for fast-neural-style") subparsers = main_arg_parser.add_subparsers(title="subcommands", dest="subcommand") train_arg_parser = subparsers.add_parser("train", help="parser for training arguments") train_arg_parser.add_argument("--epochs", type=int, default=2, help="number of training epochs, default is 2") train_arg_parser.add_argument("--batch-size", type=int, default=4, help="batch size for training, default is 4") train_arg_parser.add_argument("--dataset", type=str, required=True, help="path to training dataset, the path should point to a folder " "containing another folder with all the training images") train_arg_parser.add_argument("--style-image", type=str, default="images/style-images/mosaic.jpg", help="path to style-image") train_arg_parser.add_argument("--vgg-model-dir", type=str, required=True, help="directory for vgg, if model is not present in the directory it is downloaded") train_arg_parser.add_argument("--save-model-dir", type=str, required=True, help="path to folder where trained model will be saved.") train_arg_parser.add_argument("--image-size", type=int, default=256, help="size of training images, default is 256 X 256") train_arg_parser.add_argument("--style-size", type=int, default=None, help="size of style-image, default is the original size of style image") train_arg_parser.add_argument("--cuda", type=int, required=True, help="set it to 1 for running on GPU, 0 for CPU") train_arg_parser.add_argument("--seed", type=int, default=42, help="random seed for training") train_arg_parser.add_argument("--content-weight", type=float, default=1.0, help="weight for content-loss, default is 1.0") train_arg_parser.add_argument("--style-weight", type=float, default=5.0, help="weight for style-loss, default is 5.0") train_arg_parser.add_argument("--lr", type=float, default=1e-3, help="learning rate, default is 0.001") train_arg_parser.add_argument("--log-interval", type=int, default=500, help="number of images after which the training loss is logged, default is 500") eval_arg_parser = subparsers.add_parser("eval", help="parser for evaluation/stylizing arguments") eval_arg_parser.add_argument("--content-image", type=str, required=True, help="path to content image you want to stylize") eval_arg_parser.add_argument("--content-scale", type=float, default=None, help="factor for scaling down the content image") eval_arg_parser.add_argument("--output-image", type=str, required=True, help="path for saving the output image") eval_arg_parser.add_argument("--model", type=str, required=True, help="saved model to be used for stylizing the image") eval_arg_parser.add_argument("--cuda", type=int, required=True, help="set it to 1 for running on GPU, 0 for CPU") args = main_arg_parser.parse_args() if args.subcommand is None: print("ERROR: specify either train or eval") sys.exit(1) if args.cuda and not torch.cuda.is_available(): print("ERROR: cuda is not available, try running on CPU") sys.exit(1) if args.subcommand == "train": check_paths(args) train(args) else: stylize(args) if __name__ == "__main__": main()
import json import datetime import asyncio from asyncio.subprocess import PIPE from subprocess import Popen, PIPE import os import random import logging import sys from hypersh_client.main.hypersh import HypershClient from sanic.response import json as json_resp from urllib3.exceptions import NewConnectionError from proxy.driver_requests import NEW_SESSION_REQ_BODY from proxy.selenium_client import SeleniumClient from proxy.util import uuid, PORT, get_session_id, do_selenium_request_async NODE_IMAGE = os.environ.get('SELENIUM_NODE_IMAGE', 'eventjumbler/selenium-node') NEW_SESSION_REQ_BODY_STR = json.dumps(NEW_SESSION_REQ_BODY) MAX_DRIVERS_PER_CONTAINER = 3 logging.basicConfig(level=logging.INFO, stream=sys.stdout) logger = logging.getLogger(__name__) def base_url(container_name): return 'http://' + container_name + ':' + PORT def create_node_container(app_logic, container_name): return app_logic.hyper_client.create_container( NODE_IMAGE, container_name, size='M2', environment_variables={'PROXY_CONTAINER': app_logic.proxy_container}, tcp_ports=['4444', '5555'] ) class AppLogic(object): def __init__(self, asyncio_loop, proxy_container_id): self.loop = asyncio_loop self.leftover_drivers = [] self.drivers = {} self.proxy_container = proxy_container_id self.hyper_client = HypershClient(os.environ.get('HYPERSH_REGION')) self.selenium_client = SeleniumClient(self.loop) @property def container_capacities(self): driver_counts = {} for driver_id, di in self.drivers.items(): driver_counts[di['container']] = driver_counts.get(di['container'], 0) + 1 return { container: (MAX_DRIVERS_PER_CONTAINER-count) for (container, count) in driver_counts.items() } async def launch_driver(self, req_body): leftover_id = await self._find_leftover() if leftover_id: logger.info('reusing leftover driver') success = self._create_from_leftover(leftover_id) if success: return True, False, self.drivers[leftover_id] success, created, container_name = await self.get_or_create_container() if success is False: return False, None, None if created: # wait for selenium to start await asyncio.sleep(3.5) success = await self._wait_for_selenium_ready(container_name) if success is False: return False, None, None success, req_session, resp_json = await self.selenium_client._launch_driver_on_container( req_body, container_name ) if success is False: return False, None, None selenium_session_id = resp_json['value']['sessionId'] self.drivers[selenium_session_id] = { 'requests_session': req_session, 'selenium_session_id': selenium_session_id, 'container': container_name, 'last_command_time': datetime.datetime.now(), 'creation_resp_json': resp_json } return True, True, self.drivers[selenium_session_id] async def quit_driver(self, selenium_id): container = self.drivers[selenium_id]['container'] if (await self.ping_container(container)) is False: logger.warning('quit_driver() called on offline container') return success = await self.selenium_client.get_page(container, selenium_id, 'about:blank') if not success: logger.error('quit_driver(): driver not added to leftovers because get_page() failed') return self.leftover_drivers.append(selenium_id) def sort_leftovers(self): """ Sort leftovers so most recently used drivers can get reused first and so drivers in the same container are adjacent (makes _find_leftover() more efficient) """ def order_leftovers(id): container = self.drivers[id]['container'] command_times = [ self.drivers[id]['last_command_time'] for id in self.drivers if self.drivers[id]['container'] == container ] return max(command_times) # will be same for all drivers in a container self.leftover_drivers.sort(key=order_leftovers, reverse=True) async def _wait_for_selenium_ready(self, container_name, wait_time=12): """ Wait for selenium to initialise and respond to requests. """ logger.info('waiting for selenium to be ready, will retry get_active_sessions() for %s seconds' % wait_time) if (await self.ping_container(container_name)) is False: logger.warning('_wait_for_selenium_ready() called on container that seems offline (ping failed)') iterations = round(wait_time/0.5) for i in range(iterations): try: success, sessions = await self.selenium_client.get_active_sessions([container_name]) if success: logger.info('selenium ready on: '+container_name) return True logger.info('_get_active_sessions() failed, this is normal while the container is initialising') except NewConnectionError: logger.info('waiting for selenium-grid to initialise on container (POST to /wd/hub/sessions/ gave a NewConnectionError)') await asyncio.sleep(0.5) logger.warning('selenium failed to be ready on %s after %s seconds' % (container_name, wait_time)) return False async def _launch_container(self): container_name = 'seleniumnode' + uuid(10) logger.info('creating and starting container: %s from image: %s' % (container_name, NODE_IMAGE)) success, container_id = await self.loop.run_in_executor( None, create_container, self, container_name ) if not success: logger.error('error: problem when launching container') return False, None logger.info('pinging new container repeatedly for 22s to wait for launch') success = await ping_wait(container_name, wait=22) if not success: logger.error('error: ping_wait for new container failed after 16 seconds pinging') return False, None logger.info('successfully launched container: ' + container_name) return True, container_name async def ping_container(self, container_name, deep=False): success, stdout, std_err = await sys_call_async("ping -c 1 " + container_name) if success is False: return False if not deep: return True try: success, sessions = await self.selenium_client.get_active_sessions([container_name]) return success except: return False async def shutdown_nodes(self): containers = self.container_capacities.keys() for container in containers: await self.loop.run_in_executor( # hopefully doesn't stall? None, self.hyper_client.remove_container, container ) self.notify_container_down(container) def notify_container_down(self, container_name): to_delete = [] for session_id, di in self.drivers.items(): if di['container'] == container_name: to_delete.append(session_id) for session_id in to_delete: del self.drivers[session_id] if session_id in self.leftover_drivers: try: self.leftover_drivers.remove(session_id) except: pass # just in case of race condition async def get_or_create_container(self): for name, capacity in self.container_capacities.items(): # slight possibility that this would be out of sync, it could be that one of the driver sessions has been dropped if capacity >= 1: ping_result = await self.ping_container(name) # can we put this in the if statement? if ping_result is False: self.notify_container_down(name) continue return True, False, name success, container_name = await self._launch_container() return success, True, container_name # success, created, container_name async def _find_leftover(self): if not self.leftover_drivers: return None logger.info('find_leftover() called, leftovers: %s' % self.leftover_drivers) active_sessions = {} self.sort_leftovers() while self.leftover_drivers: try: leftover_id = self.leftover_drivers.pop() except IndexError: break # very slight chance of race-condition container = self.drivers[leftover_id]['container'] if container not in active_sessions: # so we query it once per container success, sessions = await self.selenium_client.get_active_sessions([container]) active_sessions[container] = sessions if success else [] if leftover_id in active_sessions[container]: return leftover_id # otherwise leftover_id will get discarded return None async def proxy_selenium_request(self, request, driver_url): body_str = request.body.decode() selenium_id = get_session_id(driver_url, body_str) container = self.drivers[selenium_id]['container'] request_session = self.drivers[selenium_id]['requests_session'] if random.randint(0, 10) == 9: # for efficiency, we do this 1 in every 10 requests self.drivers['last_command_time'] = datetime.datetime.now() url = 'http://' + container + ':' + PORT + '/' + driver_url status_code, resp_json = await do_selenium_request_async( request, request_session, url ) if status_code != 200: print('warning: selenium request gave status: %s' % status_code) return json_resp(resp_json, status=status_code) # return HTTPResponse(resp.content.decode(), status=resp.status_code, content_type="application/json") def _create_from_leftover(self, leftover_id): if leftover_id in self.leftover_drivers: try: self.leftover_drivers.remove(leftover_id) except: # possible race condition return False self.drivers[leftover_id]['last_command_time'] = datetime.datetime.now() return True async def sys_call_async(command): proc = await asyncio.create_subprocess_exec(*command.split(), stdout=PIPE, stderr=PIPE) # or loop.subprocess_exec? await proc.wait() stdout, stderr = await proc.communicate() success = proc.returncode == 0 return success, stdout.decode(), stderr.decode() def sys_call(cmd_str, shell=False, suppress_errors=True): p = Popen(cmd_str.split(), stdout=PIPE, stderr=PIPE, stdin=PIPE, shell=shell) #stderr=PIPE, #p.communicate() stdout, stderr = p.stdout.read(), p.stderr.read() p.wait() success = p.returncode == 0 return success, stdout, stderr async def ping_wait(container_name, wait=9): print('poop') num_loops = round(wait / 0.35) #host = container_name if PRODUCTION else HYPER_FIP command = "ping -c 1 " + container_name #+ " >/dev/null 2>&1" #command = 'ls -la sdfsdf' print('num loops: %s' % num_loops) for i in range(num_loops): # wait up to 9 seconds print('ping!') success, stdout, stderr = await sys_call_async(command) if success: return True print('stdout: '+ stdout) print('stderr: ' + stderr) await asyncio.sleep(0.35) print('finished pinging without succeeding') return False # old code: ''' async def launch_driver(): if reuse_session: if reuse_session in self.leftover_drivers: self._create_from_leftover(reuse_session) return True, False, self.drivers[reuse_session] # else, ignore and continue as normal else: if reuse_session in self.drivers: logger.warning( 'warning: reuse_session not found in leftovers, ' 'you need to call driver.quit() or /quit_driver/ first' ) else: logger.error('warning: reuse_session not found, driver session doesn\'t exist') async def refresh(self): running_containers = await self.get_running_containers() for cn in list(self.container_capacities.keys()): if cn not in running_containers: self.notify_container_down(cn) def is_valid(di): if di['container'] in running_containers:# and di['state'] != 'DRIVER_LAUNCH_FAILED': return True return False self.drivers = {sel_id: di for (sel_id, di) in self.drivers.items() if is_valid(di)} self.leftover_drivers = [id for id in self.leftover_drivers if id in self.drivers.keys()] async def get_running_containers(self): now = datetime.datetime.now() fifteen_secs_agp = datetime.timedelta(seconds=7) if self.running_containers_cache is None or now-self.running_containers_last_checked > fifteen_secs_agp: success, running_containers = self.hyper_client.get_containers(state='running', image=NODE_IMAGE) if not success: print('warning: failed to get running containers from hypersh') result = [di['name'] for di in running_containers] self.running_containers_cache = result self.running_containers_last_checked = datetime.datetime.now() return self.running_containers_cache '''
# # Author: Bo Maryniuk <bo@suse.de> # # Copyright 2017 SUSE 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. r""" Execution of Ansible modules from within states =============================================== With `ansible.call` these states allow individual Ansible module calls to be made via states. To call an Ansible module function use a :mod:`module.run <salt.states.ansible.call>` state: .. code-block:: yaml some_set_of_tasks: ansible: - system.ping - packaging.os.zypper - name: emacs - state: installed """ import logging import os import sys # Import salt modules import salt.fileclient import salt.utils.decorators.path from salt.utils.decorators import depends log = logging.getLogger(__name__) __virtualname__ = "ansible" @depends("ansible") class AnsibleState: """ Ansible state caller. """ def get_args(self, argset): """ Get args and kwargs from the argset. :param argset: :return: """ args = [] kwargs = {} for element in argset or []: if isinstance(element, dict): kwargs.update(element) else: args.append(element) return args, kwargs def __call__(self, **kwargs): """ Call Ansible module. :return: """ ret = { "name": kwargs.pop("name"), "changes": {}, "comment": "", "result": True, } for mod_name, mod_params in kwargs.items(): args, kwargs = self.get_args(mod_params) try: ans_mod_out = __salt__["ansible.{}".format(mod_name)]( **{"__pub_arg": [args, kwargs]} ) except Exception as err: # pylint: disable=broad-except ans_mod_out = 'Module "{}" failed. Error message: ({}) {}'.format( mod_name, err.__class__.__name__, err ) ret["result"] = False ret["changes"][mod_name] = ans_mod_out return ret def __virtual__(): """ Disable, if Ansible is not available around on the Minion. """ # pylint: disable=unnecessary-lambda setattr(sys.modules[__name__], "call", lambda **kwargs: AnsibleState()(**kwargs)) # pylint: enable=unnecessary-lambda return __virtualname__ def _client(): """ Get a fileclient """ return salt.fileclient.get_file_client(__opts__) def _changes(plays): """ Find changes in ansible return data """ changes = {} for play in plays["plays"]: task_changes = {} for task in play["tasks"]: host_changes = {} for host, data in task["hosts"].items(): if data.get("changed", False) is True: host_changes[host] = data.get("diff", data.get("changes", {})) elif any(x in data for x in ["failed", "skipped", "unreachable"]): host_changes[host] = data.get("results", data.get("msg", {})) if host_changes: task_changes[task["task"]["name"]] = host_changes if task_changes: changes[play["play"]["name"]] = task_changes return changes @salt.utils.decorators.path.which("ansible-playbook") def playbooks(name, rundir=None, git_repo=None, git_kwargs=None, ansible_kwargs=None): """ Run Ansible Playbooks :param name: path to playbook. This can be relative to rundir or the git repo :param rundir: location to run ansible-playbook from. :param git_repo: git repository to clone for ansible playbooks. This is cloned using the `git.latest` state, and is cloned to the `rundir` if specified, otherwise it is clone to the `cache_dir` :param git_kwargs: extra kwargs to pass to `git.latest` state module besides the `name` and `target` :param ansible_kwargs: extra kwargs to pass to `ansible.playbooks` execution module besides the `name` and `target` :return: Ansible playbook output. .. code-block:: yaml run nginx install: ansible.playbooks: - name: install.yml - git_repo: git://github.com/gituser/playbook.git - git_kwargs: rev: master """ ret = { "result": False, "changes": {}, "comment": "Running playbook {}".format(name), "name": name, } if git_repo: if not isinstance(rundir, str) or not os.path.isdir(rundir): rundir = _client()._extrn_path(git_repo, "base") log.trace("rundir set to %s", rundir) if not isinstance(git_kwargs, dict): log.debug("Setting git_kwargs to empty dict: %s", git_kwargs) git_kwargs = {} __states__["git.latest"](name=git_repo, target=rundir, **git_kwargs) if not isinstance(ansible_kwargs, dict): log.debug("Setting ansible_kwargs to empty dict: %s", ansible_kwargs) ansible_kwargs = {} if __opts__["test"]: checks = __salt__["ansible.playbooks"]( name, rundir=rundir, check=True, diff=True, **ansible_kwargs ) if all( not check["changed"] and not check["failures"] and not check["unreachable"] and not check["skipped"] for check in checks["stats"].values() ): ret["comment"] = "No changes to be made from playbook {}".format(name) ret["result"] = True elif any( check["changed"] and not check["failures"] and not check["unreachable"] and not check["skipped"] for check in checks["stats"].values() ): ret["comment"] = "Changes will be made from playbook {}".format(name) ret["result"] = None ret["changes"] = _changes(checks) else: ret["comment"] = "There were some issues running the playbook {}".format( name ) ret["result"] = False ret["changes"] = _changes(checks) else: results = __salt__["ansible.playbooks"]( name, rundir=rundir, diff=True, **ansible_kwargs ) if all( not check["changed"] and not check["failures"] and not check["unreachable"] and not check["skipped"] for check in results["stats"].values() ): ret["comment"] = "No changes to be made from playbook {}".format(name) ret["result"] = True ret["changes"] = _changes(results) else: ret["changes"] = _changes(results) ret["result"] = all( not check["failures"] and not check["unreachable"] and not check["skipped"] for check in results["stats"].values() ) if ret["result"]: ret["comment"] = "Changes were made by playbook {}".format(name) else: ret[ "comment" ] = "There were some issues running the playbook {}".format(name) return ret
from datetime import datetime, date import iso8601 import re import rethinkdb as r from shapely.geometry import mapping from shapely.geometry.base import BaseGeometry import sondra.document from sondra.exceptions import ValidationError from sondra.api.ref import Reference class ValueHandler(object): """This is base class for transforming values to/from RethinkDB representations to standard representations. Attributes: is_geometry (bool): Does this handle geometry/geographical values. Indicates to Sondra that indexing should be handled differently. """ is_geometry = False has_default = False def __init__(self, *args, **kwargs): self._str = self.__class__.__name__ + str(args) + str(kwargs) def __str__(self): return self._str def __repr__(self): return self._str def to_rql_repr(self, value, document): """Transform the object value into a ReQL object for storage. Args: value: The value to transform Returns: object: A ReQL object. """ return value def to_json_repr(self, value, document, **kwargs): """Transform the object from a ReQL value into a standard value. Args: value (ReQL): The value to transform Returns: dict: A Python object representing the value. """ return value def to_python_repr(self, value, document): """Transform the object from a ReQL value into a standard value. Args: value (ReQL): The value to transform Returns: dict: A Python object representing the value. """ return value def default_value(self): raise NotImplemented() def post_save(self, document): pass def pre_delete(self, document): pass class ListHandler(ValueHandler): def __init__(self, sub_handler): super(ListHandler, self).__init__(sub_handler) self.sub_handler = sub_handler def to_rql_repr(self, value, document): if value is not None: return [self.sub_handler.to_rql_repr(v, document) for v in value] def to_json_repr(self, value, document, **kwargs): if value is not None: return [self.sub_handler.to_json_repr(v, document, **kwargs) for v in value] def to_python_repr(self, value, document): if value is not None: return [self.sub_handler.to_python_repr(v, document) for v in value] class PropertyHandler(ValueHandler): def __init__(self, prop, sub_handler): super(PropertyHandler, self).__init__(sub_handler) self.prop = prop self.sub_handler = sub_handler def to_rql_repr(self, value, document): if value is None: return None if self.prop in value: v = dict(value) v[self.prop] = self.sub_handler.to_rql_repr(v[self.prop], document) return v else: return value def to_json_repr(self, value, document, **kwargs): if value is None: return None if self.prop in value: v = dict(value) v[self.prop] = self.sub_handler.to_json_repr(v[self.prop], document, **kwargs) return v else: return value def to_python_repr(self, value, document): if value is None: return None if self.prop in value: v = dict(value) v[self.prop] = self.sub_handler.to_python_repr(v[self.prop], document) return v else: return value class PropertiesHandler(ValueHandler): def __init__(self, **handler_mapping): super(PropertiesHandler, self).__init__(**handler_mapping) self.sub_handlers = handler_mapping def to_rql_repr(self, value, document): if value is None: return None v = value for prop in self.sub_handlers: if prop in value: if v is value: # don't clone until we have to make a modification v = dict(value) v[prop] = self.sub_handlers[prop].to_rql_repr(v[prop], document) return v def to_json_repr(self, value, document, **kwargs): if value is None: return None v = value for prop in self.sub_handlers: if prop in value: if v is value: # don't clone until we have to make a modification v = dict(value) v[prop] = self.sub_handlers[prop].to_json_repr(v[prop], document, **kwargs) return v def to_python_repr(self, value, document): if value is None: return None v = value for prop in self.sub_handlers: if prop in value: if v is value: # don't clone until we have to make a modification v = dict(value) v[prop] = self.sub_handlers[prop].to_python_repr(v[prop], document) return v class PatternPropertiesHandler(ValueHandler): def __init__(self, **handler_mapping): super(PatternPropertiesHandler, self).__init__(**handler_mapping) self.sub_handlers = handler_mapping def to_rql_repr(self, value, document): if value is None: return None v = value for pattern in self.sub_handlers: for k, v in value.items(): if re.match(pattern, k): if v is value: # don't clone until we have to make a modification v = dict(value) v[k] = self.sub_handlers[k].to_rql_repr(v[k], document) return v def to_json_repr(self, value, document, **kwargs): if value is None: return None v = value for pattern in self.sub_handlers: for k, v in value.items(): if re.match(pattern, k): if v is value: # don't clone until we have to make a modification v = dict(value) v[k] = self.sub_handlers[k].to_json_repr(v[k], document) return v def to_python_repr(self, value, document): v = value for pattern in self.sub_handlers: for k, v in value.items(): if re.match(pattern, k): if v is value: # don't clone until we have to make a modification v = dict(value) v[k] = self.sub_handlers[k].to_python_repr(v[k], document) return v class KeyValueHandler(ValueHandler): """Handle a key-value object of a particular type of value""" def __init__(self, sub_handler): super(KeyValueHandler, self).__init__(sub_handler) self.sub_handler = sub_handler def to_rql_repr(self, value, document): if value: return {k: self.sub_handler.to_rql_repr(v, document) for k, v in value.items()} def to_json_repr(self, value, document, **kwargs): if value: return {k: self.sub_handler.to_json_repr(v, document) for k, v in value.items()} def to_python_repr(self, value, document): if value: return {k: self.sub_handler.to_python_repr(v, document) for k, v in value.items()} class ForeignKey(ValueHandler): def __init__(self, app, coll, urlify=True): super(ForeignKey, self).__init__(app, coll, urlify=urlify) self.app = app self.coll = coll self._urlify = urlify def to_rql_repr(self, value, document): """Should be just the 'id' of the document, not the full URL for portability""" if value is None: return value elif isinstance(value, str): if value.startswith('/') or value.startswith('http'): return Reference(document.suite, value).value.id else: return value else: return value.id def to_json_repr(self, value, document, **kwargs): """The URL of the document""" if value is None: return None elif isinstance(value, str): if value.startswith('/') or value.startswith('http'): return value elif self._urlify and not kwargs.get('bare_keys', False): return document.suite[self.app][self.coll].url + '/' + value else: return value elif self._urlify and not kwargs.get('bare_keys', False): return value.url else: return value.id def to_python_repr(self, value, document): """The document itself""" if value is None: return None elif isinstance(value, str): if value.startswith('/') or value.startswith('http'): return Reference(document.suite, value).value else: return document.suite[self.app][self.coll][value] else: return value class Geometry(ValueHandler): """A value handler for GeoJSON""" is_geometry = True def __init__(self, *allowed_types): super(Geometry, self).__init__(*allowed_types) self.allowed_types = set(x.lower() for x in allowed_types) if allowed_types else None def to_rql_repr(self, value, document): if value is None: return value if value == {}: return None if self.allowed_types: if value['type'].lower() not in self.allowed_types: raise ValidationError('value not in ' + ','.join(t for t in self.allowed_types)) return r.geojson(value) def to_json_repr(self, value, document, **kwargs): if value is None: return value if value == {}: return None if isinstance(value, BaseGeometry): return mapping(value) elif '$reql_type$' in value: del value['$reql_type$'] return value else: return value def to_python_repr(self, value, document): if value is None: return value if value == {}: return None if isinstance(value, BaseGeometry): return value if '$reql_type$' in value: del value['$reql_type$'] return value class DateTime(ValueHandler): """A value handler for Python datetimes""" DEFAULT_TIMEZONE='Z' def __init__(self, timezone='Z'): super(DateTime, self).__init__(timezone=timezone) self.timezone = timezone def from_rql_tz(self, tz): if tz == 'Z': return 0 else: posneg = -1 if tz[0] == '-' else 1 hours, minutes = map(int, tz.split(":")) offset = posneg*(hours*60 + minutes) return offset def to_rql_repr(self, value, document): if value is None: return value if isinstance(value, str): return r.iso8601(value, default_timezone=self.DEFAULT_TIMEZONE).in_timezone(self.timezone) elif isinstance(value, int) or isinstance(value, float): return datetime.fromtimestamp(value).isoformat() elif isinstance(value, dict): return r.time( value.get('year', None), value.get('month', None), value.get('day', None), value.get('hour', None), value.get('minute', None), value.get('second', None), value.get('timezone', self.timezone), ).in_timezone(self.timezone) else: return r.iso8601(value.isoformat(), default_timezone=self.DEFAULT_TIMEZONE).as_timezone(self.timezone) def to_json_repr(self, value, document, **kwargs): if value is None: return value if isinstance(value, date) or isinstance(value, datetime): return value.isoformat() elif isinstance(value, str): return value elif isinstance(value, int) or isinstance(value, float): return datetime.fromtimestamp(value).isoformat() else: return value.to_iso8601() def to_python_repr(self, value, document): if value is None: return value if isinstance(value, str): return iso8601.parse_date(value) elif isinstance(value, datetime): return value else: return iso8601.parse_date(value.to_iso8601()) class Now(DateTime): """Return a timestamp for right now if the value is null.""" has_default = True def from_rql_tz(self, tz): return 0 def to_rql_repr(self, value, document): value = value or datetime.utcnow() return super(Now, self).to_rql_repr(value, document) def to_json_repr(self, value, document, **kwargs): value = value or datetime.utcnow() return super(Now, self).to_json_repr(value, document) def to_python_repr(self, value, document): value = value or datetime.utcnow() return super(Now, self).to_python_repr(value, document) def default_value(self): return class SchemaParser(object): """ Automatically determines value-handlers for the given document schema. """ def __init__(self, schema, definitions): self._schema = schema self._definitions = definitions def __call__(self): return self._scan_properties_for_specials(self._schema) def _scan_properties_for_specials(self, s): if 'properties' in s: handlers = {pname: self._value_handler(pdef) for pname, pdef in s['properties'].items()} rem = [] for k, v in handlers.items(): if v is None: rem.append(k) for k in rem: del handlers[k] return handlers else: return None def _scan_patternProperties_for_specials(self, s): if 'patternProperties' in s: handlers = {"[{0}]".format(pname): self._value_handler(pdef) for pname, pdef in s['patternProperties'].items()} rem = [] for k, v in handlers.items(): if v is None: rem.append(k) for k in rem: del handlers[k] return handlers else: return None def _value_handler(self, pdef): ret = None ptype = pdef.get('type', 'string') if 'fk' in pdef: ret = ForeignKey(*pdef['fk'].split('/')) elif 'geo' in pdef: if 'geometry_type' in pdef: ret = Geometry(pdef['geometry_type']) else: ret = Geometry() elif 'formatters' in pdef: if pdef['formatters'] in {'time', 'datetime-local'}: ret = DateTime() elif 'format' in pdef: if pdef['format'] in {'date', 'time', 'date-time'}: ret = DateTime() elif '$ref' in pdef: defn_name = pdef['$ref'].rsplit('/', 1)[-1] if defn_name in self._definitions: defn = self._definitions[defn_name] defn_type = defn.get('type', 'string') # technically wrong, but entirely reasonable. assume string because you can have a bare enum and it is almost always a string if defn_type != 'object': ret = self._value_handler(defn) else: handlers = self._scan_properties_for_specials(defn) if handlers: ret = PropertiesHandler(**handlers) elif ptype == 'object': handlers = self._scan_properties_for_specials(pdef) pattern_handlers = self._scan_patternProperties_for_specials(pdef) if handlers: ret = PropertiesHandler(**handlers) elif pattern_handlers: ret = PatternPropertiesHandler(**pattern_handlers) elif ptype == 'array': sub_handler = self._value_handler(pdef['items']) if sub_handler: ret = ListHandler(sub_handler) return ret
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for model_coverage_lib.py.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tempfile import numpy as np from tensorflow.lite.python import lite from tensorflow.lite.testing.model_coverage import model_coverage_lib as model_coverage from tensorflow.python import keras from tensorflow.python.client import session from tensorflow.python.eager import def_function from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.platform import test from tensorflow.python.saved_model import saved_model from tensorflow.python.training.training_util import write_graph class EvaluateFrozenGraph(test.TestCase): def _saveFrozenGraph(self, sess): graph_def_file = os.path.join(self.get_temp_dir(), 'model.pb') write_graph(sess.graph_def, '', graph_def_file, False) return graph_def_file def testFloat(self): with ops.Graph().as_default(): with session.Session().as_default() as sess: in_tensor = array_ops.placeholder( shape=[1, 16, 16, 3], dtype=dtypes.float32) _ = in_tensor + in_tensor filename = self._saveFrozenGraph(sess) model_coverage.test_frozen_graph(filename, ['Placeholder'], ['add']) def testInputWithRange(self): with ops.Graph().as_default(): with session.Session().as_default() as sess: in_tensor = array_ops.placeholder( shape=[1, 16, 16, 3], dtype=dtypes.float32) _ = in_tensor + in_tensor filename = self._saveFrozenGraph(sess) model_coverage.test_frozen_graph( filename, ['Placeholder'], ['add'], input_data_range={'Placeholder': (0, 10)}) def testMultipleOutputs(self): with ops.Graph().as_default(): with session.Session().as_default() as sess: in_tensor_1 = array_ops.placeholder( shape=[1, 16], dtype=dtypes.float32, name='inputA') in_tensor_2 = array_ops.placeholder( shape=[1, 16], dtype=dtypes.float32, name='inputB') weight = constant_op.constant(-1.0, shape=[16, 16]) bias = constant_op.constant(-1.0, shape=[16]) layer = math_ops.matmul(in_tensor_1, weight) + bias _ = math_ops.reduce_mean(math_ops.square(layer - in_tensor_2)) filename = self._saveFrozenGraph(sess) model_coverage.test_frozen_graph(filename, ['inputA', 'inputB'], ['add', 'Mean']) def testFunctions(self): """Tests functions.""" @def_function.function def plus_placeholder(x, placeholder): return x + placeholder with ops.Graph().as_default(): placeholder = array_ops.placeholder( dtype=dtypes.float32, shape=[1], name='input') variable_node = constant_op.constant(1.0, name='variable_node') defun_node = plus_placeholder(variable_node, placeholder) _ = math_ops.multiply(defun_node, 2.0, name='output_node') # Initialize variables in the model. sess = session.Session() filename = self._saveFrozenGraph(sess) model_coverage.test_frozen_graph(filename, ['input'], ['output_node']) def _getQuantizedModel(self): np.random.seed(0) with ops.Graph().as_default(): with session.Session().as_default() as sess: # The tensor needs to have more than 1024 elements for quantize_weights # to kick in. Thus, the [33, 33] shape. in_tensor_1 = array_ops.placeholder( shape=[33, 33], dtype=dtypes.float32, name='inputA') in_tensor_2 = constant_op.constant( np.random.uniform(low=-10., high=10., size=(33, 33)), shape=[33, 33], dtype=dtypes.float32, name='inputB') _ = math_ops.matmul(in_tensor_1, in_tensor_2, name='output') filename = self._saveFrozenGraph(sess) return filename def testQuantized(self): filename = self._getQuantizedModel() model_coverage.test_frozen_graph_quant(filename, ['inputA'], ['output']) def testQuantizedInputShapes(self): filename = self._getQuantizedModel() model_coverage.test_frozen_graph_quant( filename, ['inputA'], ['output'], input_shapes={'inputA': [33, 33]}) def testQuantizedFlexAll(self): filename = self._getQuantizedModel() model_coverage.test_frozen_graph_quant( filename, ['inputA'], ['output'], target_ops=set([lite.OpsSet.SELECT_TF_OPS])) class EvaluateSavedModel(test.TestCase): def testFloat(self): saved_model_dir = os.path.join(self.get_temp_dir(), 'simple_savedmodel') with ops.Graph().as_default(): with session.Session().as_default() as sess: in_tensor_1 = array_ops.placeholder( shape=[1, 16, 16, 3], dtype=dtypes.float32, name='inputB') in_tensor_2 = array_ops.placeholder( shape=[1, 16, 16, 3], dtype=dtypes.float32, name='inputA') out_tensor = in_tensor_1 + in_tensor_2 inputs = {'x': in_tensor_1, 'y': in_tensor_2} outputs = {'z': out_tensor} saved_model.simple_save(sess, saved_model_dir, inputs, outputs) model_coverage.test_saved_model(saved_model_dir) class EvaluateKerasModel(test.TestCase): def _getSingleInputKerasModel(self): """Returns single input Sequential tf.keras model.""" keras.backend.clear_session() xs = [-1, 0, 1, 2, 3, 4] ys = [-3, -1, 1, 3, 5, 7] model = keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])]) model.compile(optimizer='sgd', loss='mean_squared_error') model.train_on_batch(xs, ys) return model def _saveKerasModel(self, model): try: fd, keras_file = tempfile.mkstemp('.h5') keras.models.save_model(model, keras_file) finally: os.close(fd) return keras_file def testFloat(self): model = self._getSingleInputKerasModel() keras_file = self._saveKerasModel(model) model_coverage.test_keras_model(keras_file) def testPostTrainingQuantize(self): model = self._getSingleInputKerasModel() keras_file = self._saveKerasModel(model) model_coverage.test_keras_model(keras_file, post_training_quantize=True) def testTargetOps(self): model = self._getSingleInputKerasModel() keras_file = self._saveKerasModel(model) model_coverage.test_keras_model( keras_file, target_ops=set([lite.OpsSet.TFLITE_BUILTINS, lite.OpsSet.SELECT_TF_OPS])) if __name__ == '__main__': test.main()
# 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. # ============================================================================== """A Python interface for creating TensorFlow servers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.core.protobuf import cluster_pb2 from tensorflow.core.protobuf import tensorflow_server_pb2 from tensorflow.python import pywrap_tensorflow as c_api from tensorflow.python.framework import errors from tensorflow.python.util import compat from tensorflow.python.util.tf_export import tf_export def _make_server_def(server_or_cluster_def, job_name, task_index, protocol, config): """Creates a `tf.train.ServerDef` protocol buffer. Args: server_or_cluster_def: A `tf.train.ServerDef` or `tf.train.ClusterDef` protocol buffer, or a `tf.train.ClusterSpec` object, describing the server to be defined and/or the cluster of which it is a member. job_name: (Optional.) Specifies the name of the job of which the server is a member. Defaults to the value in `server_or_cluster_def`, if specified. task_index: (Optional.) Specifies the task index of the server in its job. Defaults to the value in `server_or_cluster_def`, if specified. Otherwise defaults to 0 if the server's job has only one task. protocol: (Optional.) Specifies the protocol to be used by the server. Acceptable values include `"grpc", "grpc+verbs"`. Defaults to the value in `server_or_cluster_def`, if specified. Otherwise defaults to `"grpc"`. config: (Options.) A `tf.ConfigProto` that specifies default configuration options for all sessions that run on this server. Returns: A `tf.train.ServerDef`. Raises: TypeError: If the arguments do not have the appropriate type. ValueError: If an argument is not specified and cannot be inferred. """ server_def = tensorflow_server_pb2.ServerDef() if isinstance(server_or_cluster_def, tensorflow_server_pb2.ServerDef): server_def.MergeFrom(server_or_cluster_def) if job_name is not None: server_def.job_name = job_name if task_index is not None: server_def.task_index = task_index if protocol is not None: server_def.protocol = protocol if config is not None: server_def.default_session_config.MergeFrom(config) else: try: cluster_spec = ClusterSpec(server_or_cluster_def) except TypeError: raise TypeError("Could not convert `server_or_cluster_def` to a " "`tf.train.ServerDef` or `tf.train.ClusterSpec`.") if job_name is None: if len(cluster_spec.jobs) == 1: job_name = cluster_spec.jobs[0] else: raise ValueError("Must specify an explicit `job_name`.") if task_index is None: task_indices = cluster_spec.task_indices(job_name) if len(task_indices) == 1: task_index = task_indices[0] else: raise ValueError("Must specify an explicit `task_index`.") if protocol is None: protocol = "grpc" server_def = tensorflow_server_pb2.ServerDef( cluster=cluster_spec.as_cluster_def(), job_name=job_name, task_index=task_index, protocol=protocol) if config is not None: server_def.default_session_config.MergeFrom(config) return server_def @tf_export("train.Server") class Server(object): """An in-process TensorFlow server, for use in distributed training. A `tf.train.Server` instance encapsulates a set of devices and a `tf.Session` target that can participate in distributed training. A server belongs to a cluster (specified by a `tf.train.ClusterSpec`), and corresponds to a particular task in a named job. The server can communicate with any other server in the same cluster. """ def __init__(self, server_or_cluster_def, job_name=None, task_index=None, protocol=None, config=None, start=True): """Creates a new server with the given definition. The `job_name`, `task_index`, and `protocol` arguments are optional, and override any information provided in `server_or_cluster_def`. Args: server_or_cluster_def: A `tf.train.ServerDef` or `tf.train.ClusterDef` protocol buffer, or a `tf.train.ClusterSpec` object, describing the server to be created and/or the cluster of which it is a member. job_name: (Optional.) Specifies the name of the job of which the server is a member. Defaults to the value in `server_or_cluster_def`, if specified. task_index: (Optional.) Specifies the task index of the server in its job. Defaults to the value in `server_or_cluster_def`, if specified. Otherwise defaults to 0 if the server's job has only one task. protocol: (Optional.) Specifies the protocol to be used by the server. Acceptable values include `"grpc", "grpc+verbs"`. Defaults to the value in `server_or_cluster_def`, if specified. Otherwise defaults to `"grpc"`. config: (Options.) A `tf.ConfigProto` that specifies default configuration options for all sessions that run on this server. start: (Optional.) Boolean, indicating whether to start the server after creating it. Defaults to `True`. Raises: tf.errors.OpError: Or one of its subclasses if an error occurs while creating the TensorFlow server. """ self._server_def = _make_server_def(server_or_cluster_def, job_name, task_index, protocol, config) self._server = c_api.TF_NewServer(self._server_def.SerializeToString()) if start: self.start() def __del__(self): try: c_api.TF_ServerStop(self._server) # Clean shutdown of servers is not yet implemented, so # we leak instead of calling c_api.TF_DeleteServer here. # See: # https://github.com/tensorflow/tensorflow/blob/0495317a6e9dd4cac577b9d5cf9525e62b571018/tensorflow/core/distributed_runtime/rpc/grpc_server_lib.h#L73 except errors.UnimplementedError: pass except AttributeError: # At shutdown, `c_api` may have been garbage collected. pass self._server = None def start(self): """Starts this server. Raises: tf.errors.OpError: Or one of its subclasses if an error occurs while starting the TensorFlow server. """ c_api.TF_ServerStart(self._server) def join(self): """Blocks until the server has shut down. This method currently blocks forever. Raises: tf.errors.OpError: Or one of its subclasses if an error occurs while joining the TensorFlow server. """ c_api.TF_ServerJoin(self._server) @property def server_def(self): """Returns the `tf.train.ServerDef` for this server. Returns: A `tf.train.ServerDef` protocol buffer that describes the configuration of this server. """ return self._server_def @property def target(self): """Returns the target for a `tf.Session` to connect to this server. To create a `tf.Session` that connects to this server, use the following snippet: ```python server = tf.train.Server(...) with tf.Session(server.target): # ... ``` Returns: A string containing a session target for this server. """ return c_api.TF_ServerTarget(self._server) @staticmethod def create_local_server(config=None, start=True): """Creates a new single-process cluster running on the local host. This method is a convenience wrapper for creating a `tf.train.Server` with a `tf.train.ServerDef` that specifies a single-process cluster containing a single task in a job called `"local"`. Args: config: (Options.) A `tf.ConfigProto` that specifies default configuration options for all sessions that run on this server. start: (Optional.) Boolean, indicating whether to start the server after creating it. Defaults to `True`. Returns: A local `tf.train.Server`. """ # Specifying port 0 means that the OS will choose a free port for the # server. return Server({"local": ["localhost:0"]}, protocol="grpc", config=config, start=start) @tf_export("train.ClusterSpec") class ClusterSpec(object): """Represents a cluster as a set of "tasks", organized into "jobs". A `tf.train.ClusterSpec` represents the set of processes that participate in a distributed TensorFlow computation. Every `tf.train.Server` is constructed in a particular cluster. To create a cluster with two jobs and five tasks, you specify the mapping from job names to lists of network addresses (typically hostname-port pairs). ```python cluster = tf.train.ClusterSpec({"worker": ["worker0.example.com:2222", "worker1.example.com:2222", "worker2.example.com:2222"], "ps": ["ps0.example.com:2222", "ps1.example.com:2222"]}) ``` Each job may also be specified as a sparse mapping from task indices to network addresses. This enables a server to be configured without needing to know the identity of (for example) all other worker tasks: ```python cluster = tf.train.ClusterSpec({"worker": {1: "worker1.example.com:2222"}, "ps": ["ps0.example.com:2222", "ps1.example.com:2222"]}) ``` """ def __init__(self, cluster): """Creates a `ClusterSpec`. Args: cluster: A dictionary mapping one or more job names to (i) a list of network addresses, or (ii) a dictionary mapping integer task indices to network addresses; or a `tf.train.ClusterDef` protocol buffer. Raises: TypeError: If `cluster` is not a dictionary mapping strings to lists of strings, and not a `tf.train.ClusterDef` protobuf. """ if isinstance(cluster, dict): self._cluster_spec = {} for job_name, tasks in cluster.items(): if isinstance(tasks, (list, tuple)): job_tasks = {i: task for i, task in enumerate(tasks)} elif isinstance(tasks, dict): job_tasks = {i: task for i, task in tasks.items()} else: raise TypeError("The tasks for job %r must be a list or a dictionary " "from integers to strings." % job_name) self._cluster_spec[job_name] = job_tasks self._make_cluster_def() elif isinstance(cluster, cluster_pb2.ClusterDef): self._cluster_def = cluster self._cluster_spec = {} for job_def in self._cluster_def.job: self._cluster_spec[job_def.name] = { i: t for i, t in job_def.tasks.items()} elif isinstance(cluster, ClusterSpec): self._cluster_def = cluster_pb2.ClusterDef() self._cluster_def.MergeFrom(cluster.as_cluster_def()) self._cluster_spec = {} for job_def in self._cluster_def.job: self._cluster_spec[job_def.name] = { i: t for i, t in job_def.tasks.items()} else: raise TypeError("`cluster` must be a dictionary mapping one or more " "job names to lists of network addresses, or a " "`ClusterDef` protocol buffer") def __nonzero__(self): return bool(self._cluster_spec) # Python 3.x __bool__ = __nonzero__ def __eq__(self, other): return self._cluster_spec == other def __ne__(self, other): return self._cluster_spec != other def __str__(self): key_values = self.as_dict() string_items = [ repr(k) + ": " + repr(key_values[k]) for k in sorted(key_values)] return "ClusterSpec({" + ", ".join(string_items) + "})" def as_dict(self): """Returns a dictionary from job names to their tasks. For each job, if the task index space is dense, the corresponding value will be a list of network addresses; otherwise it will be a dictionary mapping (sparse) task indices to the corresponding addresses. Returns: A dictionary mapping job names to lists or dictionaries describing the tasks in those jobs. """ ret = {} for job in self.jobs: task_indices = self.task_indices(job) if max(task_indices) + 1 == len(task_indices): # Return a list because the task indices are dense. This # matches the behavior of `as_dict()` before support for # sparse jobs was added. ret[job] = self.job_tasks(job) else: ret[job] = {i: self.task_address(job, i) for i in task_indices} return ret def as_cluster_def(self): """Returns a `tf.train.ClusterDef` protocol buffer based on this cluster.""" return self._cluster_def @property def jobs(self): """Returns a list of job names in this cluster. Returns: A list of strings, corresponding to the names of jobs in this cluster. """ return list(self._cluster_spec.keys()) def num_tasks(self, job_name): """Returns the number of tasks defined in the given job. Args: job_name: The string name of a job in this cluster. Returns: The number of tasks defined in the given job. Raises: ValueError: If `job_name` does not name a job in this cluster. """ try: job = self._cluster_spec[job_name] except KeyError: raise ValueError("No such job in cluster: %r" % job_name) return len(job) def task_indices(self, job_name): """Returns a list of valid task indices in the given job. Args: job_name: The string name of a job in this cluster. Returns: A list of valid task indices in the given job. Raises: ValueError: If `job_name` does not name a job in this cluster, or no task with index `task_index` is defined in that job. """ try: job = self._cluster_spec[job_name] except KeyError: raise ValueError("No such job in cluster: %r" % job_name) return list(sorted(job.keys())) def task_address(self, job_name, task_index): """Returns the address of the given task in the given job. Args: job_name: The string name of a job in this cluster. task_index: A non-negative integer. Returns: The address of the given task in the given job. Raises: ValueError: If `job_name` does not name a job in this cluster, or no task with index `task_index` is defined in that job. """ try: job = self._cluster_spec[job_name] except KeyError: raise ValueError("No such job in cluster: %r" % job_name) try: return job[task_index] except KeyError: raise ValueError("No task with index %r in job %r" % (task_index, job_name)) def job_tasks(self, job_name): """Returns a mapping from task ID to address in the given job. NOTE: For backwards compatibility, this method returns a list. If the given job was defined with a sparse set of task indices, the length of this list may not reflect the number of tasks defined in this job. Use the `tf.train.ClusterSpec.num_tasks` method to find the number of tasks defined in a particular job. Args: job_name: The string name of a job in this cluster. Returns: A list of task addresses, where the index in the list corresponds to the task index of each task. The list may contain `None` if the job was defined with a sparse set of task indices. Raises: ValueError: If `job_name` does not name a job in this cluster. """ try: job = self._cluster_spec[job_name] except KeyError: raise ValueError("No such job in cluster: %r" % job_name) ret = [None for _ in range(max(job.keys()) + 1)] for i, task in job.items(): ret[i] = task return ret def _make_cluster_def(self): """Creates a `tf.train.ClusterDef` based on the given `cluster_spec`. Raises: TypeError: If `cluster_spec` is not a dictionary mapping strings to lists of strings. """ self._cluster_def = cluster_pb2.ClusterDef() # NOTE(mrry): Sort by job_name to produce deterministic protobufs. for job_name, tasks in sorted(self._cluster_spec.items()): try: job_name = compat.as_bytes(job_name) except TypeError: raise TypeError("Job name %r must be bytes or unicode" % job_name) job_def = self._cluster_def.job.add() job_def.name = job_name for i, task_address in sorted(tasks.items()): try: task_address = compat.as_bytes(task_address) except TypeError: raise TypeError( "Task address %r must be bytes or unicode" % task_address) job_def.tasks[i] = task_address
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import logging import os from hashlib import sha1 from six import string_types from twitter.common.collections import OrderedSet, maybe_list from pants.base.build_environment import get_buildroot from pants.base.exceptions import TargetDefinitionException from pants.base.fingerprint_strategy import DefaultFingerprintStrategy from pants.base.hash_utils import hash_all from pants.base.payload import Payload from pants.base.payload_field import PrimitiveField from pants.base.validation import assert_list from pants.build_graph.address import Address from pants.build_graph.address_lookup_error import AddressLookupError from pants.build_graph.target_addressable import TargetAddressable from pants.build_graph.target_scopes import Scope from pants.source.payload_fields import SourcesField from pants.source.wrapped_globs import Files, FilesetWithSpec, Globs from pants.subsystem.subsystem import Subsystem from pants.util.memo import memoized_property logger = logging.getLogger(__name__) class AbstractTarget(object): @classmethod def subsystems(cls): """The subsystems this target uses. Targets always use the global subsystem instance. They have no notion of any other scope. :API: public :return: A tuple of subsystem types. """ return tuple() @classmethod def alias(cls): """Subclasses should return their desired BUILD file alias. :rtype: string """ raise NotImplementedError() class Target(AbstractTarget): """A generic target used to group dependencies. The baseclass for all pants targets. Handles registration of a target amongst all parsed targets as well as location of the target parse context. :API: public """ class RecursiveDepthError(AddressLookupError): """Raised when there are too many recursive calls to calculate the fingerprint.""" _MAX_RECURSION_DEPTH = 250 class WrongNumberOfAddresses(Exception): """Internal error, too many elements in Addresses :API: public """ class IllegalArgument(TargetDefinitionException): """Argument that isn't allowed supplied to Target. :API: public """ class Arguments(Subsystem): """Options relating to handling target arguments.""" class UnknownArgumentError(TargetDefinitionException): """An unknown keyword argument was supplied to Target.""" options_scope = 'target-arguments' @classmethod def register_options(cls, register): register('--ignored', advanced=True, type=dict, help='Map of target name to a list of keyword arguments that should be ignored if a ' 'target receives them unexpectedly. Typically used to allow usage of arguments ' 'in BUILD files that are not yet available in the current version of pants.') @classmethod def check(cls, target, kwargs): """ :API: public """ cls.global_instance().check_unknown(target, kwargs) def check_unknown(self, target, kwargs): """ :API: public """ ignore_params = set((self.get_options().ignored or {}).get(target.type_alias, ())) unknown_args = {arg: value for arg, value in kwargs.items() if arg not in ignore_params} ignored_args = {arg: value for arg, value in kwargs.items() if arg in ignore_params} if ignored_args: logger.debug('{target} ignoring the unimplemented arguments: {args}' .format(target=target.address.spec, args=', '.join('{} = {}'.format(key, val) for key, val in ignored_args.items()))) if unknown_args: error_message = '{target_type} received unknown arguments: {args}' raise self.UnknownArgumentError(target.address.spec, error_message.format( target_type=type(target).__name__, args=''.join('\n {} = {}'.format(key, value) for key, value in unknown_args.items()) )) @classmethod def subsystems(cls): return super(Target, cls).subsystems() + (cls.Arguments,) @classmethod def get_addressable_type(target_cls): """ :API: public """ class ConcreteTargetAddressable(TargetAddressable): @classmethod def get_target_type(cls): return target_cls return ConcreteTargetAddressable @memoized_property def target_base(self): """ :API: public :returns: the source root path for this target. """ source_root = self._sources_field.source_root if not source_root: raise TargetDefinitionException(self, 'Not under any configured source root.') return source_root.path @classmethod def identify(cls, targets): """Generates an id for a set of targets. :API: public """ return cls.combine_ids(target.id for target in targets) @classmethod def maybe_readable_identify(cls, targets): """Generates an id for a set of targets. If the set is a single target, just use that target's id. :API: public """ return cls.maybe_readable_combine_ids([target.id for target in targets]) @classmethod def compute_target_id(cls, address): """Computes a target id from the given address.""" id_candidate = address.path_safe_spec if len(id_candidate) >= 200: # two dots + 79 char head + 79 char tail + 40 char sha1 return '{}.{}.{}'.format(id_candidate[:79], sha1(id_candidate).hexdigest(), id_candidate[-79:]) return id_candidate @staticmethod def combine_ids(ids): """Generates a combined id for a set of ids. :API: public """ return hash_all(sorted(ids)) # We sort so that the id isn't sensitive to order. @classmethod def maybe_readable_combine_ids(cls, ids): """Generates combined id for a set of ids, but if the set is a single id, just use that. :API: public """ ids = list(ids) # We can't len a generator. return ids[0] if len(ids) == 1 else cls.combine_ids(ids) @classmethod def _closure_dep_predicate(cls, roots, include_scopes=None, exclude_scopes=None, respect_intransitive=False): if not respect_intransitive and include_scopes is None and exclude_scopes is None: return None root_lookup = set(roots) def predicate(target, dep_target): if not dep_target.scope.in_scope(include_scopes=include_scopes, exclude_scopes=exclude_scopes): return False # dep_target.transitive == False means that dep_target is only included if target is a root target. if respect_intransitive and not dep_target.transitive and target not in root_lookup: return False return True return predicate @classmethod def closure_for_targets(cls, target_roots, exclude_scopes=None, include_scopes=None, bfs=None, postorder=None, respect_intransitive=False): """Computes the closure of the given targets respecting the given input scopes. :API: public :param list target_roots: The list of Targets to start from. These targets will always be included in the closure, regardless of scope settings. :param Scope exclude_scopes: If present and non-empty, only dependencies which have none of the scope names in this Scope will be traversed. :param Scope include_scopes: If present and non-empty, only dependencies which have at least one of the scope names in this Scope will be traversed. :param bool bfs: Whether to traverse in breadth-first or depth-first order. (Defaults to True). :param bool respect_intransitive: If True, any dependencies which have the 'intransitive' scope will not be included unless they are direct dependencies of one of the root targets. (Defaults to False). """ target_roots = list(target_roots) # Sometimes generators are passed into this function. if not target_roots: return OrderedSet() build_graph = target_roots[0]._build_graph addresses = [target.address for target in target_roots] dep_predicate = cls._closure_dep_predicate(target_roots, include_scopes=include_scopes, exclude_scopes=exclude_scopes, respect_intransitive=respect_intransitive) closure = OrderedSet() if not bfs: build_graph.walk_transitive_dependency_graph( addresses=addresses, work=closure.add, postorder=postorder, dep_predicate=dep_predicate, ) else: closure.update(build_graph.transitive_subgraph_of_addresses_bfs( addresses=addresses, dep_predicate=dep_predicate, )) # Make sure all the roots made it into the closure. closure.update(target_roots) return closure def __init__(self, name, address, build_graph, type_alias=None, payload=None, tags=None, description=None, no_cache=False, scope=None, _transitive=None, **kwargs): """ :API: public :param string name: The name of this target, which combined with this build file defines the target address. :param dependencies: Target address specs of other targets that this target depends on. :type dependencies: list of strings :param address: The Address that maps to this Target in the BuildGraph. :type address: :class:`pants.build_graph.address.Address` :param build_graph: The BuildGraph that this Target lives within. :type build_graph: :class:`pants.build_graph.build_graph.BuildGraph` :param string type_alias: The type_alias used to construct this target, may be None if constructed directly. :param payload: The configuration encapsulated by this target. Also in charge of most fingerprinting details. :type payload: :class:`pants.base.payload.Payload` :param tags: Arbitrary string tags that describe this target. Usable by downstream/custom tasks for reasoning about the build graph. NOT included in payloads and thus not used in fingerprinting, thus not suitable for anything that affects how a particular target is built. :type tags: :class:`collections.Iterable` of strings :param no_cache: If True, results for this target should not be stored in the artifact cache. :param string description: Human-readable description of this target. :param string scope: The scope of this target, used to determine its inclusion on the classpath (and possibly more things in the future). See :class:`pants.build_graph.target_scopes.Scopes`. A value of None, '', or 'default' results in the default scope, which is included everywhere. """ # NB: dependencies are in the pydoc above as a BUILD dictionary hack only; implementation hides # the dependencies via TargetAddressable. self.payload = payload or Payload() self._scope = Scope(scope) self.payload.add_field('scope_string', PrimitiveField(str(scope))) self.payload.add_field('transitive', PrimitiveField(True if _transitive is None else _transitive)) self.payload.freeze() self.name = name self.address = address self._build_graph = build_graph self._type_alias = type_alias self._tags = set(tags or []) self.description = description self._cached_fingerprint_map = {} self._cached_all_transitive_fingerprint_map = {} self._cached_direct_transitive_fingerprint_map = {} self._cached_strict_dependencies_map = {} self._cached_exports_addresses = None self._no_cache = no_cache if kwargs: self.Arguments.check(self, kwargs) @property def scope(self): return self._scope @property def transitive(self): return self.payload.transitive @property def no_cache(self): return self._no_cache @property def type_alias(self): """Returns the type alias this target was constructed via. For a target read from a BUILD file, this will be target alias, like 'java_library'. For a target constructed in memory, this will be the simple class name, like 'JavaLibrary'. The end result is that the type alias should be the most natural way to refer to this target's type to the author of the target instance. :API: public :rtype: string """ return self._type_alias or type(self).__name__ @property def tags(self): """ :API: public """ return self._tags def assert_list(self, putative_list, expected_type=string_types, key_arg=None): """ :API: public """ return assert_list(putative_list, expected_type, key_arg=key_arg, raise_type=lambda msg: TargetDefinitionException(self, msg)) def compute_invalidation_hash(self, fingerprint_strategy=None): """ :API: public :param FingerprintStrategy fingerprint_strategy: optional fingerprint strategy to use to compute the fingerprint of a target :return: a fingerprint representing this target (no dependencies) :rtype: string """ fingerprint_strategy = fingerprint_strategy or DefaultFingerprintStrategy() return fingerprint_strategy.fingerprint_target(self) def invalidation_hash(self, fingerprint_strategy=None): """ :API: public """ fingerprint_strategy = fingerprint_strategy or DefaultFingerprintStrategy() if fingerprint_strategy not in self._cached_fingerprint_map: self._cached_fingerprint_map[fingerprint_strategy] = self.compute_invalidation_hash(fingerprint_strategy) return self._cached_fingerprint_map[fingerprint_strategy] def mark_extra_invalidation_hash_dirty(self): """ :API: public """ def mark_invalidation_hash_dirty(self): """Invalidates memoized fingerprints for this target, including those in payloads. Exposed for testing. :API: public """ self._cached_fingerprint_map = {} self._cached_all_transitive_fingerprint_map = {} self._cached_direct_transitive_fingerprint_map = {} self._cached_strict_dependencies_map = {} self._cached_exports_addresses = None self.mark_extra_invalidation_hash_dirty() self.payload.mark_dirty() def transitive_invalidation_hash(self, fingerprint_strategy=None, depth=0): """ :API: public :param FingerprintStrategy fingerprint_strategy: optional fingerprint strategy to use to compute the fingerprint of a target :return: A fingerprint representing this target and all of its dependencies. The return value can be `None`, indicating that this target and all of its transitive dependencies did not contribute to the fingerprint, according to the provided FingerprintStrategy. :rtype: string """ if depth > self._MAX_RECURSION_DEPTH: # NB(zundel) without this catch, we'll eventually hit the python stack limit # RuntimeError: maximum recursion depth exceeded while calling a Python object raise self.RecursiveDepthError("Max depth of {} exceeded.".format(self._MAX_RECURSION_DEPTH)) fingerprint_strategy = fingerprint_strategy or DefaultFingerprintStrategy() direct = (depth == 0 and fingerprint_strategy.direct(self)) if direct: fingerprint_map = self._cached_direct_transitive_fingerprint_map else: fingerprint_map = self._cached_all_transitive_fingerprint_map if fingerprint_strategy not in fingerprint_map: hasher = sha1() def dep_hash_iter(): dep_list = fingerprint_strategy.dependencies(self) if direct else self.dependencies for dep in dep_list: try: if direct: dep_hash = dep.invalidation_hash(fingerprint_strategy) else: dep_hash = dep.transitive_invalidation_hash(fingerprint_strategy, depth=depth+1) if dep_hash is not None: yield dep_hash except self.RecursiveDepthError as e: raise self.RecursiveDepthError("{message}\n referenced from {spec}" .format(message=e, spec=dep.address.spec)) dep_hashes = sorted(list(dep_hash_iter())) for dep_hash in dep_hashes: hasher.update(dep_hash) target_hash = self.invalidation_hash(fingerprint_strategy) if target_hash is None and not dep_hashes: return None dependencies_hash = hasher.hexdigest()[:12] combined_hash = '{target_hash}.{deps_hash}'.format(target_hash=target_hash, deps_hash=dependencies_hash) fingerprint_map[fingerprint_strategy] = combined_hash return fingerprint_map[fingerprint_strategy] def mark_transitive_invalidation_hash_dirty(self): """ :API: public """ self._cached_all_transitive_fingerprint_map = {} self._cached_direct_transitive_fingerprint_map = {} self.mark_extra_transitive_invalidation_hash_dirty() def mark_extra_transitive_invalidation_hash_dirty(self): """ :API: public """ def inject_dependency(self, dependency_address): """ :API: public """ self._build_graph.inject_dependency(dependent=self.address, dependency=dependency_address) def invalidate_dependee(dependee): dependee.mark_transitive_invalidation_hash_dirty() self._build_graph.walk_transitive_dependee_graph([self.address], work=invalidate_dependee) @memoized_property def _sources_field(self): sources_field = self.payload.get_field('sources') if sources_field is not None: return sources_field return SourcesField(sources=FilesetWithSpec.empty(self.address.spec_path)) def has_sources(self, extension=None): """Return `True` if this target owns sources; optionally of the given `extension`. :API: public :param string extension: Optional suffix of filenames to test for. :return: `True` if the target contains sources that match the optional extension suffix. :rtype: bool """ source_paths = self._sources_field.source_paths if not source_paths: return False if not extension: return True return any(source.endswith(extension) for source in source_paths) def sources_relative_to_buildroot(self): """ :API: public """ if self.has_sources(): return self._sources_field.relative_to_buildroot() else: return [] def sources_relative_to_source_root(self): """ :API: public """ if self.has_sources(): abs_source_root = os.path.join(get_buildroot(), self.target_base) for source in self.sources_relative_to_buildroot(): abs_source = os.path.join(get_buildroot(), source) yield os.path.relpath(abs_source, abs_source_root) def globs_relative_to_buildroot(self): """ :API: public """ return self._sources_field.filespec def sources_relative_to_target_base(self): """ :API: public """ return self._sources_field.sources def sources_count(self): """Returns the count of source files owned by the target.""" return len(self._sources_field.sources.files) @property def derived_from(self): """Returns the target this target was derived from. If this target was not derived from another, returns itself. :API: public """ return self._build_graph.get_derived_from(self.address) @property def derived_from_chain(self): """Returns all targets that this target was derived from. If this target was not derived from another, returns an empty sequence. :API: public """ cur = self while cur.derived_from is not cur: cur = cur.derived_from yield cur @property def concrete_derived_from(self): """Returns the concrete target this target was (directly or indirectly) derived from. The returned target is guaranteed to not have been derived from any other target, and is thus guaranteed to be a 'real' target from a BUILD file, not a programmatically injected target. :API: public """ return self._build_graph.get_concrete_derived_from(self.address) @staticmethod def _validate_target_representation_args(kwargs, payload): assert (kwargs is None) ^ (payload is None), 'must provide either kwargs or payload' assert (kwargs is None) or isinstance(kwargs, dict), ( 'expected a `dict` object for kwargs, instead found a {}'.format(type(kwargs)) ) assert (payload is None) or isinstance(payload, Payload), ( 'expected a `Payload` object for payload, instead found a {}'.format(type(payload)) ) @classmethod def compute_injectable_specs(cls, kwargs=None, payload=None): """Given either pre-Target.__init__() kwargs or a post-Target.__init__() payload, compute the specs to inject as non-dependencies in the same vein as the prior `traversable_specs`. :API: public :param dict kwargs: The pre-Target.__init__() kwargs dict. :param Payload payload: The post-Target.__init__() Payload object. :yields: Spec strings representing dependencies of this target. """ cls._validate_target_representation_args(kwargs, payload) # N.B. This pattern turns this method into a non-yielding generator, which is helpful for # subclassing. return yield @classmethod def compute_dependency_specs(cls, kwargs=None, payload=None): """Given either pre-Target.__init__() kwargs or a post-Target.__init__() payload, compute the full set of dependency specs in the same vein as the prior `traversable_dependency_specs`. N.B. This is a temporary bridge to span the gap between v2 "Fields" products vs v1 `BuildGraph` `Target` object representations. See: https://github.com/pantsbuild/pants/issues/3560 https://github.com/pantsbuild/pants/issues/3561 :API: public :param dict kwargs: The pre-Target.__init__() kwargs dict. :param Payload payload: The post-Target.__init__() Payload object. :yields: Spec strings representing dependencies of this target. """ cls._validate_target_representation_args(kwargs, payload) # N.B. This pattern turns this method into a non-yielding generator, which is helpful for # subclassing. return yield @property def dependencies(self): """ :API: public :return: targets that this target depends on :rtype: list of Target """ return [self._build_graph.get_target(dep_address) for dep_address in self._build_graph.dependencies_of(self.address)] @property def export_addresses(self): exports = self._cached_exports_addresses if exports is None: exports = [] for export_spec in getattr(self, 'export_specs', tuple()): if isinstance(export_spec, Target): exports.append(export_spec.address) else: exports.append(Address.parse(export_spec, relative_to=self.address.spec_path)) exports = tuple(exports) dep_addresses = {d.address for d in self.dependencies} invalid_export_specs = [a.spec for a in exports if a not in dep_addresses] if len(invalid_export_specs) > 0: raise TargetDefinitionException( self, 'Invalid exports: these exports must also be dependencies\n {}'.format('\n '.join(invalid_export_specs))) self._cached_exports_addresses = exports return exports def strict_dependencies(self, dep_context): """ :param dep_context: A DependencyContext with configuration for the request. :return: targets that this target "strictly" depends on. This set of dependencies contains only directly declared dependencies, with two exceptions: 1) aliases are expanded transitively 2) the strict_dependencies of targets exported targets exported by strict_dependencies (transitively). :rtype: list of Target """ strict_deps = self._cached_strict_dependencies_map.get(dep_context, None) if strict_deps is None: default_predicate = self._closure_dep_predicate({self}, **dep_context.target_closure_kwargs) def dep_predicate(source, dependency): if not default_predicate(source, dependency): return False # Always expand aliases. if type(source) in dep_context.alias_types: return True # Traverse other dependencies if they are exported. if source._dep_is_exported(dependency): return True return False dep_addresses = [d.address for d in self.dependencies if default_predicate(self, d) ] result = self._build_graph.transitive_subgraph_of_addresses_bfs( addresses=dep_addresses, dep_predicate=dep_predicate ) strict_deps = OrderedSet() for declared in result: if type(declared) in dep_context.alias_types: continue if isinstance(declared, dep_context.compiler_plugin_types): strict_deps.update(declared.closure( bfs=True, **dep_context.target_closure_kwargs)) strict_deps.add(declared) strict_deps = list(strict_deps) self._cached_strict_dependencies_map[dep_context] = strict_deps return strict_deps def _dep_is_exported(self, dependency): return dependency.address in self.export_addresses or \ dependency.is_synthetic and (dependency.concrete_derived_from.address in self.export_addresses) @property def dependents(self): """ :API: public :return: targets that depend on this target :rtype: list of Target """ return [self._build_graph.get_target(dep_address) for dep_address in self._build_graph.dependents_of(self.address)] @property def is_synthetic(self): """ :API: public :return: True if this target did not originate from a BUILD file. """ return self.address in self._build_graph.synthetic_addresses @property def is_original(self): """ :API: public Returns ``True`` if this target is derived from no other. """ return self.derived_from == self @memoized_property def id(self): """A unique and unix safe identifier for the Target. Since other classes use this id to generate new file names and unix system has 255 character limitation on a file name, 200-character limit is chosen as a safe measure. :API: public """ return self.compute_target_id(self.address) @property def identifier(self): """ :API: public """ return self.id def walk(self, work, predicate=None): """Walk of this target's dependency graph, DFS preorder traversal, visiting each node exactly once. If a predicate is supplied it will be used to test each target before handing the target to work and descending. Work can return targets in which case these will be added to the walk candidate set if not already walked. :API: public :param work: Callable that takes a :py:class:`pants.build_graph.target.Target` as its single argument. :param predicate: Callable that takes a :py:class:`pants.build_graph.target.Target` as its single argument and returns True if the target should passed to ``work``. """ if not callable(work): raise ValueError('work must be callable but was {}'.format(work)) if predicate and not callable(predicate): raise ValueError('predicate must be callable but was {}'.format(predicate)) self._build_graph.walk_transitive_dependency_graph([self.address], work, predicate) def closure(self, *vargs, **kwargs): """Returns this target's transitive dependencies. The walk will be depth-first in preorder, or breadth first if bfs=True is specified. See Target.closure_for_targets(). :API: public """ return self.closure_for_targets([self], *vargs, **kwargs) def __lt__(self, other): return self.address < other.address def __eq__(self, other): return isinstance(other, Target) and self.address == other.address def __hash__(self): return hash(self.address) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): addr = self.address if hasattr(self, 'address') else 'address not yet set' return "{}({})".format(type(self).__name__, addr) # List of glob patterns, or a single glob pattern. # Subclasses can override, typically to specify a file extension (e.g., '*.java'). default_sources_globs = None # List of glob patterns, or a single glob pattern. # Subclasses can override, to specify files that should be excluded from the # default_sources_globs (e.g., '*Test.java'). default_sources_exclude_globs = None @classmethod def supports_default_sources(cls): """Whether this target type can provide default sources if none were specified explicitly.""" return cls.default_sources_globs is not None @classmethod def default_sources(cls, sources_rel_path): """Provide sources, if they weren't specified explicitly in the BUILD file. By default this globs over self.default_sources_globs (e.g., '*.java') but subclasses can override to provide more nuanced default behavior. In this case, the subclasses must also override supports_default_sources(). """ if cls.default_sources_globs is not None: if cls.default_sources_exclude_globs is not None: exclude = [Globs.create_fileset_with_spec(sources_rel_path, *maybe_list(cls.default_sources_exclude_globs))] else: exclude = [] return Globs.create_fileset_with_spec(sources_rel_path, *maybe_list(cls.default_sources_globs), exclude=exclude) return None def create_sources_field(self, sources, sources_rel_path, key_arg=None): """Factory method to create a SourcesField appropriate for the type of the sources object. Note that this method is called before the call to Target.__init__ so don't expect fields to be populated! :API: public :return: a payload field object representing the sources parameter :rtype: SourcesField """ if sources is None: # Make sure we don't apply the defaulting to uses of this method other than for # creating a sources= field (e.g., we also use this for creating resources= fields). # Note that the check for supports_default_sources() precedes the subsystem check. # This is so that tests don't need to set up the subsystem when creating targets that # legitimately do not require sources. if (key_arg is None or key_arg == 'sources') and self.supports_default_sources(): sources = self.default_sources(sources_rel_path) else: sources = FilesetWithSpec.empty(sources_rel_path) elif isinstance(sources, (set, list, tuple)): # Received a literal sources list: convert to a FilesetWithSpec via Files. sources = Files.create_fileset_with_spec(sources_rel_path, *sources) elif not isinstance(sources, FilesetWithSpec): key_arg_section = "'{}' to be ".format(key_arg) if key_arg else "" raise TargetDefinitionException(self, "Expected {}a glob, an address or a list, but was {}" .format(key_arg_section, type(sources))) return SourcesField(sources=sources)
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import atexit import errno import os import shutil import stat import tempfile import threading import uuid from collections import defaultdict from contextlib import contextmanager from pants.util.strutil import ensure_text def longest_dir_prefix(path, prefixes): """Given a list of prefixes, return the one that is the longest prefix to the given path. Returns None if there are no matches. """ longest_match, longest_prefix = 0, None for prefix in prefixes: if fast_relpath_optional(path, prefix) is not None and len(prefix) > longest_match: longest_match, longest_prefix = len(prefix), prefix return longest_prefix def fast_relpath(path, start): """A prefix-based relpath, with no normalization or support for returning `..`.""" relpath = fast_relpath_optional(path, start) if relpath is None: raise ValueError('{} is not a directory containing {}'.format(start, path)) return relpath def fast_relpath_optional(path, start): """A prefix-based relpath, with no normalization or support for returning `..`. Returns None if `start` is not a directory-aware prefix of `path`. """ if len(start) == 0: # Empty prefix. return path # Determine where the matchable prefix ends. pref_end = len(start) - 1 if start[-1] == '/' else len(start) if pref_end > len(path): # The prefix is too long to match. return None elif path[:pref_end] == start[:pref_end] and (len(path) == pref_end or path[pref_end] == '/'): # The prefix matches, and the entries are either identical, or the suffix indicates that # the prefix is a directory. return path[pref_end+1:] def safe_mkdir(directory, clean=False): """Ensure a directory is present. If it's not there, create it. If it is, no-op. If clean is True, ensure the dir is empty. :API: public """ if clean: safe_rmtree(directory) try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise def safe_mkdir_for(path, clean=False): """Ensure that the parent directory for a file is present. If it's not there, create it. If it is, no-op. """ safe_mkdir(os.path.dirname(path), clean=clean) def safe_mkdir_for_all(paths): """Make directories which would contain all of the passed paths. This avoids attempting to re-make the same directories, which may be noticeably expensive if many paths mostly fall in the same set of directories. :param list of str paths: The paths for which containing directories should be created. """ created_dirs = set() for path in paths: dir_to_make = os.path.dirname(path) if dir_to_make not in created_dirs: safe_mkdir(dir_to_make) created_dirs.add(dir_to_make) def safe_file_dump(filename, payload): """Write a string to a file. :param string filename: The filename of the file to write to. :param string payload: The string to write to the file. """ with safe_open(filename, 'wb') as f: f.write(payload) def read_file(filename): """Read and return the contents of a file in a single file.read(). :param string filename: The filename of the file to read. :returns: The contents of the file. :rtype: string """ with open(filename, 'rb') as f: return f.read() def safe_walk(path, **kwargs): """Just like os.walk, but ensures that the returned values are unicode objects. This isn't strictly safe, in that it is possible that some paths will not be decodeable, but that case is rare, and the only alternative is to somehow avoid all interaction between paths and unicode objects, which seems especially tough in the presence of unicode_literals. See e.g. https://mail.python.org/pipermail/python-dev/2008-December/083856.html :API: public """ # If os.walk is given a text argument, it yields text values; if it # is given a binary argument, it yields binary values. return os.walk(ensure_text(path), **kwargs) class ExistingFileError(ValueError): """Indicates a copy operation would over-write a file with a directory.""" class ExistingDirError(ValueError): """Indicates a copy operation would over-write a directory with a file.""" def mergetree(src, dst, symlinks=False, ignore=None): """Just like `shutil.copytree`, except the `dst` dir may exist. The `src` directory will be walked and its contents copied into `dst`. If `dst` already exists the `src` tree will be overlayed in it; ie: existing files in `dst` will be over-written with files from `src` when they have the same subtree path. """ safe_mkdir(dst) for src_path, dirnames, filenames in safe_walk(src, topdown=True, followlinks=True): ignorenames = () if ignore: to_ignore = ignore(src_path, dirnames + filenames) if to_ignore: ignorenames = frozenset(to_ignore) dst_path = os.path.join(dst, os.path.relpath(src_path, src)) visit_dirs = [] for dirname in dirnames: if dirname in ignorenames: continue src_dir = os.path.join(src_path, dirname) dst_dir = os.path.join(dst_path, dirname) if os.path.exists(dst_dir): if not os.path.isdir(dst_dir): raise ExistingFileError('While copying the tree at {} to {}, encountered directory {} in ' 'the source tree that already exists in the destination as a ' 'non-directory.'.format(src, dst, dst_dir)) visit_dirs.append(dirname) elif symlinks and os.path.islink(src_dir): link = os.readlink(src_dir) os.symlink(link, dst_dir) # We need to halt the walk at a symlink dir; so we do not place dirname in visit_dirs # here. else: os.makedirs(dst_dir) visit_dirs.append(dirname) # In-place mutate dirnames to halt the walk when the dir is ignored by the caller. dirnames[:] = visit_dirs for filename in filenames: if filename in ignorenames: continue dst_filename = os.path.join(dst_path, filename) if os.path.exists(dst_filename): if not os.path.isfile(dst_filename): raise ExistingDirError('While copying the tree at {} to {}, encountered file {} in the ' 'source tree that already exists in the destination as a non-file.' .format(src, dst, dst_filename)) else: os.unlink(dst_filename) src_filename = os.path.join(src_path, filename) if symlinks and os.path.islink(src_filename): link = os.readlink(src_filename) os.symlink(link, dst_filename) else: shutil.copy2(src_filename, dst_filename) _MKDTEMP_CLEANER = None _MKDTEMP_DIRS = defaultdict(set) _MKDTEMP_LOCK = threading.RLock() def _mkdtemp_atexit_cleaner(): for td in _MKDTEMP_DIRS.pop(os.getpid(), []): safe_rmtree(td) def _mkdtemp_unregister_cleaner(): global _MKDTEMP_CLEANER _MKDTEMP_CLEANER = None def _mkdtemp_register_cleaner(cleaner): global _MKDTEMP_CLEANER if not cleaner: return assert callable(cleaner) if _MKDTEMP_CLEANER is None: atexit.register(cleaner) _MKDTEMP_CLEANER = cleaner def safe_mkdtemp(cleaner=_mkdtemp_atexit_cleaner, **kw): """Create a temporary directory that is cleaned up on process exit. Arguments are as to tempfile.mkdtemp. :API: public """ # Proper lock sanitation on fork [issue 6721] would be desirable here. with _MKDTEMP_LOCK: return register_rmtree(tempfile.mkdtemp(**kw), cleaner=cleaner) def register_rmtree(directory, cleaner=_mkdtemp_atexit_cleaner): """Register an existing directory to be cleaned up at process exit.""" with _MKDTEMP_LOCK: _mkdtemp_register_cleaner(cleaner) _MKDTEMP_DIRS[os.getpid()].add(directory) return directory def safe_rmtree(directory): """Delete a directory if it's present. If it's not present, no-op. Note that if the directory argument is a symlink, only the symlink will be deleted. :API: public """ if os.path.islink(directory): safe_delete(directory) else: shutil.rmtree(directory, ignore_errors=True) def safe_open(filename, *args, **kwargs): """Open a file safely, ensuring that its directory exists. :API: public """ safe_mkdir_for(filename) return open(filename, *args, **kwargs) def safe_delete(filename): """Delete a file safely. If it's not present, no-op.""" try: os.unlink(filename) except OSError as e: if e.errno != errno.ENOENT: raise def safe_concurrent_rename(src, dst): """Rename src to dst, ignoring errors due to dst already existing. Useful when concurrent processes may attempt to create dst, and it doesn't matter who wins. """ # Delete dst, in case it existed (with old content) even before any concurrent processes # attempted this write. This ensures that at least one process writes the new content. if os.path.isdir(src): # Note that dst may not exist, so we test for the type of src. safe_rmtree(dst) else: safe_delete(dst) try: shutil.move(src, dst) except IOError as e: if e.errno != errno.EEXIST: raise def safe_rm_oldest_items_in_dir(root_dir, num_of_items_to_keep, excludes=frozenset()): """ Keep `num_of_items_to_keep` newly modified items besides `excludes` in `root_dir` then remove the rest. :param root_dir: the folder to examine :param num_of_items_to_keep: number of files/folders/symlinks to keep after the cleanup :param excludes: absolute paths excluded from removal (must be prefixed with `root_dir`) :return: none """ if os.path.isdir(root_dir): found_files = [] for old_file in os.listdir(root_dir): full_path = os.path.join(root_dir, old_file) if full_path not in excludes: found_files.append((full_path, os.path.getmtime(full_path))) found_files = sorted(found_files, key=lambda x: x[1], reverse=True) for cur_file, _ in found_files[num_of_items_to_keep:]: rm_rf(cur_file) @contextmanager def safe_concurrent_creation(target_path): """A contextmanager that yields a temporary path and renames it to a final target path when the contextmanager exits. Useful when concurrent processes may attempt to create a file, and it doesn't matter who wins. :param target_path: The final target path to rename the temporary path to. :yields: A temporary path containing the original path with a unique (uuid4) suffix. """ safe_mkdir_for(target_path) tmp_path = '{}.tmp.{}'.format(target_path, uuid.uuid4().hex) try: yield tmp_path except Exception: rm_rf(tmp_path) raise else: if os.path.exists(tmp_path): safe_concurrent_rename(tmp_path, target_path) def chmod_plus_x(path): """Equivalent of unix `chmod a+x path`""" path_mode = os.stat(path).st_mode path_mode &= int('777', 8) if path_mode & stat.S_IRUSR: path_mode |= stat.S_IXUSR if path_mode & stat.S_IRGRP: path_mode |= stat.S_IXGRP if path_mode & stat.S_IROTH: path_mode |= stat.S_IXOTH os.chmod(path, path_mode) def absolute_symlink(source_path, target_path): """Create a symlink at target pointing to source using the absolute path. :param source_path: Absolute path to source file :param target_path: Absolute path to intended symlink :raises ValueError if source_path or link_path are not unique, absolute paths :raises OSError on failure UNLESS file already exists or no such file/directory """ if not os.path.isabs(source_path): raise ValueError("Path for source : {} must be absolute".format(source_path)) if not os.path.isabs(target_path): raise ValueError("Path for link : {} must be absolute".format(target_path)) if source_path == target_path: raise ValueError("Path for link is identical to source : {}".format(source_path)) try: if os.path.lexists(target_path): if os.path.islink(target_path) or os.path.isfile(target_path): os.unlink(target_path) else: shutil.rmtree(target_path) safe_mkdir_for(target_path) os.symlink(source_path, target_path) except OSError as e: # Another run may beat us to deletion or creation. if not (e.errno == errno.EEXIST or e.errno == errno.ENOENT): raise def relative_symlink(source_path, link_path): """Create a symlink at link_path pointing to relative source :param source_path: Absolute path to source file :param link_path: Absolute path to intended symlink :raises ValueError if source_path or link_path are not unique, absolute paths :raises OSError on failure UNLESS file already exists or no such file/directory """ if not os.path.isabs(source_path): raise ValueError("Path for source:{} must be absolute".format(source_path)) if not os.path.isabs(link_path): raise ValueError("Path for link:{} must be absolute".format(link_path)) if source_path == link_path: raise ValueError("Path for link is identical to source:{}".format(source_path)) # The failure state below had a long life as an uncaught error. No behavior was changed here, it just adds a catch. # Raising an exception does differ from absolute_symlink, which takes the liberty of deleting existing directories. if os.path.isdir(link_path) and not os.path.islink(link_path): raise ValueError("Path for link would overwrite an existing directory: {}".format(link_path)) try: if os.path.lexists(link_path): os.unlink(link_path) rel_path = os.path.relpath(source_path, os.path.dirname(link_path)) os.symlink(rel_path, link_path) except OSError as e: # Another run may beat us to deletion or creation. if not (e.errno == errno.EEXIST or e.errno == errno.ENOENT): raise def relativize_path(path, rootdir): """ :API: public """ # Note that we can't test for length and return the shorter of the two, because we need these # paths to be stable across systems (e.g., because they get embedded in analysis files), # and this choice might be inconsistent across systems. So we assume the relpath is always # shorter. We relativize because of a known case of very long full path prefixes on Mesos, # so this seems like the right heuristic. # Note also that we mustn't call realpath on the path - we need to preserve the symlink structure. return os.path.relpath(path, rootdir) # When running pants under mesos/aurora, the sandbox pathname can be very long. Since it gets # prepended to most components in the classpath (some from ivy, the rest from the build), # in some runs the classpath gets too big and exceeds ARG_MAX. # We prevent this by using paths relative to the current working directory. def relativize_paths(paths, rootdir): return [relativize_path(path, rootdir) for path in paths] def touch(path, times=None): """Equivalent of unix `touch path`. :API: public :path: The file to touch. :times Either a tuple of (atime, mtime) or else a single time to use for both. If not specified both atime and mtime are updated to the current time. """ if times: if len(times) > 2: raise ValueError('times must either be a tuple of (atime, mtime) or else a single time value ' 'to use for both.') if len(times) == 1: times = (times, times) with safe_open(path, 'a'): os.utime(path, times) def recursive_dirname(f): """Given a relative path like 'a/b/c/d', yield all ascending path components like: 'a/b/c/d' 'a/b/c' 'a/b' 'a' '' """ prev = None while f != prev: yield f prev = f f = os.path.dirname(f) yield '' def get_basedir(path): """Returns the base directory of a path. Examples: get_basedir('foo/bar/baz') --> 'foo' get_basedir('/foo/bar/baz') --> '' get_basedir('foo') --> 'foo' """ return path[:path.index(os.sep)] if os.sep in path else path def rm_rf(name): """Remove a file or a directory similarly to running `rm -rf <name>` in a UNIX shell. :param str name: the name of the file or directory to remove. :raises: OSError on error. """ if not os.path.exists(name): return try: # Avoid using safe_rmtree so we can detect failures. shutil.rmtree(name) except OSError as e: if e.errno == errno.ENOTDIR: # 'Not a directory', but a file. Attempt to os.unlink the file, raising OSError on failure. safe_delete(name) elif e.errno != errno.ENOENT: # Pass on 'No such file or directory', otherwise re-raise OSError to surface perm issues etc. raise def is_executable(path): """Returns whether a path names an existing executable file.""" return os.path.isfile(path) and os.access(path, os.X_OK) def split_basename_and_dirname(path): if not os.path.isfile(path): raise ValueError("{} does not exist or is not a regular file.".format(path)) return (os.path.dirname(path), os.path.basename(path)) def check_no_overlapping_paths(paths): """Given a list of paths, ensure that all are unique and do not have the same prefix.""" for path in paths: list_copy_without_path = list(paths) list_copy_without_path.remove(path) if path in list_copy_without_path: raise ValueError('{} appeared more than once. All paths must be unique.'.format(path)) for p in list_copy_without_path: if path in p: raise ValueError('{} and {} have the same prefix. All paths must be unique and cannot overlap.'.format(path, p)) def is_readable_dir(path): """Returns whether a path names an existing directory that we can read.""" return os.path.isdir(path) and os.access(path, os.R_OK)
from jsonrpc import ServiceProxy import sys import string import getpass # ===== BEGIN USER SETTINGS ===== # if you do not set these you will be prompted for a password for every command rpcuser = "" rpcpass = "" # ====== END USER SETTINGS ====== if rpcpass == "": access = ServiceProxy("http://127.0.0.1:8419") else: access = ServiceProxy("http://"+rpcuser+":"+rpcpass+"@127.0.0.1:8419") cmd = sys.argv[1].lower() if cmd == "backupwallet": try: path = raw_input("Enter destination path/filename: ") print access.backupwallet(path) except: print "\n---An error occurred---\n" elif cmd == "encryptwallet": try: pwd = getpass.getpass(prompt="Enter passphrase: ") pwd2 = getpass.getpass(prompt="Repeat passphrase: ") if pwd == pwd2: access.encryptwallet(pwd) print "\n---Wallet encrypted. Server stopping, restart to run with encrypted wallet---\n" else: print "\n---Passphrases do not match---\n" except: print "\n---An error occurred---\n" elif cmd == "getaccount": try: addr = raw_input("Enter a Greencoin address: ") print access.getaccount(addr) except: print "\n---An error occurred---\n" elif cmd == "getaccountaddress": try: acct = raw_input("Enter an account name: ") print access.getaccountaddress(acct) except: print "\n---An error occurred---\n" elif cmd == "getaddressesbyaccount": try: acct = raw_input("Enter an account name: ") print access.getaddressesbyaccount(acct) except: print "\n---An error occurred---\n" elif cmd == "getbalance": try: acct = raw_input("Enter an account (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getbalance(acct, mc) except: print access.getbalance() except: print "\n---An error occurred---\n" elif cmd == "getblockbycount": try: height = raw_input("Height: ") print access.getblockbycount(height) except: print "\n---An error occurred---\n" elif cmd == "getblockcount": try: print access.getblockcount() except: print "\n---An error occurred---\n" elif cmd == "getblocknumber": try: print access.getblocknumber() except: print "\n---An error occurred---\n" elif cmd == "getconnectioncount": try: print access.getconnectioncount() except: print "\n---An error occurred---\n" elif cmd == "getdifficulty": try: print access.getdifficulty() except: print "\n---An error occurred---\n" elif cmd == "getgenerate": try: print access.getgenerate() except: print "\n---An error occurred---\n" elif cmd == "gethashespersec": try: print access.gethashespersec() except: print "\n---An error occurred---\n" elif cmd == "getinfo": try: print access.getinfo() except: print "\n---An error occurred---\n" elif cmd == "getnewaddress": try: acct = raw_input("Enter an account name: ") try: print access.getnewaddress(acct) except: print access.getnewaddress() except: print "\n---An error occurred---\n" elif cmd == "getreceivedbyaccount": try: acct = raw_input("Enter an account (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getreceivedbyaccount(acct, mc) except: print access.getreceivedbyaccount() except: print "\n---An error occurred---\n" elif cmd == "getreceivedbyaddress": try: addr = raw_input("Enter a Greencoin address (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getreceivedbyaddress(addr, mc) except: print access.getreceivedbyaddress() except: print "\n---An error occurred---\n" elif cmd == "gettransaction": try: txid = raw_input("Enter a transaction ID: ") print access.gettransaction(txid) except: print "\n---An error occurred---\n" elif cmd == "getwork": try: data = raw_input("Data (optional): ") try: print access.gettransaction(data) except: print access.gettransaction() except: print "\n---An error occurred---\n" elif cmd == "help": try: cmd = raw_input("Command (optional): ") try: print access.help(cmd) except: print access.help() except: print "\n---An error occurred---\n" elif cmd == "listaccounts": try: mc = raw_input("Minimum confirmations (optional): ") try: print access.listaccounts(mc) except: print access.listaccounts() except: print "\n---An error occurred---\n" elif cmd == "listreceivedbyaccount": try: mc = raw_input("Minimum confirmations (optional): ") incemp = raw_input("Include empty? (true/false, optional): ") try: print access.listreceivedbyaccount(mc, incemp) except: print access.listreceivedbyaccount() except: print "\n---An error occurred---\n" elif cmd == "listreceivedbyaddress": try: mc = raw_input("Minimum confirmations (optional): ") incemp = raw_input("Include empty? (true/false, optional): ") try: print access.listreceivedbyaddress(mc, incemp) except: print access.listreceivedbyaddress() except: print "\n---An error occurred---\n" elif cmd == "listtransactions": try: acct = raw_input("Account (optional): ") count = raw_input("Number of transactions (optional): ") frm = raw_input("Skip (optional):") try: print access.listtransactions(acct, count, frm) except: print access.listtransactions() except: print "\n---An error occurred---\n" elif cmd == "move": try: frm = raw_input("From: ") to = raw_input("To: ") amt = raw_input("Amount:") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") try: print access.move(frm, to, amt, mc, comment) except: print access.move(frm, to, amt) except: print "\n---An error occurred---\n" elif cmd == "sendfrom": try: frm = raw_input("From: ") to = raw_input("To: ") amt = raw_input("Amount:") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") commentto = raw_input("Comment-to (optional): ") try: print access.sendfrom(frm, to, amt, mc, comment, commentto) except: print access.sendfrom(frm, to, amt) except: print "\n---An error occurred---\n" elif cmd == "sendmany": try: frm = raw_input("From: ") to = raw_input("To (in format address1:amount1,address2:amount2,...): ") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") try: print access.sendmany(frm,to,mc,comment) except: print access.sendmany(frm,to) except: print "\n---An error occurred---\n" elif cmd == "sendtoaddress": try: to = raw_input("To (in format address1:amount1,address2:amount2,...): ") amt = raw_input("Amount:") comment = raw_input("Comment (optional): ") commentto = raw_input("Comment-to (optional): ") try: print access.sendtoaddress(to,amt,comment,commentto) except: print access.sendtoaddress(to,amt) except: print "\n---An error occurred---\n" elif cmd == "setaccount": try: addr = raw_input("Address: ") acct = raw_input("Account:") print access.setaccount(addr,acct) except: print "\n---An error occurred---\n" elif cmd == "setgenerate": try: gen= raw_input("Generate? (true/false): ") cpus = raw_input("Max processors/cores (-1 for unlimited, optional):") try: print access.setgenerate(gen, cpus) except: print access.setgenerate(gen) except: print "\n---An error occurred---\n" elif cmd == "settxfee": try: amt = raw_input("Amount:") print access.settxfee(amt) except: print "\n---An error occurred---\n" elif cmd == "stop": try: print access.stop() except: print "\n---An error occurred---\n" elif cmd == "validateaddress": try: addr = raw_input("Address: ") print access.validateaddress(addr) except: print "\n---An error occurred---\n" elif cmd == "walletpassphrase": try: pwd = getpass.getpass(prompt="Enter wallet passphrase: ") access.walletpassphrase(pwd, 60) print "\n---Wallet unlocked---\n" except: print "\n---An error occurred---\n" elif cmd == "walletpassphrasechange": try: pwd = getpass.getpass(prompt="Enter old wallet passphrase: ") pwd2 = getpass.getpass(prompt="Enter new wallet passphrase: ") access.walletpassphrasechange(pwd, pwd2) print print "\n---Passphrase changed---\n" except: print print "\n---An error occurred---\n" print else: print "Command not found or not supported"
# -*- coding: utf-8 -*- """ Created on Tue Apr 25 19:12:18 2017 @author: pablo """ import os dir_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import sys sys.path.append(dir_path) #change to src from src import np,math,interp1d,Hyperplume,griddata,interp2d,plt import matplotlib.lines as mlines class AEM(Hyperplume): """Asymptotic Expansion Model of a plasma plume expansion.Class AEM inherits methods from parent class Hyperplume, and particularizes them.All initial inputs must be given in dimensional form. """ def __init__(self,plasma={'Electrons': {'Gamma': 1,'T_0_electron': 2.1801714e-19,'q_electron': -1.6e-19},'Ions': {'mass_ion': 2.1801714e-25, 'q_ion': 1.6e-19}},z_span=np.linspace(0,100,500),r_span=np.linspace(0,40,500),n_init=np.linspace(1,100,500),uz_init=np.linspace(1,100,500),ur_init=np.linspace(0,100,500),sol_order=0): """ Class method __init__ is used as class constructor. Calls parent class Hyperplume constructor method __init__ to store main plasma properties as attributes in the class. Args: plasma (dict): simple_plasma object dictionary containing basic plasma parameters. z_span (numpy.ndarray): axial region where the problem will be integrated. r_span (numpy.ndarray): initial far-field plasma radial profile. n_init (numpy.ndarray): initial far-field plum density front. uz_init (numpy.ndarray): initial far-region plume axial velocity profile ur_init (numpy.ndarray): initial fr-region plume radial velocity profile sol_order (int): Integer defining the AEM correction order for the plume integration. -0: AEM "cold beam" zeroth order solution -1: AEM first order correction -2: Second Order Correction Usage: >>>>>> e_charge,ion_mass,Plasma_temp,gamma_value=1.6e-19,2.1801714e-25,2.1801714e-19,1 #Main Plasma Parameters >>> Plasma = Hyperplume().simple_plasma(e_charge,ion_mass,Plasma_temp,gamma_value) #Loading Plasma dict >>> z_span = np.linspace(0,110,5000) # Axial plume grid for integration >>> r_0 = np.linspace(0,10,5000) #Initial plume radial profile >>> n0 = np.exp(-6.15/2 * r_0**2) #Initial far-field plume density >>> uz0,,ur0 = np.linspace(20000,20000,100),np.linspace(0,40000,100) #Intial far-field plume axial and radial velocity fronts >>> AEM_Order = 2 # AEM model solution >>> PlumeAEM = AEM(Plasma,z_span,eta_0,n0,uz0,ur0,AEM_Order) #Creation of AEM plume Other important class attributes loaded in the AEM constructor are: d0 (numpy.ndarray): far field initial divergence ur0/uz0. d0p (numpy.ndarray): derivative of plume initial divergence eps (float): AEM expansion parameter 1/M_{0}^{2} uz0p (numpy.ndarray): derivative of initial far region axial velocity duz0p (numpy.ndarray): derivative of initial far region radial velocity z_grid,r_grid (numpy.ndarray): Plume grids where AEM problem is integrated To access these attributes, for instance: >>> print(PlumeAEM.d0) >>> print(PlumeAEM.eps) """ #Call parent class Hyperplume constructor method to store main plasma properties as attributes in the AEM class.""" super(AEM,self).__init__(plasma,z_span,r_span,n_init) self.uz0,self.ur0,self.d0 = uz_init,ur_init,ur_init/uz_init #Load additional AEM plasma plume properties self.alpha0=math.degrees(math.atan(interp1d(self.eta,self.d0)(1))) #Initial Plume divergence at the 95% streamline self.order = sol_order #AEM Solution Order self.eps = self.Gamma*self.T_0/(self.m_ion*(uz_init[0]**2 + ur_init[0]**2)) #residual expansion parameter. Inverse of squared Mach Number self.M0 = np.sqrt(1/self.eps) #Plume Mach Nmeber "Derivatives of initial front" self.d0p = self.eta_deriver(self.eta,self.d0) #derivative of plume divergence self.d0p[0],self.d0p[-1] = self.d0[1]/self.eta[1],self.d0p[-2] + (self.d0p[-2] - self.d0p[-3]) #Edge vetor prime conditions self.uz0p = self.eta_deriver(self.eta,self.uz0) #derivative of initial axial velocity self.uz0p[0],self.uz0p[-1] = 0,self.uz0p[-2] + (self.uz0p[-2] - self.uz0p[-3]) self.duz0p = self.eta_deriver(self.eta,self.d0*self.uz0) #derivatie of initial radial velocity self.duz0p[0],self.duz0p[-1] = self.duz0p[1]/self.eta[1],self.duz0p[-2] + (self.duz0p[-2] - self.duz0p[-3]) "Grid Set Up" self.z_grid,self.r_grid = self.grid_setup(self.z_span.size,self.eta.size) #2D grids of z, and r points in the plume def solver(self): """ Class method Solver integrates the AEM model equations in the specified plume grid. The method stores the different order plasma properties in matrixes of size (mxn), where m,n are the number of z,r points,respectively.Porperties such as density,temperature,electric field,etc are calculated and saved as attributes of the class in this matrix form. Usage: >>> PlumeAEM = AEM(Plasma,z_span,eta_0,n0,uz0,ur0,AEM_Order) #Creation of AEM plume >>> PlumeAEM.solver() # be sure to create a valid AEM plasma plume before applying the plume solver method Main Plume properties solved and saved by the method as class attributes: lnn (numpy.ndarray): 3-D matrix containing density values (logarithmic) for the three possible AEM solution orders. uz (numpy.ndarray): 3-D matrix containing axial velocity values for the three possible AEM solution orders. ur (numpy.ndarray): 3-D matrix containing radial velocity values for the three possible AEM solution orders. T (numpy.ndarray): 3-D matrix containing plasma Temperature values for the three possible AEM solution orders. phi (numpy.ndarray):3-D matrix containing plasma ambipolar electric field for the three possible AEM solution orders. div (numpy.ndarray): 3-D matrix containing plume divergence values for the three possible AEM solution orders. eta_ (int,numpy.ndarray): 3-D matrix containing ion current streamlines for the three possible AEM solution orders. To access these varibles,for instance: >>> PlumeAEM.lnn[0,:,:] #density values for Cold Beam Zeroth Order AEM solution of plume expansion in the grid >>> PlumeAEM.uz[1,:,:] # axial velocity First Order AEM solution >>> PlumeAEM.T[2,:,:] ## Temperature values for Second Order AEM solution """ self.__zpts = np.shape(self.z_grid)[1] #Number of axial steps self.__epts = np.shape(self.r_grid)[0] #Number of radial steps self.uz = np.zeros((3,self.__epts,self.__zpts)) #3D matrix containing the axial velocity solutions for zeroth,first and second order self.ur = np.zeros((3,self.__epts,self.__zpts)) #3D matrix containing the axial velocity solutions for zeroth,first and second order self.div = np.zeros((3,self.__epts,self.__zpts)) #3D matrix containing the plume divergence solutions for zeroth,first and second order self.lnn = np.zeros((3,self.__epts,self.__zpts)) #3D matrix containing the natural logarothm of density solutions for zeroth,first and second order self.T = np.zeros((3,self.__epts,self.__zpts)) #3D matrix containing the plasma temperature solutions for zeroth,first and second order self.phi = np.zeros((3,self.__epts,self.__zpts)) #3D matrix containing the electric potential solutions for zeroth,first and second order self.eta_ = np.zeros((3,self.__epts,self.__zpts)) #3D matrix containing the eta lines for zeroth,first and second order """COMPUTE COLD PLASMA BEAM (ZEROTH ORDER) SOLUTION""" self.uz_0 = np.zeros((self.__epts, self.__zpts)) #matrix containing cold plasma axial velocity self.ur_0 = np.zeros((self.__epts, self.__zpts)) #matrix containing zeroth order radial velocity n_0 = np.zeros((self.__epts, self.__zpts)) #matrix containing zeroth order plasma density self.lnn_0 = np.zeros((self.__epts, self.__zpts)) #matrix containing natural logarithm of density """ADVANCES IN AXIAL DIRECTION""" for i in range(0,self.__zpts): "Calculation of properties at plume axis r = 0" z = self.z_grid[0,i] # Step in z-grid n_0[0,i] = self.n0[0] / (1 + self.d0p[0] * z)**2 #COMPUTATION OF DENSITY WHEN r0 --> 0, ON THE AXIS.Apply L'Hopital to equation 3.2 in paper" self.uz_0[0,i] = self.uz0[0] #Axial velocity at axis is kept constant and equal to origin velocity self.ur_0[0,i] = 0 #No radial velocity at axis for j in range(1,self.__epts): "ADVANCE IN THE RADIAL DIRECTION" r0 = self.eta[j] #Updating radial coordinate self.uz_0[j,i] = self.uz0[j] #Updating axial velocity self.ur_0[j,i] = self.uz0[j]*self.d0[j] #updating radial velocity "COMPUTATION OF DENSITY" n_0[j,i] = self.n0[j] / ((1 + self.d0p[j] * z) * (1 + self.d0[j] * z / r0 )) #updating density "Updating plume variable arrays with Zeroth-Order plasma plume reults" self.lnn_0[:,:] = np.log(n_0[:,:]) self.uz[0,:,:] = self.uz_0 self.ur[0,:,:] = self.ur_0 self.lnn[0,:,:] = self.lnn_0 self.div[0,:,:] = self.ur[0,:,:]/ self.uz[0,:,:] self.T[0,:,:] = super(AEM,self).temp(n_0[:,:],self.n0[0],self.T_0,self.Gamma) #Calling parent class method Hyperplume.temp() to calculate plume cold beam temperature based on density self.phi[0,:,:] = super(AEM,self).phi(n_0[:,:],self.n0[0],self.T_0,self.Gamma,self.q_ion) #Calling parent class method Hyperplume.phi() to calculate plume cold beam potential based on density self.eta_[0,:,:] = self.r_grid-self.div[0,:,:]*self.z_grid #Zeroth order eta-lines based on theory (paper equation no.) """COMPUTE FIRST ORDER CORRECTION OF PLUME VARIABLES""" zed = np.zeros((self.__zpts,1)) #array of axial steps zed[:,0] = self.z_grid[0,:] #redimensioning zstep = zed[1]-zed[0] #integer measuing the axial step of the grid.Assumes linearly spaced z points dlnn_dz_0, dlnn_dr_0 = self.partial_derivs(self.lnn_0, 0) #GET REQUIRED DERIVATIVES OF ZEROTH ORDER DENSITY (LOGARITHMIC) ALONG GRID POINTS "COMPUTE FIRST ORDER CONTRIBUTION OF VELOCITIES. EULER METHOD APPLIED TO ALL STREAMLINES" self.uz_1 = np.zeros((self.__epts,self.__zpts)) #matrix containing first order axial velocity self.ur_1 = np.zeros((self.__epts,self.__zpts)) #matrix containing first order radial velocity n1 = np.zeros((self.__epts,self.__zpts)) #matrix containing first order radial velocity for i in range(1,self.__zpts): "Computation of the first order velocity perturbation along one streamline. Euler method applied to all the streamlines at the same time" self.uz_1[:,i] = self.uz_1[:,i-1] + zstep * self.uz0[0]**2 / self.uz0 * ( 1/self.uz0[0]**2 * self.uz0p / (1+self.d0p*zed[i-1]) * (self.d0 * self.uz_1[:,i-1] - self.ur_1[:,i-1]) - (n_0[:,i-1]/self.n0[0]) ** (self.Gamma-1) * dlnn_dz_0[:,i-1] ) self.ur_1[:,i] = self.ur_1[:,i-1] + zstep * self.uz0[0]**2 / self.uz0 * ( 1/self.uz0[0]**2 * self.duz0p / (1+self.d0p*zed[i-1]) * (self.d0 * self.uz_1[:,i-1] - self.ur_1[:,i-1]) - (n_0[:,i-1]/self.n0[0]) ** (self.Gamma-1) * dlnn_dr_0[:,i-1] ) "GET REQUIRED VECTORS AND DERIVATIVES TO BE USED IN FISRT ORDER DENSITY CORRECTION" rur_1 = self.ur_1 * self.r_grid _,drur1_dr = self.partial_derivs(rur_1,0) duz1_dz,_ = self.partial_derivs(self.uz_1,0) """GET FIRST ORDER CONTRIBUTION OF THE DENSITY LOGARITHIM. EULER METHOD APPLIED TO ALL STREAMLINES.tHE FUNCTION INTEGRATES THE FIRST ORDER DENSTY PERTURBATION ALONG STREAMLINE""" self.lnn_1 = np.zeros((self.__epts,self.__zpts)) #matrix containing first order density correction(logarithmic) "Compute limit of 1/r*drur1/dr for r-->0 as second order derivative of r*ur1.Apply L'Hopital" limit = np.zeros((1,self.__zpts)) #array containing 1/r(0) * drur1(0)/dr (at the axis of plume) _,limit = self.partial_derivs(drur1_dr,0) for i in range(1,self.__zpts): "COMPUTE DENSITY FIRST ORDER SOLUTION FOR THE AXIS STREAMLINE" self.lnn_1[0,i] = self.lnn_1[0,i-1] + zstep * 1 / self.uz0[0] *( - self.uz_1[0,i-1] * dlnn_dz_0[0,i-1] - self.ur_1[0,i-1] * dlnn_dr_0[0,i-1] - duz1_dz[0,i-1] - limit[1,i-1] ) for i in range(1,self.__zpts): "COMPUTE DENSITY FIRST ORDER SOLUTION FOR ALL REMAINING STREAMLINES" self.lnn_1[1:,i] = self.lnn_1[1:,i-1] + zstep * 1 / self.uz0[1:] *( - self.uz_1[1:,i-1] * dlnn_dz_0[1:,i-1] - self.ur_1[1:,i-1] * dlnn_dr_0[1:,i-1] - duz1_dz[1:,i-1] - 1 / self.r_grid[1:,i-1] * drur1_dr[1:,i-1]) """Updating plume variable arrays with First Order Correction plasma plume reults""" self.uz[1,:,:] = self.uz[0,:,:] + self.uz_1*self.eps self.ur[1,:,:] = self.ur[0,:,:] + self.ur_1*self.eps self.lnn[1,:,:] = self.lnn[0,:,:] + self.lnn_1*self.eps n1[:,:] = np.exp(self.lnn[1,:,:]) self.div[1,:,:] = self.ur[1,:,:]/ self.uz[1,:,:] self.T [1,:,:] = super(AEM,self).temp(n1[:,:],self.n0[0],self.T_0,self.Gamma) #Calling parent class method Hyperplume.temp() to calculate plume second order solution temperature based on density self.phi[1,:,:] = super(AEM,self).phi(n1[:,:],self.n0[0],self.T_0,self.Gamma,self.q_ion) #Calling parent class method Hyperplume.phi() to calculate plume second order solution temperature based on density self.eta_[1,:,:] = self.r_grid-self.div[1,:,:]*self.z_grid #PABLO20170426this is clearly wrong. But why??, corrections are integrable along zeroth order streamlines as said in article.Matlab code calls function orbit2d.m , which I cannot understand """COMPUTE SECOND ORDER SOLUTION""" dlnn_dz_0, dlnn_dr_0 = self.partial_derivs(self.lnn_0, 0) #COMPUTE REQUIRED VECTORS AND DERIVATIVES TO BE USED IN SECOND ORDER CORRECTION CALCULATIONS dlnn_dz_1, dlnn_dr_1 = self.partial_derivs(self.lnn_1, 0) duz_dz_1, duz_dr_1 = self.partial_derivs(self.uz_1, 0) dur_dz_1, dur_dr_1 = self.partial_derivs(self.ur_1, -1) self.uz_2 = np.zeros((self.__epts,self.__zpts)) #matrix containing second order axial velocity self.ur_2 = np.zeros((self.__epts,self.__zpts)) #matrix containing second order radial velocity n2 = np.zeros((self.__epts,self.__zpts)) #matrix containing second order radial velocity for i in range(1,self.__zpts): "Computation of the second order velocity perturbation along one streamline. Euler method applied to all the streamlines at the same time" self.uz_2[:,i] = self.uz_2[:,i-1] + zstep * 1 / self.uz0 *( self.uz0p / ( 1 + self.d0p*zed[i-1] )*( self.d0* self.uz_2[:,i-1] - self.ur_2[:,i-1] )-self.uz_1[:,i-1] * duz_dz_1[:,i-1] - self.ur_1[:,i-1] * duz_dr_1[:,i-1]- self.uz0[0]**2*((n_0[:,i-1]/self.n0[0])**(self.Gamma-1) * ( (self.Gamma-1)*self.lnn_1[:,i-1] * dlnn_dz_0[:,i-1] + dlnn_dz_1[:,i-1] ) )) self.ur_2[:,i] = self.ur_2[:,i-1] + zstep * 1 / self.uz0 * ( self.duz0p / ( 1 + self.d0p*zed[i-1] )*( self.d0 * self.uz_2[:,i-1] - self.ur_2[:,i-1] )-self.uz_1[:,i-1] * dur_dz_1[:,i-1] - self.ur_1[:,i-1] * dur_dr_1[:,i-1]- self.uz0[0]**2*((n_0[:,i-1]/self.n0[0])**(self.Gamma-1) * ( (self.Gamma-1)*self.lnn_1[:,i-1] * dlnn_dr_0[:,i-1] + dlnn_dr_1[:,i-1] ) )) "GET REQUIRED VECTORS AND DERIVATIVES TO BE USED IN FISRT ORDER DENSITY CORRECTION" rur_2 = self.ur_2 * self.r_grid _,drur2_dr = self.partial_derivs(rur_2,0) duz2_dz,_ = self.partial_derivs(self.uz_2,0) """GET SECOND ORDER CONTRIBUTION OF THE DENSITY LOGARITHIM. EULER METHOD APPLIED TO ALL STREAMLINES.tHE FUNCTION INTEGRATES THE FIRST ORDER DENSTY PERTURBATION ALONG STREAMLINE""" self.lnn_2 = np.zeros((self.__epts,self.__zpts)) #matrix containing first order density (logarithmic) "Compute limit of 1/r*drur2/dr for r-->0 as second order derivative of r*ur2.Apply L'Hopital" limit = np.zeros((1,self.__zpts)) #array containing 1/r(0) * drur1(0)/dr (at the axis of plume) _,limit = self.partial_derivs(drur2_dr,0) for i in range(1,self.__zpts): "COMPUTE SOLUTION FOR THE AXIS STREAMLINE" self.lnn_2[0,i] = self.lnn_2[0,i-1] + zstep * 1 / self.uz0[0] *( - self.uz_2[0,i-1] * dlnn_dz_0[0,i-1] - self.ur_2[0,i-1] * dlnn_dr_0[0,i-1] - duz2_dz[0,i-1] - limit[0,i-1] - self.uz_1[0,i-1]*dlnn_dz_1[0,i-1] - self.ur_1[0,i-1]*dlnn_dr_1[0,i-1] ) for i in range(1,self.__zpts): "COMPUTE SOLUTION FOR ALL REMAINING STREAMLINES" self.lnn_2[1:,i] = self.lnn_2[1:,i-1] + zstep * 1 / self.uz0[1:] * (-self.uz_2[1:,i-1] * dlnn_dz_0[1:,i-1] - self.ur_2[1:,i-1] * dlnn_dr_0[1:,i-1] - duz2_dz[1:,i-1]- 1/self.r_grid[1:,i-1] * drur2_dr[1:,i-1]- self.uz_1[1:,i-1]*dlnn_dz_1[1:,i-1] - self.ur_1[1:,i-1]*dlnn_dr_1[1:,i-1] ) "Updating plume variable arrays with Second-Order plasma plume reults" self.uz[2,:,:] = self.uz[1,:,:] + self.uz_2*self.eps**2 self.ur[2,:,:] = self.ur[1,:,:] + self.ur_2*self.eps**2 self.lnn[2,:,:] = self.lnn[1,:,:] + self.lnn_2*self.eps**2 n2[:,:] = np.exp(self.lnn[2,:,:]) self.div[2,:,:] = self.ur[2,:,:]/ self.uz[2,:,:] self.T [2,:,:] = super(AEM,self).temp(n2[:,:],self.n0[0],self.T_0,self.Gamma) #Calling parent class method Hyperplume.temp() to calculate plume second order solution temperature based on density self.phi[2,:,:] = super(AEM,self).phi(n2[:,:],self.n0[0],self.T_0,self.Gamma,self.q_ion) #Calling parent class method Hyperplume.phi() to calculate plume second order solution temperature based on density self.eta_[2,:,:] = self.r_grid-self.div[2,:,:]*self.z_grid #PABLO20170426 This is clearly wrong. But why?? corrections are integrable along zeroth order streamlines as said in article.Matlab code calls function orbit2d.m , which I dont understand. Could you explain? def marching_solver(self,nsects): """Marching schem AEM plume solver.AEM Class method marching_solver solves extends the AEM solution downstream by reinitializing the method at each new calculated plasma plume front, (r0_front,z0_front,uz0_front,n0_front) preventing excessive error growth in the calculations and widening the convergence region of thr AEM model. Marching_solver method reinitializes the plume initial parameter, with the values calculated in the previous integration step, as many times as indicated by the user in nsects. It then solves the plume expansion incrementally by callling the solver method multiple times. Args: nsects (int): number of axial sections or steps (plume fronts), where solver reinitializes the model and integrates the solution agin. Usage: >>> PlumeAEM = AEM(Plasma,z_span,eta_0,n0,uz0,ur0,AEM_Order) #Creation of AEM plume >>> Plume.marching_solver(nsects=100) Same Plasma attributes from standard solver can be accessed in Method marching_solver, but in this case the method stores only the ith higher order correction specified by the user at plume creation with the input argument sol_order: lnn (numpy.ndarray): matrix containing density values (logarithmic) for the selected AEM solution order. uz (numpy.ndarray): matrix containing axial velocity values for the selected AEM solution order. ur (numpy.ndarray): matrix containing radial velocity values for the selected AEM solution order. T (numpy.ndarray): matrix containing plasma Temperature values for the selected AEM solution order. phi (numpy.ndarray): matrix containing plasma ambipolar electric field for the selected AEM solution order. div (numpy.ndarray): matrix containing plume divergence values for the selected AEM solution order. To access these properties, for instance: >>> PlumeAEM.lnn # density values for AEM ith order solution of plume expansion in the grid >>> PlumeAEM.uz # axial velocity for AEM ith order solution >>> PlumeAEM.T # Temperature values for AEM ith order solution """ z_grid_ = np.zeros((self.eta.size,self.z_span.size)) #2D matrix containing the z grid points in marching mode r_grid_ = np.zeros((self.eta.size,self.z_span.size)) #2D matrix containing the r grid points in marching mode lnn_ = np.zeros((self.eta.size,self.z_span.size)) #2D matrix containing the density (natural logarithm) in marching mode uz_ = np.zeros((self.eta.size,self.z_span.size)) #2D matrix containing the plume axial velocity in marching mode ur_ = np.zeros((self.eta.size,self.z_span.size)) #2D matrix containing the plume radial velocity in marching mode div_ = np.zeros((self.eta.size,self.z_span.size)) #2D matrix containing the plume divergence in marching mode #T_ = np.zeros((self.eta.size,self.z_span.size)) #2D matrix containing theplume temperature in marching mode #phi_ = np.zeros((self.eta.size,self.z_span.size)) #2D matrix containing the electric potential in marching mode zsects_val = np.linspace(self.z_span.max()/nsects,self.z_span.max(),nsects) #z_grid points values at the end of each section/front in maching mode """GENERATION OF FIRST COMPUTATIONAL GRID""" dz = self.z_span.max()/(self.z_span.size - 1) #minimum integration step in axial direction zpts = int(round(zsects_val[0]/dz) + 1) #number of steps in axial direction (number od z_points) zed = np.zeros((1,zpts+1)) #array containing integration axial steps zed[0,0:zpts] = np.linspace(0,zsects_val[0],zpts) zed[0,zpts] = zsects_val[0] + dz self.z_grid,self.r_grid = self.grid_setup(zpts+1,self.eta.size) #calculation of z_grid and r_grid based on first front M0_start = self.M0 #Initial Mach Number based on first front """Tracking variables for marching method""" zpts_old = 1 #tracker of previous axial grid points count = 0 #counter of axial sections vel_factor = 1 #factor for front plume velocity correction Te_factor = 1 #factor for front plume temperature corrections for i in range(nsects): """Solving current plasma axial extension""" self.solver() #Calling to method AEM class method to solve the plume in the entire grid if i == 0: """Update contents of marching plume_final result matrixes with results from self.solver method in the grid, for first axial section""" lnn_[:,0:zpts] = self.lnn[self.order,:,0:zpts] uz_[:,0:zpts] = self.uz[self.order,:,0:zpts] ur_[:,0:zpts] = self.ur[self.order,:,0:zpts] div_[:,0:zpts] = self.div[self.order,:,0:zpts] #T_[:,0:zpts] = self.T[self.order,:,0:zpts] #phi_[:,0:zpts] = self.phi[self.order,:,0:zpts] z_grid_[:,0:zpts] = self.z_grid[:,0:zpts] r_grid_[:,0:zpts] = self.r_grid[:,0:zpts] else: """Update contents of marching plume_final result matrixes with results from self.solver method in the grid, for remaining axial section""" lnn_[:,zpts_old-1:zpts_old+zpts-1] = self.lnn[self.order,:,0:zpts] uz_[:,zpts_old-1:zpts_old+zpts-1] = self.uz[self.order,:,0:zpts] * vel_factor ur_[:,zpts_old-1:zpts_old+zpts-1] = self.ur[self.order,:,0:zpts] * vel_factor div_[:,zpts_old-1:zpts_old+zpts-1] = self.div[self.order,:,0:zpts] #T_[:,zpts_old-1:zpts_old+zpts-1] = self.T[self.order,:,0:zpts] * Te_factor #phi_[:,zpts_old-1:zpts_old+zpts-1] = self.phi[self.order,:,0:zpts] z_grid_[:,zpts_old-1:zpts_old+zpts-1] = self.z_grid[:,0:zpts] + zsects_val[i-1] r_grid_[:,zpts_old-1:zpts_old+zpts-1] = self.r_grid[:,0:zpts] zpts_old = zpts_old + zpts -1 #Updating value of axial points, to move forward along the sections """PREPARING NEXT INTEGATION AXIAL STEP""" if i < nsects-1: """Updating new integration interval parameters""" zpts = int(round((zsects_val[i+1]-zsects_val[i])/dz) + 1) #Updating next number of axial points zed = np.zeros((1,zpts+1)) #Updating next array of axial integration steps zed[0,0:zpts] = np.linspace(zsects_val[i],zsects_val[i+1],zpts) - zsects_val[i] zed[0,zpts] = zed[0,zpts-1] + dz """New initial profiles for the next axial integration interval""" r0_front = self.r_grid[:,-2] #New initial r_span obtained from before-last previous section r_grid z0_front = zed #New z0_front based on zed array n0_front = np.exp(self.lnn[self.order,:,-2]) #New initial density profile obatained from before-last previous section density uz0_front = self.uz[self.order,:,-2] #New initial axial velocity profile obatained from before-last previous section axial velocity ur0_front = self.ur[self.order,:,-2] #New radial velocity profile obatained from before-last previous section radial velocity super(AEM,self) .__init__(self.plasma,z0_front.reshape(zed.shape[1],),r0_front,n0_front) #calling Hyperplume constructor to reload the new initial profiles self.uz0,self.ur0,self.d0 = uz0_front,ur0_front,ur0_front/uz0_front #reloading remaining new plume initial profiles """Compute derivatives of new initial plume profiles""" self.d0p = self.eta_deriver(self.eta,self.d0) #derivative of plume divergence self.d0p[0],self.d0p[-1] = self.d0[1]/self.eta[1],self.d0p[-2] + (self.d0p[-2] - self.d0p[-3]) self.uz0p = self.eta_deriver(self.eta,self.uz0) #derivative of initial axial velocity self.uz0p[0],self.uz0p[-1] = 0,self.uz0p[-2] + (self.uz0p[-2] - self.uz0p[-3]) self.duz0p = self.eta_deriver(self.eta,self.d0*self.uz0) #derivatie of initial radial velocity self.duz0p[0],self.duz0p[-1] = self.duz0p[1]/self.eta[1],self.duz0p[-2] + (self.duz0p[-2] - self.duz0p[-3]) """Updating correction factors""" vel_factor = vel_factor * self.uz[self.order,0,-2]/self.uz[self.order,0,0] #velocity factor for next integration interval Te_factor = Te_factor * self.T[self.order,0,-2]/self.T[self.order,0,0] #Temperature factor for next integration interval self.M0 = M0_start*np.sqrt(vel_factor**2/Te_factor) #Update new Mach number based on previos Mach and correction factors self.eps = 1/self.M0**2 #new AEM epsilon expansion parameter self.z_grid,self.r_grid = self.grid_setup(zpts+1,self.eta.size) #new interval solution grids """line1 = plt.plot(self.eta,self.n0,'b'); line2 = plt.plot(self.eta,self.uz0/self.uz0[0],'k') line3 = plt.plot(self.eta,self.d0,'r',label=r'$Plume divergence \delta = u_{r0}/u_{z0}$') count = count + 1 if count > 100: plt.close(fig) count = 0 red_line = mlines.Line2D([], [], color='red', label=r'$\delta_{0}$') black_line = mlines.Line2D([], [], color='black', label=r'$\tilde{u}_{z0}$') blue_line = mlines.Line2D([], [], color='blue', label=r'$\tilde{n}_{0}$') plt.legend(handles=[red_line,black_line,blue_line],loc='best') plt.title('AEM Marching Solver plume front evolution') plt.xlabel(r'$\eta$') plt.savefig('Marching_solver_init_fronts.png')""" """ Updating final plume attibutes structure with marching_plume results""" self.z_grid = z_grid_ self.r_grid = r_grid_ self.lnn = lnn_ self.uz = uz_ self.ur = ur_ self.div = div_ self.T = super(AEM,self).temp(np.exp(self.lnn),np.exp(self.lnn)[0,0],self.T_0,self.Gamma)#T_ self.phi = super(AEM,self).phi(np.exp(self.lnn),np.exp(self.lnn)[0,0],self.T_0,self.Gamma,self.q_ion)#phi_ def query(self,z,r): """ Method query returns the density, velocity profile, temperature, the electric potential at particular (z,r) points in the Plume. These plasma properties are interpolated along the previously calculated 2D grids z_grid and r_grid at targeted (z,r) points specified by the user. User must always check if np.max(r) > np.max(self.r_grid), np.max(z) > np.max(self.z_grid) in their query point set,to avoid extrapolation results. Args: z (float,numpy.ndarray): new interpolation z points. r (float,numpy.ndarray): new interpolation r points. Outputs: lnn (int,numpy.ndarray): logarithmic plasma density at specified (z,r) points in plume grid u_z (int,numpy.ndarray): plasma axial velocity at specified (z,r) points in plume grid u_r (int,numpy.ndarray): plasma radial velocity at specified (z,r) points in plume grid T (int,numpy.ndarray): plasma temperature at specified (z,r) points in plume grid phi (int,numpy.ndarray): plasma ambipolar electric potential at specified (z,r) points in plume grid eta (int,numpy.ndarray): ion current stream lines at specified (z,r) points in plume grid Usage: >>> z,r = np.linspace(0,100,50),np.linspace(0,50,40) #target (z,r) for plume query >>> lnn,u_z,u_r,T,phi,eta=PlumeAEM.query(z,r) Method query returns only the self.order solution indicated by the user. #PABLO20170506: After reading extensively on how to perform interpolation over 2D rectagunlar grids, I decided to leave method griddata for such task. The problem with interp2D is that given the great size of self.z_grid,and r_grid (mxn), the number of points exceeds memory of method and return error. Even if the size of the grids is made smaller (losing accuracy and information in the AEM) the method interp2D takes a lot of time (sometimes I had to reset the console). If you want to try to fix the bug or otherwise tell what I am doing incorrectly I leave the line of code with interp2D that I was using to solve the interpolation (The syntax is exactly the same as the one we saw the ither day in your office, but for some reason it is not returning the results i expect. lnn = interp2d(self.z_grid,self.r_grid,self.lnn[self.order,:,:])(z.flatten(),r.flatten()) On the other hand, griddadta in python does not behave like the Matlab function(In Matlab this function does indeed extrapolate the results).Griddata is the recommended function to use over large arrays of data over 2D structured or unstructured data, and I have check the return of the interpolation using griddata and it is correct """ grid_points = np.array((self.z_grid.flatten(),self.r_grid.flatten())).T #pairing each z_grid point to its matching r_grid point lnn = griddata(grid_points,self.lnn[self.order,:,:].flatten(),(z,r),method='linear') #Logarithm of plasma plume density interpolation matrix u_z = griddata(grid_points,self.uz[self.order,:,:].flatten(),(z,r),method='linear') #Plasma plume axial velocity interpolation matrix u_r = griddata(grid_points,self.ur[self.order,:,:].flatten(),(z,r),method='linear') #Plasma plume radial velocity interpolation matrix T = griddata(grid_points,self.T[self.order,:,:].flatten(),(z,r),method='linear') #Plasma plume temperature interpolation matrix phi = griddata(grid_points,self.phi[self.order,:,:].flatten(),(z,r),method='linear') #Plasma plume electric potential interpolation matrix eta = griddata(grid_points,self.eta_[self.order,:,:].flatten(),(z,r),method='linear') #Eta-line interpolated values at specied (z,r) points return lnn,u_z,u_r,T,phi,eta def grid_setup(self,zpts,epts): """ grid_setup creates an strctured grid of z,r points where the AEM problem will be integrated Args: zpts (int): number of axial points in the structure. Indicates legnth oof axial plume span epts (int): number of radial points in the structure. Indicates legnth of radial plume span Returns: z_grid (numpy.ndarray): 2D matrix containing axial grid points for model integration r_grid (numpy.ndarray): 2D matrix containing radial grid points for model integration Usage: >>> z_grid,r_grid = PlumeAEM.grid_setup(100,50) """ z_grid = np.zeros((epts,zpts)) #2D Matrix of Plume z points r_grid = np.zeros((epts,zpts)) #2D Matrix of Plume r points """Compute the radial and axial coordinates of each grid points along the streamlines""" for j in range(epts): #advance radially for k in range(zpts): #advance axially "Compute the axial coordinate along the jth streamline" z_grid[j,k] = self.z_span[k] #update z_grid point from initial z_front for j in range(epts): #advance radially r_grid[j,0] = self.eta[j] #updating initial r_grid fron points for k in range(1,zpts): #advance axially r_grid[j,k] = r_grid[j,0]+self.d0[j]*self.z_span[k] #update r_grid points from initial front and divergence return z_grid,r_grid def val_domain(self): """ val_domain class method evaluates the validity of the AEM series expansion solution at z_grid and r_grid points in the plume. Validity results for each AEM order are stored in the 3D matrix Plume.val. These matrix is filled with values indicating a specific validity condition in the results. VALIDITY VALUES 0 - Not valid for both velocity and density 1 - Valid only for velocity -1 - Valid only for density 2 - Valid for both velocity and density Usage: >>> PlumeAEM.val_domain() #Intialize validity condition study >>> print(Plume.val) #See results of validation """ rel_size = 0.1 #Maximum relative size of the ith order perturbation wrt(i-1)th order to ensure validity of the solution self.val = np.zeros((3,self.__epts,self.__zpts)) #3D matrix with validity values for each grid point and each solution order self.val[0,:,:]=2 #Setting valitidity od Zeroth Order solution as reference for i in range(self.order): "Creation of plume variable contribution matrixes" uz_contribution= np.zeros((self.__epts,self.__zpts)) ur_contribution= np.zeros((self.__epts,self.__zpts)) lnn_contribution= np.zeros((self.__epts,self.__zpts)) uz_contribution[:,1:] = abs((self.uz[i+1,:,1:]-self.uz[i,:,1:])/self.uz[i,:,1:]) ur_contribution[1:,1:] = abs((self.ur[i+1,1:,1:]-self.ur[i,1:,1:])/self.ur[i,1:,1:]) lnn_contribution[:,1:] = abs((self.lnn[i+1,:,1:]-self.lnn[i,:,1:])/self.lnn[i,:,1:]) for j in range(self.__epts): #advance in radial direction for k in range(self.__zpts): #advance axially if (uz_contribution[j,k]<rel_size and ur_contribution[j,k] < rel_size): #applying validity criterion stated in dissertation self.val[i+1,j,k] = 1 if lnn_contribution[j,k] < rel_size: #applying validity criterion stated in dissertation self.val[i+1,j,k] = 2 elif lnn_contribution[j,k] < rel_size: #applying validity criterion stated in dissertation self.val[i+1,j,k] = -1 def partial_derivs(self,var,type2): """Class method partial_derivs computes the partial derivatives of plasma variables with respect to the physical z,r at the plume grid points. Args: var (numpy.ndarray): Variable values to derive at z,r grid points type2 (int): Integer defining the behaviour of the derivative at the borders and therefore the Type of varible to be differentiated: 0: Symmetric function. Border derivative value is set to 0 -1; Anti-symmetric function. Forward finite difference is used for border derivative calculation. Returns: dvar_dz : z-partial derivative values of input argument var at the grid points dvar_dr : r-partial derivative values of input argument var at the grid points Usage: >>> dlnn0_dz,dlnn0dr = PlumeAEM.partial_derivs(Plume.lnn_0) #derivative of Zeroth order density correction """ dvar_dz = np.zeros((self.__epts,self.__zpts)) #2D matrix storing z-derivative values of var at grid points dvar_dr = np.zeros((self.__epts,self.__zpts)) #2D matrix storing z-derivative values of var at grid points zfactor = np.zeros((self.__epts,self.__zpts)) #2D Jacobian z tranformation matrix to pass from zita-eta derivatives to z,r derivatives at grid points(see dissertation appendix) rfactor = np.zeros((self.__epts,self.__zpts)) #2D Jacobian r tranformation matrix to pass from zita-eta derivatives to z,r derivatives at grid points(see dissertation appendix) eta_grid = np.dstack((self.r_grid[:,0],)*self.__zpts)[0] #2D matrix containing stacked values of the eta coordinates at grid points "CALCULATION OF DERIVATIVES IN ZITA-ETA COORDINATES AT GRID POINTS" "This function computes the partial derivatives with respect to the stream coordinates eta-Zita at the grid points" dvar_dzita = np.zeros((self.__epts,self.__zpts)) #2D matrix storing zita-derivative values of var at grid points dvar_deta = np.zeros((self.__epts,self.__zpts)) #2D matrix storing eta-derivative values of var at grid points "Compute the zita partial derivatives of the grid points inside the domain (excluding the boundaries) with a centred difference" dvar_dzita[0:,1:-1] = (var[0:,2:] - var[0:,0:-2]) / (self.z_grid[0:,2:] - self.z_grid[0:,0:-2]) "Compute the zita partial derivatives at z = 0 and zmax, using respectively a forwards and backwards Euler derivative" dvar_dzita[0:,0] = ( var[0:,1] - var[0:,0] ) / (self.z_grid[0,1] - self.z_grid[0,0]) dvar_dzita[0:,-1] = ( var[0:, -1] - var[0:, -2] ) / (self.z_grid[0,-1] - self.z_grid[0,-2]) """Compute the eta partial derivatives of the grid points inside the domain (excluding the boundaries) with a centred difference even when points are not uniform along eta""" h1 = eta_grid[1:-1,0:] - eta_grid[0:-2,0:] #steps in eta-grid used for derivation of variable h2 = eta_grid[2:,0:] - eta_grid[1:-1,0:] dvar_deta[1:-1,0:] = ((h1**2) * var[2:,0:] - ((h1**2) - (h2**2)) * var[1:-1,0:] - (h2**2) * var[0:-2,0:] ) / ((h1**2)*h2 + h1*(h2**2)) """ Compute the eta partial derivatives at z = 0 and zmax, using respectively a forwards and backwards Euler derivative For eta = 0, consider the type of input function""" if type2 == 0: dvar_deta[0,0:] = 0 else: dvar_deta[0,0:] = ( var[1, 0:] - var[0, 0:] ) / (eta_grid[1, 0:] - eta_grid[0,0:]) "Take the final eta line derivative equal to that of the previous point" dvar_deta[-1,0:] = dvar_deta[-2,0:] + (dvar_deta[-2,0:] - dvar_deta[-3,0:]) for i in range(0,self.__zpts): "Compute transformation factors in matrix form for z and r derivative using the Jacobian matrix" zfactor[:,i] = -self.d0[:] / (1 + self.z_grid[:,i] * self.d0p[:]) #Updating Jacobian matrixes rfactor[:,i] = 1 / (1 + self.z_grid[:,i] * self.d0p[:]) dvar_dz[:,:] = dvar_dzita + zfactor * dvar_deta #updatinf final derivatives in z,r coordinates dvar_dr[:,:] = rfactor * dvar_deta return dvar_dz, dvar_dr
import datetime import requests import json from bs4 import BeautifulSoup import dateutil.parser as dup import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) def _get_player_popup(fantasy_id): """Gets ESPN fantasy player overview popup using fantasyId returns BS4 Soup object""" base = 'http://games.espn.go.com/flb/format/playerpop/overview?' params = { "playerId": fantasy_id } resp = requests.get(base, params=params) soup = BeautifulSoup(resp.text) return soup def converter(opts): """Converts ESPN playerId (from Fantasy tool) to statsId ()""" fantasy_id = opts.get('playerId') soup = _get_player_popup(fantasy_id) stats_id = soup.find(class_='pc').findAll('a')[1]['href'].split('=')[1] return int(stats_id) class League(): def __init__(self, league_id): self.league_id = league_id self.get_team_rosters() def get_rostered_players(self): base_url = 'http://games.espn.com/flb/leaguerosters' data = {'leagueId': self.league_id} r = requests.get(base_url, params=data) self.roster_url = r.url s = BeautifulSoup(r.content, 'html.parser') self.rostered_player_ids = {} self.team_ids = {} for table in s.find_all('table'): team = table.find('th').find('a') team_id = team['href'].split('=')[-1] team_name = team.get_text() for a in table.find_all('a', {'class': 'flexpop', 'leagueid': str(self.league_id)}): self.rostered_player_ids[a['playerid']] = {'team_id': team_id, 'team_name': team_name} def get_team_rosters(self): self.get_rostered_players() self.team_rosters = {} for player_id, data in self.rostered_player_ids.iteritems(): team_id = data['team_id'] team_roster = self.team_rosters.get('team_id', []) team_roster.append(player_id) class Team(): def __init__(self, league_id, team_id, year=2017): self.league_id = league_id self.team_id = team_id params = 'leagueId={0}&teamId={1}&seasonId={2}'.format(self.league_id, self.team_id, year) self.url = 'http://games.espn.com/flb/clubhouse?{}'.format(params) self.get_roster() def get_roster(self): league = League(self.league_id) self.roster = league.team_rosters[str(self.team_id)] class FangraphsClosers(): def __init__(self): self.get_fg_closers() def get_fg_closers(self): base_url = 'http://www.fangraphs.com/fantasy/category/bullpen-report/' r = requests.get(base_url) s = BeautifulSoup(r.content, 'html.parser') dates = [] bullpen_reports = {} for h2 in s.find_all('h2', {'class': 'posttitle'}): try: br_date = dup.parse(h2.text, fuzzy=True) br_date_readable = br_date.strftime('%B %d, %Y') dates.append(br_date) bullpen_reports[br_date_readable] = h2.find('a')['href'] except Exception: pass most_recent_br = max(dates) most_recent_br_readable = most_recent_br.strftime('%B %d, %Y') href = bullpen_reports[most_recent_br_readable] self.parse_closer_table(href) def parse_closer_table(self, url): r = requests.get(url) s = BeautifulSoup(r.content, 'html.parser') self.closer_table = [] for td in s.find_all('td'): if td.get('class'): if ('closer' in td['class'][0].lower()) and (td.find('a')): name = td.find('a').get_text() player_url = td.find('a')['href'] player_id = player_url.split('?')[1].split('&')[0].split('=')[1] role = td['class'][0].split('_')[0] color = td['class'][0].split('_')[1] player_dict = {'player_name': name, 'player_id': player_id, 'role': role, 'color': color} self.closer_table.append(player_dict) class GameScores(): def __init__(self): self.get_game_scores() self.get_opp_team_stats() def get_latest_post(self): r = requests.get('http://www.espn.com/fantasy/baseball/') soup = BeautifulSoup(r.content, 'html.parser') daily_notes_dates = {} for a in soup.find_all('a'): if 'daily-notes' in a['href'].lower(): date_string = a['href'].split('daily-notes-')[-1] date = dup.parse(date_string, fuzzy=True) daily_notes_dates[date] = a['href'] self.latest_post = daily_notes_dates[max(daily_notes_dates.keys())] def get_game_scores(self): self.get_latest_post() url = 'http://www.espn.com{}'.format(self.latest_post) r = requests.get(url) soup = BeautifulSoup(r.content, 'html.parser') self.game_scores = {} self.pitchers = {} self.venues = {} self.opponents = {} table = soup.find('table', {'class', 'inline-table'}) self.date = dup.parse(table.find('caption').text, fuzzy=True) for tr in table.find_all('tr', {'class': 'last'}): try: player_id = tr.find('a')['href'].split('/')[-2:-1][0] game_score = tr.find('b').text name = tr.find('a').text team = tr.find('img')['src'].split('/')[-1].split('.')[0] opp = tr.find_all('b')[1].text if '@' in opp: venue = opp.split('@')[1] self.opponents[player_id] = opp.split('@')[1] else: venue = team self.opponents[player_id] = opp self.game_scores[player_id] = game_score self.pitchers[player_id] = name self.venues[player_id] = venue.lower() except TypeError: print('One of the table rows is missing a player href. Passing.') pass self.sorted_by_game_score = sorted(self.game_scores, key=self.game_scores.get, reverse=True) def get_park_factors(self): with open('./park_codes.json', 'r') as j: park_codes = json.load(j) park_factors_url = 'http://www.espn.com/mlb/stats/parkfactor/_/sort/HRFactor' r = requests.get(park_factors_url) s = BeautifulSoup(r.content, 'html.parser') park_factors = {} for a in s.find_all('a'): if 'http://espn.go.com/travel/stadium/index?eVenue=' in a.get('href'): hr_score = a.parent.parent.find('td', class_='sortcell').text park_factors[a.get('href').split('=')[1]] = hr_score self.park_factors = {} for i in self.pitchers.keys(): self.park_factors[i] = park_factors.get(park_codes.get(self.venues.get(i))) def get_opp_team_stats(self): self.get_park_factors() with open('./team_names.json', 'r') as j: team_names = json.load(j) tr_url = 'https://www.teamrankings.com/mlb/stat/on-base-plus-slugging-pct' #fg_url = 'http://www.fangraphs.com/leaders.aspx?pos=all&stats=bat&lg=all&qual=0&type=8&season=2017&month=0&season1=2017&ind=0&team=0,ts&rost=0&age=0&filter=&players=0&sort=16,d' headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'} r = requests.get(tr_url, headers=headers) s = BeautifulSoup(r.content, 'html.parser') #wrc_plus = {} #for td in s.find_all('td', class_='rgSorted'): # wrc_plus[td.parent.find('a').text.lower()] = td.text ops = {} for tr in s.find_all('tr'): if tr.find('td'): for td in tr.find_all('td', {'class': 'nowrap'}): href = td.find('a')['href'] if 'sox' in href or 'jays' in href: ix = -2 else: ix = -1 ops[' '.join(href.split('-')[ix:]).strip()] = td.findNextSibling().get_text() #self.wrc_plus = {} self.ops = {} for i in self.pitchers.keys(): logging.info('getting team abbr') opp = self.opponents[i].lower() logging.info("getting team name") team = team_names[opp] logging.info('getting ops for team') #self.wrc_plus[i] = wrc_plus.get(team, "n/a") self.ops[i] = ops.get(team, 'n/a') def set_fantasy_team(self, ts_teams): self.ts_teams = ts_teams
# -*- coding: utf-8 -*- """ Created on Sat Jun 6 23:58:51 2015 @author: jharrison902 """ import gdal import os import os.path import argparse import xml.etree.ElementTree as ET import psycopg2 """ Tile and import into database our raster files. Usage: importer.py --satellite SATELLITE --dir DIRECTORY """ class Importer: def __init__(self): #initialize variables self._directory = "" self._satellite = None self._table = "GISBox" self._projection_target_short = "EPSG:32618" #projection handy for the test region self._projection_target = 'PROJCS["WGS 84 / UTM zone 18N",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-75],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32618"]]' self._tmp_dir = "/Users/jharrison902/Desktop/giswork/tmp" self._bands={} self._masks={} try: self._conn = psycopg2.connect(dbname="GISBox",user="postgres",password="postgres",host="localhost") except: print "Could not connect to the database!" def get_satellite_dictionary(self): satellites = {} satellites['7']=self.set_satellite_landsat_7 satellites['8']=self.set_satellite_landsat_8 return satellites def parse_metadata(self): """ Parse the product metadata and generate bounds, etc. """ print "Parsing metadata" metadata_tree = ET.parse(os.path.join(self._directory,self._product_metadata)) root = metadata_tree.getroot() assert root.tag == '{http://espa.cr.usgs.gov/v1.2}espa_metadata' """ get overall metadata """ global_metadata = root.find('{http://espa.cr.usgs.gov/v1.2}global_metadata') """ get band information """ band_metadata = root.find('{http://espa.cr.usgs.gov/v1.2}bands') """ obtain data from global metadata """ self._acquisition_date = global_metadata.find('{http://espa.cr.usgs.gov/v1.2}acquisition_date').text+'T'+global_metadata.find('{http://espa.cr.usgs.gov/v1.2}scene_center_time').text self._bounds={} """ Get lat/lon bounds for records """ ll_bounds = global_metadata.find('{http://espa.cr.usgs.gov/v1.2}bounding_coordinates') for direction in ll_bounds: cardinal = direction.tag.replace('{http://espa.cr.usgs.gov/v1.2}','') self._bounds[cardinal]=float(direction.text) """ Get satellite """ satellite = global_metadata.find('{http://espa.cr.usgs.gov/v1.2}satellite').text """ TODO: make this dynamically draw from available satellites """ satellite_list = {'LANDSAT_7':self.set_satellite_landsat_7,'LANDSAT_8':self.set_satellite_landsat_8} satellite_list[satellite]() """ Parse band metadata """ self._bands={} for band in band_metadata: print band.tag assert band.tag == '{http://espa.cr.usgs.gov/v1.2}band' attributes = band.attrib if attributes['category'] == "image": #This is an sr_band self._bands[attributes['name']]={} print "Found band "+attributes['name'] self._bands[attributes['name']]['fill']=attributes['fill_value'] self._bands[attributes['name']]['file']=band.find('{http://espa.cr.usgs.gov/v1.2}file_name').text elif attributes['category'] =='pq': self._masks[attributes['name']]={} self._masks[attributes['name']]['bits']=[] for bit in band.find('{http://espa.cr.usgs.gov/v1.2}bitmap_description'): self._masks[attributes['name']]['bits']=bit.attrib['num'] else: print "Unidentified record in metadata: "+attributes['category']+"!" def set_satellite_landsat_7(self): """ Set our importer to use Landsat 7 settings """ self._satellite = 'LANDSAT_7' """ TODO: should this do more? """ def set_satellite_landsat_8(self): """ Set our importer to use Landsat 8 settings """ self._satellite = 'LANDSAT_8' """ TODO: should this do more? """ def generate_cmd_string(self, input_file, tile_path, tile_x, tile_y, size): """ Generate the string to store a tile in the database. """ cmd = 'gdalwarp' cmd+=' -q' cmd+=' -of GTiff' #geotiff output cmd+=' -tr 30 30' #30m resolution cmd+=' -te '+str(tile_x)+' '+str(tile_y)+' '+str(tile_x+size)+' '+str(tile_y+size) cmd+=' -tap -tap' cmd+=' -r cubic' #cubic resampling if we absolutely have to resample cmd+=' '+os.path.join(self._directory,input_file) cmd+=' '+os.path.join(self._tmp_dir,tile_path) return cmd def tile_raster(self): """ Convert raster into tiles using gdalwarp. Coordinates will be stored in self._projection_target projection. """ print "Preparing to create tiles" gdal.AllRegister() for band in self._bands: print band file_path = os.path.join(self._directory,self._bands[band]['file']) band_file = gdal.Open(file_path) """ TODO: implement a database lock on inserts at this point """ """ Reproject our data """ print "Reprojecting product..." band_file.SetProjection(self._projection_target) band_file.FlushCache() """ Slice data into tiles based on size in coordinate system """ x_size = band_file.RasterXSize y_size = band_file.RasterYSize geotrans = band_file.GetGeoTransform() x_arr = [0,x_size] y_arr = [0,y_size] extent = [] #determine extents for xpixel in x_arr: for ypixel in y_arr: x = geotrans[0]+(xpixel*geotrans[1])+(ypixel*geotrans[2]) y = geotrans[3]+(xpixel*geotrans[4])+(ypixel*geotrans[5]) extent.append([x,y]) y_arr.reverse() """ slice file based on 30000m squares """ tile_size = 30000.0 #get lower x, lower y low_x=10000000000.0 low_y=10000000000.0 high_x=-10000000000.0 high_y=-10000000000.0 for pair in extent: if pair[0]<low_x: low_x=pair[0] if pair[0]>high_x: high_x=pair[0] if pair[1]<low_y: low_y=pair[1] if pair[1]>high_y: high_y=pair[1] x_step = low_x y_step = low_y while x_step <= high_x: while y_step <= high_y: print "Generating tile: "+str(x_step)+" "+str(y_step) cmd = self.generate_cmd_string(self._bands[band]['file'],self._satellite+'_'+band+'_'+self._acquisition_date+'_'+str(x_step)+'_'+str(y_step)+'.tif',x_step,y_step,tile_size) os.system(cmd) """ Store raster in database """ cmd = self.generate_tif_insertion_cmd_string(self._satellite+'_'+band+'_'+self._acquisition_date+'_'+str(x_step)+'_'+str(y_step)+'.tif') os.system(cmd) #execute the import cmd = "psql -h localhost -p 5432 -U postgres GISBox < "+os.path.join(self._tmp_dir,self._satellite+'_'+band+'_'+self._acquisition_date+'_'+str(x_step)+'_'+str(y_step)+'.tif'+'.sql') #TODO: externalize database settings os.system(cmd) """ TODO: Implement psql insertion! """ y_step+=tile_size y_step = low_y x_step+=tile_size def generate_tif_insertion_cmd_string(self,input_file): cmd = "raster2pgsql" cmd+=' -a -F -e '+os.path.join(self._tmp_dir,input_file)+' tiles > '+os.path.join(self._tmp_dir,input_file+'.sql') return cmd def determine_raster_files(self,input_directory): """ Parse the product metadata and determine the bands and masks """ print "Locating raster files in: "+input_directory if not input_directory[0] is '/': path = os.getcwd() path = os.path.join(path,input_directory) else: print "This is an absolute path!" path = input_directory files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path,f))] #find xml file for file_name in files: if file_name.endswith('.xml'): print "Product metadata found! "+file_name self._product_metadata = file_name break files.remove(self._product_metadata) self._raster_files = files self._directory=path if __name__=="__main__": parser = argparse.ArgumentParser(description="Import Landsat surface reflectance products.") #parser.add_argument('--satellite', type=str, metavar='SATELLITE',required=True,choices=['7','8'],help="The product's satellite",dest="target_satellite") parser.add_argument('--directory','-d',type=str,metavar='DIRECTORY',required=True,action='store',help="The path of the directory of SR products.",dest="directory") args = parser.parse_args() importer = Importer() importer.determine_raster_files(args.directory) importer.parse_metadata() importer.tile_raster()
import os import flask import glanceclient from keystoneclient.v2_0 import client as keystoneclient import signals from . import Storage from .local import LocalStorage from .s3 import S3Storage from .swift import SwiftStorage class GlanceStorage(object): """This class is a dispatcher, it forwards methods accessing repositories to the alternate storage defined in the config and it forwards methods accessing images to the GlanceStorageLayers class below. """ def __init__(self, config): self._config = config self._storage_layers = GlanceStorageLayers(config) kind = config.get('storage_alternate', 'local') self._storage_base = Storage() if kind == 's3': self._storage_tags = S3Storage(config) elif kind == 'local': self._storage_tags = LocalStorage(config) elif kind == 'swift': self._storage_tags = SwiftStorage(config) else: raise ValueError('Not supported storage \'{0}\''.format(kind)) def _resolve_class_path(self, method_name, *args, **kwargs): path = '' if 'path' in kwargs: path = kwargs['path'] elif len(args) > 0 and isinstance(args[0], basestring): path = args[0] if path.startswith(Storage.images): obj = self._storage_layers elif path.startswith(Storage.repositories): obj = self._storage_tags else: obj = self._storage_layers if not hasattr(obj, method_name): return return getattr(obj, method_name) def __getattr__(self, name): def dispatcher(*args, **kwargs): attr = self._resolve_class_path(name, *args, **kwargs) if not attr: raise ValueError('Cannot dispath method ' '"{0}" args: {1}, {2}'.format(name, args, kwargs)) if callable(attr): return attr(*args, **kwargs) return attr return dispatcher class GlanceStorageLayers(Storage): """This class stores the image layers into OpenStack Glance. However tags are still stored on other filesystem-like stores. """ disk_format = 'raw' container_format = 'docker' def __init__(self, config): self._config = config # Hooks the tag changes signals.tag_created.connect(self._handler_tag_created) signals.tag_deleted.connect(self._handler_tag_deleted) def _get_auth_token(self): args = {} for arg in ['username', 'password', 'tenant_name', 'auth_url']: env_name = 'OS_{0}'.format(arg.upper()) if env_name not in os.environ: raise ValueError('Cannot find env var "{0}"'.format(env_name)) args[arg] = os.environ[env_name] keystone = keystoneclient.Client(**args) return keystone.auth_token def _get_endpoint(self): if 'OS_GLANCE_URL' not in os.environ: raise ValueError('Cannot find env var "OS_GLANCE_URL"') return os.environ['OS_GLANCE_URL'] def _create_glance_client(self): token = flask.request.headers.get('X-Meta-Auth-Token') endpoint = flask.request.headers.get('X-Meta-Glance-Endpoint') if not token: token = self._get_auth_token() if not endpoint: endpoint = self._get_endpoint() return glanceclient.Client('1', endpoint=endpoint, token=token) def _init_path(self, path, create=True): """This resolve a standard Docker Registry path and returns: glance_image obj, property_name If property name is None, we want to reach the image_data """ parts = path.split('/') if len(parts) != 3 or parts[0] != self.images: raise ValueError('Invalid path: {0}'.format(path)) image_id = parts[1] filename = parts[2] glance = self._create_glance_client() image = self._find_image_by_id(glance, image_id) if not image and create is True: if 'X-Meta-Glance-Image-Id' in flask.request.headers: try: i = glance.images.get( flask.request.headers['X-Meta-Glance-Image-Id']) if i.status == 'queued': # We allow taking existing images only when queued image = i image.update(properties={'id': image_id}, purge_props=False) except Exception: pass if not image: image = glance.images.create( disk_format=self.disk_format, container_format=self.container_format, properties={'id': image_id}) try: image.update(is_public=True, purge_props=False) except Exception: pass propname = 'meta_{0}'.format(filename) if filename == 'layer': propname = None return image, propname def _find_image_by_id(self, glance, image_id): filters = { 'disk_format': self.disk_format, 'container_format': self.container_format, 'properties': {'id': image_id} } images = [i for i in glance.images.list(filters=filters)] if images: return images[0] def _clear_images_name(self, glance, image_name): images = glance.images.list(filters={'name': image_name}) for image in images: image.update(name=None, purge_props=False) def _handler_tag_created(self, sender, namespace, repository, tag, value): glance = self._create_glance_client() image = self._find_image_by_id(glance, value) if not image: # No corresponding image, ignoring return image_name = '{0}:{1}'.format(repository, tag) if namespace != 'library': image_name = '{0}/{1}'.format(namespace, image_name) # Clear any previous image tagged with this name self._clear_images_name(glance, image_name) image.update(name=image_name, purge_props=False) def _handler_tag_deleted(self, sender, namespace, repository, tag): image_name = '{0}:{1}'.format(repository, tag) if namespace != 'library': image_name = '{0}/{1}'.format(namespace, image_name) glance = self._create_glance_client() self._clear_images_name(glance, image_name) def get_content(self, path): (image, propname) = self._init_path(path, False) if not propname: raise ValueError('Wrong call (should be stream_read)') if not image or propname not in image.properties: raise IOError('No such image {0}'.format(path)) return image.properties[propname] def put_content(self, path, content): (image, propname) = self._init_path(path) if not propname: raise ValueError('Wrong call (should be stream_write)') props = {propname: content} image.update(properties=props, purge_props=False) def stream_read(self, path, bytes_range=None): (image, propname) = self._init_path(path, False) if propname: raise ValueError('Wrong call (should be get_content)') if not image: raise IOError('No such image {0}'.format(path)) return image.data(do_checksum=False) def stream_write(self, path, fp): (image, propname) = self._init_path(path) if propname: raise ValueError('Wrong call (should be put_content)') image.update(data=fp, purge_props=False) def exists(self, path): (image, propname) = self._init_path(path, False) if not image: return False if not propname: return True return (propname in image.properties) def is_private(self, namespace, repository): return False def remove(self, path): (image, propname) = self._init_path(path, False) if not image: return if propname: # Delete only the image property props = image.properties if propname in props: del props[propname] image.update(properties=props) return image.delete() def get_size(self, path): (image, propname) = self._init_path(path, False) if not image: raise OSError('No such image: \'{0}\''.format(path)) return image.size
#!/usr/bin/env python3 # # Copyright (c) 2017 Intel Corporation # # SPDX-License-Identifier: Apache-2.0 import argparse import sys import struct import os import elftools from distutils.version import LooseVersion from elftools.elf.elffile import ELFFile from elftools.elf.sections import SymbolTableSection if LooseVersion(elftools.__version__) < LooseVersion('0.24'): sys.stderr.write("pyelftools is out of date, need version 0.24 or later\n") sys.exit(1) # This will never change, first selector in the GDT after the null selector KERNEL_CODE_SEG = 0x08 # These exception vectors push an error code onto the stack. ERR_CODE_VECTORS = [8, 10, 11, 12, 13, 14, 17] def debug(text): if not args.verbose: return sys.stdout.write(os.path.basename(sys.argv[0]) + ": " + text + "\n") def error(text): sys.stderr.write(os.path.basename(sys.argv[0]) + ": " + text + "\n") sys.exit(1) # See Section 6.11 of the Intel Architecture Software Developer's Manual gate_desc_format = "<HHBBH" def create_irq_gate(handler, dpl): present = 1 gate_type = 0xE # 32-bit interrupt gate type_attr = gate_type | (dpl << 5) | (present << 7) offset_hi = handler >> 16 offset_lo = handler & 0xFFFF data = struct.pack(gate_desc_format, offset_lo, KERNEL_CODE_SEG, 0, type_attr, offset_hi) return data def create_task_gate(tss, dpl): present = 1 gate_type = 0x5 # 32-bit task gate type_attr = gate_type | (dpl << 5) | (present << 7) data = struct.pack(gate_desc_format, 0, tss, 0, type_attr, 0) return data def create_idt_binary(idt_config, filename): with open(filename, "wb") as fp: for handler, tss, dpl in idt_config: if handler and tss: error("entry specifies both handler function and tss") if not handler and not tss: error("entry does not specify either handler or tss") if handler: data = create_irq_gate(handler, dpl) else: data = create_task_gate(tss, dpl) fp.write(data) map_fmt = "<B" def create_irq_vec_map_binary(irq_vec_map, filename): with open(filename, "wb") as fp: for i in irq_vec_map: fp.write(struct.pack(map_fmt, i)) def priority_range(prio): # Priority levels are represented as groups of 16 vectors within the IDT base = 32 + (prio * 16) return range(base, base + 16) def update_irq_vec_map(irq_vec_map, irq, vector, max_irq): # No IRQ associated; exception or software interrupt if irq == -1: return if irq >= max_irq: error("irq %d specified, but CONFIG_MAX_IRQ_LINES is %d" % (irq, max_irq)) # This table will never have values less than 32 since those are for # exceptions; 0 means unconfigured if irq_vec_map[irq] != 0: error("multiple vector assignments for interrupt line %d", irq) debug("assign IRQ %d to vector %d" % (irq, vector)) irq_vec_map[irq] = vector def setup_idt(spur_code, spur_nocode, intlist, max_vec, max_irq): irq_vec_map = [0 for i in range(max_irq)] vectors = [None for i in range(max_vec)] # Pass 1: sanity check and set up hard-coded interrupt vectors for handler, irq, prio, vec, dpl, tss in intlist: if vec == -1: if prio == -1: error("entry does not specify vector or priority level") continue if vec >= max_vec: error("Vector %d specified, but size of IDT is only %d vectors" % (vec, max_vec)) if vectors[vec] != None: error("Multiple assignments for vector %d" % vec) vectors[vec] = (handler, tss, dpl) update_irq_vec_map(irq_vec_map, irq, vec, max_irq) # Pass 2: set up priority-based interrupt vectors for handler, irq, prio, vec, dpl, tss in intlist: if vec != -1: continue for vi in priority_range(prio): if vi >= max_vec: break if vectors[vi] == None: vec = vi break if vec == -1: error("can't find a free vector in priority level %d" % prio) vectors[vec] = (handler, tss, dpl) update_irq_vec_map(irq_vec_map, irq, vec, max_irq) # Pass 3: fill in unused vectors with spurious handler at dpl=0 for i in range(max_vec): if vectors[i] != None: continue if i in ERR_CODE_VECTORS: handler = spur_code else: handler = spur_nocode vectors[i] = (handler, 0, 0) return vectors, irq_vec_map def get_symbols(obj): for section in obj.iter_sections(): if isinstance(section, SymbolTableSection): return {sym.name: sym.entry.st_value for sym in section.iter_symbols()} raise LookupError("Could not find symbol table") # struct genidt_header_s { # uint32_t spurious_addr; # uint32_t spurious_no_error_addr; # int32_t num_entries; # }; intlist_header_fmt = "<IIi" # struct genidt_entry_s { # uint32_t isr; # int32_t irq; # int32_t priority; # int32_t vector_id; # int32_t dpl; # int32_t tss; # }; intlist_entry_fmt = "<Iiiiii" def get_intlist(elf): intdata = elf.get_section_by_name("intList").data() header_sz = struct.calcsize(intlist_header_fmt) header = struct.unpack_from(intlist_header_fmt, intdata, 0) intdata = intdata[header_sz:] spurious_code = header[0] spurious_nocode = header[1] debug("spurious handler (code) : %s" % hex(header[0])) debug("spurious handler (no code) : %s" % hex(header[1])) intlist = [i for i in struct.iter_unpack(intlist_entry_fmt, intdata)] debug("Configured interrupt routing") debug("handler irq pri vec dpl") debug("--------------------------") for irq in intlist: debug("{0:<10} {1:<3} {2:<3} {3:<3} {4:<2}".format( hex(irq[0]), "-" if irq[1] == -1 else irq[1], "-" if irq[2] == -1 else irq[2], "-" if irq[3] == -1 else irq[3], irq[4])) return (spurious_code, spurious_nocode, intlist) def parse_args(): global args parser = argparse.ArgumentParser(description = __doc__, formatter_class = argparse.RawDescriptionHelpFormatter) parser.add_argument("-m", "--vector-map", required=True, help="Output file mapping IRQ lines to IDT vectors") parser.add_argument("-o", "--output-idt", required=True, help="Output file containing IDT binary") parser.add_argument("-k", "--kernel", required=True, help="Zephyr kernel image") parser.add_argument("-v", "--verbose", action="store_true", help="Print extra debugging information") args = parser.parse_args() def main(): parse_args() with open(args.kernel, "rb") as fp: kernel = ELFFile(fp) syms = get_symbols(kernel) spur_code, spur_nocode, intlist = get_intlist(kernel) max_irq = syms["CONFIG_MAX_IRQ_LINES"] max_vec = syms["CONFIG_IDT_NUM_VECTORS"] vectors, irq_vec_map = setup_idt(spur_code, spur_nocode, intlist, max_vec, max_irq) create_idt_binary(vectors, args.output_idt) create_irq_vec_map_binary(irq_vec_map, args.vector_map) if __name__ == "__main__": main()
# Copyright (C) 2015 Pure Storage, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from datetime import timedelta import ddt import mock from oslo_utils import timeutils from cinder import context as ctxt from cinder.db.sqlalchemy import models from cinder.image import cache as image_cache from cinder import objects from cinder import test from cinder.tests.unit import fake_constants as fake @ddt.ddt class ImageVolumeCacheTestCase(test.TestCase): def setUp(self): super(ImageVolumeCacheTestCase, self).setUp() self.mock_db = mock.Mock() self.mock_volume_api = mock.Mock() self.context = ctxt.get_admin_context() self.volume = models.Volume() vol_params = {'id': fake.VOLUME_ID, 'host': 'foo@bar#whatever', 'cluster_name': 'cluster', 'size': 0} self.volume.update(vol_params) self.volume_ovo = objects.Volume(self.context, **vol_params) def _build_cache(self, max_gb=0, max_count=0): cache = image_cache.ImageVolumeCache(self.mock_db, self.mock_volume_api, max_gb, max_count) cache.notifier = self.notifier return cache def _build_entry(self, size=10): entry = { 'id': 1, 'host': 'test@foo#bar', 'cluster_name': 'cluster@foo#bar', 'image_id': 'c7a8b8d4-e519-46c7-a0df-ddf1b9b9fff2', 'image_updated_at': timeutils.utcnow(with_timezone=True), 'volume_id': '70a599e0-31e7-49b7-b260-868f441e862b', 'size': size, 'last_used': timeutils.utcnow(with_timezone=True) } return entry def test_get_by_image_volume(self): cache = self._build_cache() ret = {'id': 1} volume_id = '70a599e0-31e7-49b7-b260-868f441e862b' self.mock_db.image_volume_cache_get_by_volume_id.return_value = ret entry = cache.get_by_image_volume(self.context, volume_id) self.assertEqual(ret, entry) self.mock_db.image_volume_cache_get_by_volume_id.return_value = None entry = cache.get_by_image_volume(self.context, volume_id) self.assertIsNone(entry) def test_evict(self): cache = self._build_cache() entry = self._build_entry() cache.evict(self.context, entry) self.mock_db.image_volume_cache_delete.assert_called_once_with( self.context, entry['volume_id'] ) msg = self.notifier.notifications[0] self.assertEqual('image_volume_cache.evict', msg['event_type']) self.assertEqual('INFO', msg['priority']) self.assertEqual(entry['host'], msg['payload']['host']) self.assertEqual(entry['image_id'], msg['payload']['image_id']) self.assertEqual(1, len(self.notifier.notifications)) @ddt.data(True, False) def test_get_entry(self, clustered): cache = self._build_cache() entry = self._build_entry() image_meta = { 'is_public': True, 'owner': '70a599e0-31e7-49b7-b260-868f441e862b', 'properties': { 'virtual_size': '1.7' }, 'updated_at': entry['image_updated_at'] } (self.mock_db. image_volume_cache_get_and_update_last_used.return_value) = entry if not clustered: self.volume_ovo.cluster_name = None expect = {'host': self.volume.host} else: expect = {'cluster_name': self.volume.cluster_name} found_entry = cache.get_entry(self.context, self.volume_ovo, entry['image_id'], image_meta) self.assertDictEqual(entry, found_entry) (self.mock_db. image_volume_cache_get_and_update_last_used.assert_called_once_with)( self.context, entry['image_id'], **expect ) msg = self.notifier.notifications[0] self.assertEqual('image_volume_cache.hit', msg['event_type']) self.assertEqual('INFO', msg['priority']) self.assertEqual(entry['host'], msg['payload']['host']) self.assertEqual(entry['image_id'], msg['payload']['image_id']) self.assertEqual(1, len(self.notifier.notifications)) def test_get_entry_not_exists(self): cache = self._build_cache() image_meta = { 'is_public': True, 'owner': '70a599e0-31e7-49b7-b260-868f441e862b', 'properties': { 'virtual_size': '1.7' }, 'updated_at': timeutils.utcnow(with_timezone=True) } image_id = 'c7a8b8d4-e519-46c7-a0df-ddf1b9b9fff2' (self.mock_db. image_volume_cache_get_and_update_last_used.return_value) = None found_entry = cache.get_entry(self.context, self.volume_ovo, image_id, image_meta) self.assertIsNone(found_entry) msg = self.notifier.notifications[0] self.assertEqual('image_volume_cache.miss', msg['event_type']) self.assertEqual('INFO', msg['priority']) self.assertEqual(self.volume.host, msg['payload']['host']) self.assertEqual(image_id, msg['payload']['image_id']) self.assertEqual(1, len(self.notifier.notifications)) @mock.patch('cinder.objects.Volume.get_by_id') def test_get_entry_needs_update(self, mock_volume_by_id): cache = self._build_cache() entry = self._build_entry() image_meta = { 'is_public': True, 'owner': '70a599e0-31e7-49b7-b260-868f441e862b', 'properties': { 'virtual_size': '1.7' }, 'updated_at': entry['image_updated_at'] + timedelta(hours=2) } (self.mock_db. image_volume_cache_get_and_update_last_used.return_value) = entry mock_volume = mock.MagicMock() mock_volume_by_id.return_value = mock_volume found_entry = cache.get_entry(self.context, self.volume_ovo, entry['image_id'], image_meta) # Expect that the cache entry is not returned and the image-volume # for it is deleted. self.assertIsNone(found_entry) self.mock_volume_api.delete.assert_called_with(self.context, mock_volume) msg = self.notifier.notifications[0] self.assertEqual('image_volume_cache.miss', msg['event_type']) self.assertEqual('INFO', msg['priority']) self.assertEqual(self.volume.host, msg['payload']['host']) self.assertEqual(entry['image_id'], msg['payload']['image_id']) self.assertEqual(1, len(self.notifier.notifications)) def test_create_cache_entry(self): cache = self._build_cache() entry = self._build_entry() image_meta = { 'updated_at': entry['image_updated_at'] } self.mock_db.image_volume_cache_create.return_value = entry created_entry = cache.create_cache_entry(self.context, self.volume_ovo, entry['image_id'], image_meta) self.assertEqual(entry, created_entry) self.mock_db.image_volume_cache_create.assert_called_once_with( self.context, self.volume_ovo.host, self.volume_ovo.cluster_name, entry['image_id'], entry['image_updated_at'].replace(tzinfo=None), self.volume_ovo.id, self.volume_ovo.size ) def test_ensure_space_unlimited(self): cache = self._build_cache(max_gb=0, max_count=0) has_space = cache.ensure_space(self.context, self.volume) self.assertTrue(has_space) self.volume.size = 500 has_space = cache.ensure_space(self.context, self.volume) self.assertTrue(has_space) def test_ensure_space_no_entries(self): cache = self._build_cache(max_gb=100, max_count=10) self.mock_db.image_volume_cache_get_all.return_value = [] self.volume_ovo.size = 5 has_space = cache.ensure_space(self.context, self.volume_ovo) self.assertTrue(has_space) self.volume_ovo.size = 101 has_space = cache.ensure_space(self.context, self.volume_ovo) self.assertFalse(has_space) def test_ensure_space_need_gb(self): cache = self._build_cache(max_gb=30, max_count=10) mock_delete = mock.patch.object(cache, '_delete_image_volume').start() entries = [] entry1 = self._build_entry(size=12) entries.append(entry1) entry2 = self._build_entry(size=5) entries.append(entry2) entry3 = self._build_entry(size=10) entries.append(entry3) self.mock_db.image_volume_cache_get_all.return_value = entries self.volume_ovo.size = 15 has_space = cache.ensure_space(self.context, self.volume_ovo) self.assertTrue(has_space) self.assertEqual(2, mock_delete.call_count) mock_delete.assert_any_call(self.context, entry2) mock_delete.assert_any_call(self.context, entry3) self.mock_db.image_volume_cache_get_all.assert_called_with( self.context, cluster_name=self.volume_ovo.cluster_name) def test_ensure_space_need_count(self): cache = self._build_cache(max_gb=30, max_count=2) mock_delete = mock.patch.object(cache, '_delete_image_volume').start() entries = [] entry1 = self._build_entry(size=10) entries.append(entry1) entry2 = self._build_entry(size=5) entries.append(entry2) self.mock_db.image_volume_cache_get_all.return_value = entries self.volume_ovo.size = 12 has_space = cache.ensure_space(self.context, self.volume_ovo) self.assertTrue(has_space) self.assertEqual(1, mock_delete.call_count) mock_delete.assert_any_call(self.context, entry2) def test_ensure_space_need_gb_and_count(self): cache = self._build_cache(max_gb=30, max_count=3) mock_delete = mock.patch.object(cache, '_delete_image_volume').start() entries = [] entry1 = self._build_entry(size=10) entries.append(entry1) entry2 = self._build_entry(size=5) entries.append(entry2) entry3 = self._build_entry(size=12) entries.append(entry3) self.mock_db.image_volume_cache_get_all.return_value = entries self.volume_ovo.size = 16 has_space = cache.ensure_space(self.context, self.volume_ovo) self.assertTrue(has_space) self.assertEqual(2, mock_delete.call_count) mock_delete.assert_any_call(self.context, entry2) mock_delete.assert_any_call(self.context, entry3) def test_ensure_space_cant_free_enough_gb(self): cache = self._build_cache(max_gb=30, max_count=10) mock_delete = mock.patch.object(cache, '_delete_image_volume').start() entries = list(self._build_entry(size=25)) self.mock_db.image_volume_cache_get_all.return_value = entries self.volume_ovo.size = 50 has_space = cache.ensure_space(self.context, self.volume_ovo) self.assertFalse(has_space) mock_delete.assert_not_called()
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from grpc.framework.common import cardinality from grpc.framework.interfaces.face import utilities as face_utilities import google.cloud.proto.spanner.v1.result_set_pb2 as google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_result__set__pb2 import google.cloud.proto.spanner.v1.spanner_pb2 as google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2 import google.cloud.proto.spanner.v1.transaction_pb2 as google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_transaction__pb2 import google.protobuf.empty_pb2 as google_dot_protobuf_dot_empty__pb2 class SpannerStub(object): """Cloud Spanner API The Cloud Spanner API can be used to manage sessions and execute transactions on data stored in Cloud Spanner databases. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.CreateSession = channel.unary_unary( '/google.spanner.v1.Spanner/CreateSession', request_serializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.CreateSessionRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.Session.FromString, ) self.GetSession = channel.unary_unary( '/google.spanner.v1.Spanner/GetSession', request_serializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.GetSessionRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.Session.FromString, ) self.DeleteSession = channel.unary_unary( '/google.spanner.v1.Spanner/DeleteSession', request_serializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.DeleteSessionRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) self.ExecuteSql = channel.unary_unary( '/google.spanner.v1.Spanner/ExecuteSql', request_serializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.ExecuteSqlRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_result__set__pb2.ResultSet.FromString, ) self.ExecuteStreamingSql = channel.unary_stream( '/google.spanner.v1.Spanner/ExecuteStreamingSql', request_serializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.ExecuteSqlRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_result__set__pb2.PartialResultSet.FromString, ) self.Read = channel.unary_unary( '/google.spanner.v1.Spanner/Read', request_serializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.ReadRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_result__set__pb2.ResultSet.FromString, ) self.StreamingRead = channel.unary_stream( '/google.spanner.v1.Spanner/StreamingRead', request_serializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.ReadRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_result__set__pb2.PartialResultSet.FromString, ) self.BeginTransaction = channel.unary_unary( '/google.spanner.v1.Spanner/BeginTransaction', request_serializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.BeginTransactionRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_transaction__pb2.Transaction.FromString, ) self.Commit = channel.unary_unary( '/google.spanner.v1.Spanner/Commit', request_serializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.CommitRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.CommitResponse.FromString, ) self.Rollback = channel.unary_unary( '/google.spanner.v1.Spanner/Rollback', request_serializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.RollbackRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) class SpannerServicer(object): """Cloud Spanner API The Cloud Spanner API can be used to manage sessions and execute transactions on data stored in Cloud Spanner databases. """ def CreateSession(self, request, context): """Creates a new session. A session can be used to perform transactions that read and/or modify data in a Cloud Spanner database. Sessions are meant to be reused for many consecutive transactions. Sessions can only execute one transaction at a time. To execute multiple concurrent read-write/write-only transactions, create multiple sessions. Note that standalone reads and queries use a transaction internally, and count toward the one transaction limit. Cloud Spanner limits the number of sessions that can exist at any given time; thus, it is a good idea to delete idle and/or unneeded sessions. Aside from explicit deletes, Cloud Spanner can delete sessions for which no operations are sent for more than an hour. If a session is deleted, requests to it return `NOT_FOUND`. Idle sessions can be kept alive by sending a trivial SQL query periodically, e.g., `"SELECT 1"`. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetSession(self, request, context): """Gets a session. Returns `NOT_FOUND` if the session does not exist. This is mainly useful for determining whether a session is still alive. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DeleteSession(self, request, context): """Ends a session, releasing server resources associated with it. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ExecuteSql(self, request, context): """Executes an SQL query, returning all rows in a single reply. This method cannot be used to return a result set larger than 10 MiB; if the query yields more data than that, the query fails with a `FAILED_PRECONDITION` error. Queries inside read-write transactions might return `ABORTED`. If this occurs, the application should restart the transaction from the beginning. See [Transaction][google.spanner.v1.Transaction] for more details. Larger result sets can be fetched in streaming fashion by calling [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] instead. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ExecuteStreamingSql(self, request, context): """Like [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], except returns the result set as a stream. Unlike [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], there is no limit on the size of the returned result set. However, no individual row in the result set can exceed 100 MiB, and no column value can exceed 10 MiB. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def Read(self, request, context): """Reads rows from the database using key lookups and scans, as a simple key/value style alternative to [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql]. This method cannot be used to return a result set larger than 10 MiB; if the read matches more data than that, the read fails with a `FAILED_PRECONDITION` error. Reads inside read-write transactions might return `ABORTED`. If this occurs, the application should restart the transaction from the beginning. See [Transaction][google.spanner.v1.Transaction] for more details. Larger result sets can be yielded in streaming fashion by calling [StreamingRead][google.spanner.v1.Spanner.StreamingRead] instead. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def StreamingRead(self, request, context): """Like [Read][google.spanner.v1.Spanner.Read], except returns the result set as a stream. Unlike [Read][google.spanner.v1.Spanner.Read], there is no limit on the size of the returned result set. However, no individual row in the result set can exceed 100 MiB, and no column value can exceed 10 MiB. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def BeginTransaction(self, request, context): """Begins a new transaction. This step can often be skipped: [Read][google.spanner.v1.Spanner.Read], [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and [Commit][google.spanner.v1.Spanner.Commit] can begin a new transaction as a side-effect. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def Commit(self, request, context): """Commits a transaction. The request includes the mutations to be applied to rows in the database. `Commit` might return an `ABORTED` error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other reasons. If `Commit` returns `ABORTED`, the caller should re-attempt the transaction from the beginning, re-using the same session. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def Rollback(self, request, context): """Rolls back a transaction, releasing any locks it holds. It is a good idea to call this for any transaction that includes one or more [Read][google.spanner.v1.Spanner.Read] or [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] requests and ultimately decides not to commit. `Rollback` returns `OK` if it successfully aborts the transaction, the transaction was already aborted, or the transaction is not found. `Rollback` never returns `ABORTED`. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_SpannerServicer_to_server(servicer, server): rpc_method_handlers = { 'CreateSession': grpc.unary_unary_rpc_method_handler( servicer.CreateSession, request_deserializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.CreateSessionRequest.FromString, response_serializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.Session.SerializeToString, ), 'GetSession': grpc.unary_unary_rpc_method_handler( servicer.GetSession, request_deserializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.GetSessionRequest.FromString, response_serializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.Session.SerializeToString, ), 'DeleteSession': grpc.unary_unary_rpc_method_handler( servicer.DeleteSession, request_deserializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.DeleteSessionRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), 'ExecuteSql': grpc.unary_unary_rpc_method_handler( servicer.ExecuteSql, request_deserializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.ExecuteSqlRequest.FromString, response_serializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_result__set__pb2.ResultSet.SerializeToString, ), 'ExecuteStreamingSql': grpc.unary_stream_rpc_method_handler( servicer.ExecuteStreamingSql, request_deserializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.ExecuteSqlRequest.FromString, response_serializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_result__set__pb2.PartialResultSet.SerializeToString, ), 'Read': grpc.unary_unary_rpc_method_handler( servicer.Read, request_deserializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.ReadRequest.FromString, response_serializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_result__set__pb2.ResultSet.SerializeToString, ), 'StreamingRead': grpc.unary_stream_rpc_method_handler( servicer.StreamingRead, request_deserializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.ReadRequest.FromString, response_serializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_result__set__pb2.PartialResultSet.SerializeToString, ), 'BeginTransaction': grpc.unary_unary_rpc_method_handler( servicer.BeginTransaction, request_deserializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.BeginTransactionRequest.FromString, response_serializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_transaction__pb2.Transaction.SerializeToString, ), 'Commit': grpc.unary_unary_rpc_method_handler( servicer.Commit, request_deserializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.CommitRequest.FromString, response_serializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.CommitResponse.SerializeToString, ), 'Rollback': grpc.unary_unary_rpc_method_handler( servicer.Rollback, request_deserializer=google_dot_cloud_dot_proto_dot_spanner_dot_v1_dot_spanner__pb2.RollbackRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'google.spanner.v1.Spanner', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,))
#!/usr/bin/env python # # 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. # # Utility for creating well-formed pull request merges and pushing them to Apache. # usage: ./apache-pr-merge.py (see config env vars below) # # This utility assumes you already have local a Parquet git folder and that you # have added remotes corresponding to both (i) the github apache Parquet # mirror and (ii) the apache git repo. import json import os import re import subprocess import sys import tempfile import urllib2 import getpass try: import jira.client JIRA_IMPORTED = True except ImportError: JIRA_IMPORTED = False # Location of your Parquet git development area PARQUET_HOME = os.path.abspath(__file__).rsplit("/", 2)[0] PROJECT_NAME = PARQUET_HOME.rsplit("/", 1)[1] print "PARQUET_HOME = " + PARQUET_HOME print "PROJECT_NAME = " + PROJECT_NAME # Remote name which points to the Gihub site PR_REMOTE_NAME = os.environ.get("PR_REMOTE_NAME", "apache-github") # Remote name which points to Apache git PUSH_REMOTE_NAME = os.environ.get("PUSH_REMOTE_NAME", "apache") # ASF JIRA username JIRA_USERNAME = os.environ.get("JIRA_USERNAME") # ASF JIRA password JIRA_PASSWORD = os.environ.get("JIRA_PASSWORD") GITHUB_BASE = "https://github.com/apache/" + PROJECT_NAME + "/pull" GITHUB_API_BASE = "https://api.github.com/repos/apache/" + PROJECT_NAME JIRA_BASE = "https://issues.apache.org/jira/browse" JIRA_API_BASE = "https://issues.apache.org/jira" # Prefix added to temporary branches BRANCH_PREFIX = "PR_TOOL" os.chdir(PARQUET_HOME) def get_json(url): try: return json.load(urllib2.urlopen(url)) except urllib2.HTTPError as e: print "Unable to fetch URL, exiting: %s" % url sys.exit(-1) def fail(msg): print msg clean_up() sys.exit(-1) def run_cmd(cmd): if isinstance(cmd, list): return subprocess.check_output(cmd) else: return subprocess.check_output(cmd.split(" ")) def continue_maybe(prompt): result = raw_input("\n%s (y/n): " % prompt) if result.lower() != "y": fail("Okay, exiting") original_head = run_cmd("git rev-parse HEAD")[:8] def clean_up(): print "Restoring head pointer to %s" % original_head run_cmd("git checkout %s" % original_head) branches = run_cmd("git branch").replace(" ", "").split("\n") for branch in filter(lambda x: x.startswith(BRANCH_PREFIX), branches): print "Deleting local branch %s" % branch run_cmd("git branch -D %s" % branch) # merge the requested PR and return the merge hash def merge_pr(pr_num, target_ref): pr_branch_name = "%s_MERGE_PR_%s" % (BRANCH_PREFIX, pr_num) target_branch_name = "%s_MERGE_PR_%s_%s" % (BRANCH_PREFIX, pr_num, target_ref.upper()) run_cmd("git fetch %s pull/%s/head:%s" % (PR_REMOTE_NAME, pr_num, pr_branch_name)) run_cmd("git fetch %s %s:%s" % (PUSH_REMOTE_NAME, target_ref, target_branch_name)) run_cmd("git checkout %s" % target_branch_name) had_conflicts = False try: run_cmd(['git', 'merge', pr_branch_name, '--squash']) except Exception as e: msg = "Error merging: %s\nWould you like to manually fix-up this merge?" % e continue_maybe(msg) msg = "Okay, please fix any conflicts and 'git add' conflicting files... Finished?" continue_maybe(msg) had_conflicts = True commit_authors = run_cmd(['git', 'log', 'HEAD..%s' % pr_branch_name, '--pretty=format:%an <%ae>']).split("\n") distinct_authors = sorted(set(commit_authors), key=lambda x: commit_authors.count(x), reverse=True) primary_author = distinct_authors[0] commits = run_cmd(['git', 'log', 'HEAD..%s' % pr_branch_name, '--pretty=format:%h [%an] %s']).split("\n\n") merge_message_flags = [] merge_message_flags += ["-m", title] if body != None: merge_message_flags += ["-m", body] authors = "\n".join(["Author: %s" % a for a in distinct_authors]) merge_message_flags += ["-m", authors] if had_conflicts: committer_name = run_cmd("git config --get user.name").strip() committer_email = run_cmd("git config --get user.email").strip() message = "This patch had conflicts when merged, resolved by\nCommitter: %s <%s>" % ( committer_name, committer_email) merge_message_flags += ["-m", message] # The string "Closes #%s" string is required for GitHub to correctly close the PR merge_message_flags += [ "-m", "Closes #%s from %s and squashes the following commits:" % (pr_num, pr_repo_desc)] for c in commits: merge_message_flags += ["-m", c] run_cmd(['git', 'commit', '--author="%s"' % primary_author] + merge_message_flags) continue_maybe("Merge complete (local ref %s). Push to %s?" % ( target_branch_name, PUSH_REMOTE_NAME)) try: run_cmd('git push %s %s:%s' % (PUSH_REMOTE_NAME, target_branch_name, target_ref)) except Exception as e: clean_up() fail("Exception while pushing: %s" % e) merge_hash = run_cmd("git rev-parse %s" % target_branch_name)[:8] clean_up() print("Pull request #%s merged!" % pr_num) print("Merge hash: %s" % merge_hash) return merge_hash def cherry_pick(pr_num, merge_hash, default_branch): pick_ref = raw_input("Enter a branch name [%s]: " % default_branch) if pick_ref == "": pick_ref = default_branch pick_branch_name = "%s_PICK_PR_%s_%s" % (BRANCH_PREFIX, pr_num, pick_ref.upper()) run_cmd("git fetch %s %s:%s" % (PUSH_REMOTE_NAME, pick_ref, pick_branch_name)) run_cmd("git checkout %s" % pick_branch_name) run_cmd("git cherry-pick -sx %s" % merge_hash) continue_maybe("Pick complete (local ref %s). Push to %s?" % ( pick_branch_name, PUSH_REMOTE_NAME)) try: run_cmd('git push %s %s:%s' % (PUSH_REMOTE_NAME, pick_branch_name, pick_ref)) except Exception as e: clean_up() fail("Exception while pushing: %s" % e) pick_hash = run_cmd("git rev-parse %s" % pick_branch_name)[:8] clean_up() print("Pull request #%s picked into %s!" % (pr_num, pick_ref)) print("Pick hash: %s" % pick_hash) return pick_ref def fix_version_from_branch(branch, versions): # Note: Assumes this is a sorted (newest->oldest) list of un-released versions if branch == "master": return versions[0] else: branch_ver = branch.replace("branch-", "") return filter(lambda x: x.name.startswith(branch_ver), versions)[-1] def exctract_jira_id(title): m = re.search('^(PARQUET-[0-9]+):.*$', title) if m and m.groups > 0: return m.group(1) else: fail("PR title should be prefixed by a jira id \"PARQUET-XXX: ...\", found: \"%s\"" % title) def check_jira(title): jira_id = exctract_jira_id(title) asf_jira = jira.client.JIRA({'server': JIRA_API_BASE}, basic_auth=(JIRA_USERNAME, JIRA_PASSWORD)) try: issue = asf_jira.issue(jira_id) except Exception as e: fail("ASF JIRA could not find %s\n%s" % (jira_id, e)) def resolve_jira(title, merge_branches, comment): asf_jira = jira.client.JIRA({'server': JIRA_API_BASE}, basic_auth=(JIRA_USERNAME, JIRA_PASSWORD)) default_jira_id = exctract_jira_id(title) jira_id = raw_input("Enter a JIRA id [%s]: " % default_jira_id) if jira_id == "": jira_id = default_jira_id try: issue = asf_jira.issue(jira_id) except Exception as e: fail("ASF JIRA could not find %s\n%s" % (jira_id, e)) cur_status = issue.fields.status.name cur_summary = issue.fields.summary cur_assignee = issue.fields.assignee if cur_assignee is None: cur_assignee = "NOT ASSIGNED!!!" else: cur_assignee = cur_assignee.displayName if cur_status == "Resolved" or cur_status == "Closed": fail("JIRA issue %s already has status '%s'" % (jira_id, cur_status)) print ("=== JIRA %s ===" % jira_id) print ("summary\t\t%s\nassignee\t%s\nstatus\t\t%s\nurl\t\t%s/%s\n" % ( cur_summary, cur_assignee, cur_status, JIRA_BASE, jira_id)) versions = asf_jira.project_versions("PARQUET") versions = sorted(versions, key=lambda x: x.name, reverse=True) versions = filter(lambda x: x.raw['released'] is False, versions) default_fix_versions = map(lambda x: fix_version_from_branch(x, versions).name, merge_branches) for v in default_fix_versions: # Handles the case where we have forked a release branch but not yet made the release. # In this case, if the PR is committed to the master branch and the release branch, we # only consider the release branch to be the fix version. E.g. it is not valid to have # both 1.1.0 and 1.0.0 as fix versions. (major, minor, patch) = v.split(".") if patch == "0": previous = "%s.%s.%s" % (major, int(minor) - 1, 0) if previous in default_fix_versions: default_fix_versions = filter(lambda x: x != v, default_fix_versions) default_fix_versions = ",".join(default_fix_versions) fix_versions = raw_input("Enter comma-separated fix version(s) [%s]: " % default_fix_versions) if fix_versions == "": fix_versions = default_fix_versions fix_versions = fix_versions.replace(" ", "").split(",") def get_version_json(version_str): return filter(lambda v: v.name == version_str, versions)[0].raw jira_fix_versions = map(lambda v: get_version_json(v), fix_versions) resolve = filter(lambda a: a['name'] == "Resolve Issue", asf_jira.transitions(jira_id))[0] asf_jira.transition_issue( jira_id, resolve["id"], fixVersions=jira_fix_versions, comment=comment) print "Succesfully resolved %s with fixVersions=%s!" % (jira_id, fix_versions) if not JIRA_USERNAME: JIRA_USERNAME = raw_input("Env JIRA_USERNAME not set, please enter your JIRA username:") if not JIRA_PASSWORD: JIRA_PASSWORD = getpass.getpass("Env JIRA_PASSWORD not set, please enter your JIRA password:") branches = get_json("%s/branches" % GITHUB_API_BASE) branch_names = filter(lambda x: x.startswith("branch-"), [x['name'] for x in branches]) # Assumes branch names can be sorted lexicographically # Julien: I commented this out as we don't have any "branch-*" branch yet #latest_branch = sorted(branch_names, reverse=True)[0] pr_num = raw_input("Which pull request would you like to merge? (e.g. 34): ") pr = get_json("%s/pulls/%s" % (GITHUB_API_BASE, pr_num)) url = pr["url"] title = pr["title"] check_jira(title) body = pr["body"] target_ref = pr["base"]["ref"] user_login = pr["user"]["login"] base_ref = pr["head"]["ref"] pr_repo_desc = "%s/%s" % (user_login, base_ref) if pr["merged"] is True: print "Pull request %s has already been merged, assuming you want to backport" % pr_num merge_commit_desc = run_cmd([ 'git', 'log', '--merges', '--first-parent', '--grep=pull request #%s' % pr_num, '--oneline']).split("\n")[0] if merge_commit_desc == "": fail("Couldn't find any merge commit for #%s, you may need to update HEAD." % pr_num) merge_hash = merge_commit_desc[:7] message = merge_commit_desc[8:] print "Found: %s" % message maybe_cherry_pick(pr_num, merge_hash, latest_branch) sys.exit(0) if not bool(pr["mergeable"]): msg = "Pull request %s is not mergeable in its current form.\n" % pr_num + \ "Continue? (experts only!)" continue_maybe(msg) print ("\n=== Pull Request #%s ===" % pr_num) print ("title\t%s\nsource\t%s\ntarget\t%s\nurl\t%s" % ( title, pr_repo_desc, target_ref, url)) continue_maybe("Proceed with merging pull request #%s?" % pr_num) merged_refs = [target_ref] merge_hash = merge_pr(pr_num, target_ref) pick_prompt = "Would you like to pick %s into another branch?" % merge_hash while raw_input("\n%s (y/n): " % pick_prompt).lower() == "y": merged_refs = merged_refs + [cherry_pick(pr_num, merge_hash, latest_branch)] if JIRA_IMPORTED: continue_maybe("Would you like to update the associated JIRA?") jira_comment = "Issue resolved by pull request %s\n[%s/%s]" % (pr_num, GITHUB_BASE, pr_num) resolve_jira(title, merged_refs, jira_comment) else: print "Could not find jira-python library. Run 'sudo pip install jira-python' to install." print "Exiting without trying to close the associated JIRA."
# Lint as: python2, python3 # Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utilities for collecting TFLite metrics.""" import collections import enum import functools from typing import Text from tensorflow.lite.python.metrics import converter_error_data_pb2 from tensorflow.lite.python.metrics import metrics class Component(enum.Enum): """Enum class defining name of the converter components.""" # Validate the given input and prepare and optimize TensorFlow Model. PREPARE_TF_MODEL = "PREPARE_TF_MODEL" # Convert to TFLite model format. CONVERT_TF_TO_TFLITE_MODEL = "CONVERT_TF_TO_TFLITE_MODEL" # RUN quantization and sparsification. OPTIMIZE_TFLITE_MODEL = "OPTIMIZE_TFLITE_MODEL" SubComponentItem = collections.namedtuple("SubComponentItem", ["name", "component"]) class SubComponent(enum.Enum): """Enum class defining name of the converter subcomponents. This enum only defines the subcomponents in Python, there might be more subcomponents defined in C++. """ def __str__(self): return self.value.name @property def name(self): return self.value.name @property def component(self): return self.value.component # The subcomponent name is unspecified. UNSPECIFIED = SubComponentItem("UNSPECIFIED", None) # Valid the given input and parameters. VALIDATE_INPUTS = SubComponentItem("VALIDATE_INPUTS", Component.PREPARE_TF_MODEL) # Load GraphDef from SavedModel. LOAD_SAVED_MODEL = SubComponentItem("LOAD_SAVED_MODEL", Component.PREPARE_TF_MODEL) # Convert a SavedModel to frozen graph. FREEZE_SAVED_MODEL = SubComponentItem("FREEZE_SAVED_MODEL", Component.PREPARE_TF_MODEL) # Save a Keras model to SavedModel. CONVERT_KERAS_TO_SAVED_MODEL = SubComponentItem( "CONVERT_KERAS_TO_SAVED_MODEL", Component.PREPARE_TF_MODEL) # Save Concrete functions to SavedModel. CONVERT_CONCRETE_FUNCTIONS_TO_SAVED_MODEL = SubComponentItem( "CONVERT_CONCRETE_FUNCTIONS_TO_SAVED_MODEL", Component.PREPARE_TF_MODEL) # Convert a Keras model to a frozen graph. FREEZE_KERAS_MODEL = SubComponentItem("FREEZE_KERAS_MODEL", Component.PREPARE_TF_MODEL) # Replace all the variables with constants in a ConcreteFunction. FREEZE_CONCRETE_FUNCTION = SubComponentItem("FREEZE_CONCRETE_FUNCTION", Component.PREPARE_TF_MODEL) # Run grappler optimization. OPTIMIZE_TF_MODEL = SubComponentItem("OPTIMIZE_TF_MODEL", Component.PREPARE_TF_MODEL) # Convert using the old TOCO converter. CONVERT_GRAPHDEF_USING_DEPRECATED_CONVERTER = SubComponentItem( "CONVERT_GRAPHDEF_USING_DEPRECATED_CONVERTER", Component.CONVERT_TF_TO_TFLITE_MODEL) # Convert a GraphDef to TFLite model. CONVERT_GRAPHDEF = SubComponentItem("CONVERT_GRAPHDEF", Component.CONVERT_TF_TO_TFLITE_MODEL) # Convert a SavedModel to TFLite model. CONVERT_SAVED_MODEL = SubComponentItem("CONVERT_SAVED_MODEL", Component.CONVERT_TF_TO_TFLITE_MODEL) # Convert a Jax HLO to TFLite model. CONVERT_JAX_HLO = SubComponentItem("CONVERT_JAX_HLO", Component.CONVERT_TF_TO_TFLITE_MODEL) # Do quantization by the deprecated quantizer. QUANTIZE_USING_DEPRECATED_QUANTIZER = SubComponentItem( "QUANTIZE_USING_DEPRECATED_QUANTIZER", Component.OPTIMIZE_TFLITE_MODEL) # Do calibration. CALIBRATE = SubComponentItem("CALIBRATE", Component.OPTIMIZE_TFLITE_MODEL) # Do quantization by MLIR. QUANTIZE = SubComponentItem("QUANTIZE", Component.OPTIMIZE_TFLITE_MODEL) # Do sparsification by MLIR. SPARSIFY = SubComponentItem("SPARSIFY", Component.OPTIMIZE_TFLITE_MODEL) class ConverterError(Exception): """Raised when an error occurs during model conversion.""" def __init__(self, message): super(ConverterError, self).__init__(message) self.errors = [] self._parse_error_message(message) def append_error(self, error_data: converter_error_data_pb2.ConverterErrorData): self.errors.append(error_data) def _parse_error_message(self, message): """If the message matches a pattern, assigns the associated error code. It is difficult to assign an error code to some errrors in MLIR side, Ex: errors thrown by other components than TFLite or not using mlir::emitError. This function try to detect them by the error message and assign the corresponding error code. Args: message: The error message of this exception. """ error_code_mapping = { "Failed to functionalize Control Flow V1 ops. Consider using Control " "Flow V2 ops instead. See https://www.tensorflow.org/api_docs/python/" "tf/compat/v1/enable_control_flow_v2.": converter_error_data_pb2.ConverterErrorData .ERROR_UNSUPPORTED_CONTROL_FLOW_V1, } for pattern, error_code in error_code_mapping.items(): if pattern in message: error_data = converter_error_data_pb2.ConverterErrorData() error_data.error_message = message error_data.error_code = error_code self.append_error(error_data) return def convert_phase(component, subcomponent=SubComponent.UNSPECIFIED): """The decorator to identify converter component and subcomponent. Args: component: Converter component name. subcomponent: Converter subcomponent name. Returns: Forward the result from the wrapped function. Raises: ValueError: if component and subcomponent name is not valid. """ if component not in Component: raise ValueError("Given component name not found") if subcomponent not in SubComponent: raise ValueError("Given subcomponent name not found") if (subcomponent != SubComponent.UNSPECIFIED and subcomponent.component != component): raise ValueError("component and subcomponent name don't match") def report_error(error_data: converter_error_data_pb2.ConverterErrorData): # Always overwrites the component information, but only overwrites the # subcomponent if it is not available. error_data.component = component.value if not error_data.subcomponent: error_data.subcomponent = subcomponent.name tflite_metrics = metrics.TFLiteConverterMetrics() tflite_metrics.set_converter_error(error_data) def report_error_message(error_message: Text): error_data = converter_error_data_pb2.ConverterErrorData() error_data.error_message = error_message report_error(error_data) def actual_decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except ConverterError as converter_error: if converter_error.errors: for error_data in converter_error.errors: report_error(error_data) else: report_error_message(str(converter_error)) raise converter_error from None # Re-throws the exception. except Exception as error: report_error_message(str(error)) raise error from None # Re-throws the exception. return wrapper return actual_decorator
"""Utilities to evaluate models with respect to a variable """ # Author: Alexander Fabisch <afabisch@informatik.uni-bremen.de> # # License: BSD 3 clause import warnings import numpy as np from .base import is_classifier, clone from .cross_validation import check_cv from .externals.joblib import Parallel, delayed from .cross_validation import _safe_split, _score, _fit_and_score from .metrics.scorer import check_scoring from .utils import indexable from .utils.fixes import astype __all__ = ['learning_curve', 'validation_curve'] def learning_curve(estimator, X, y, train_sizes=np.linspace(0.1, 1.0, 5), cv=None, scoring=None, exploit_incremental_learning=False, n_jobs=1, pre_dispatch="all", verbose=0): """Learning curve. Determines cross-validated training and test scores for different training set sizes. A cross-validation generator splits the whole dataset k times in training and test data. Subsets of the training set with varying sizes will be used to train the estimator and a score for each training subset size and the test set will be computed. Afterwards, the scores will be averaged over all k runs for each training subset size. Read more in the :ref:`User Guide <learning_curves>`. Parameters ---------- estimator : object type that implements the "fit" and "predict" methods An object of that type which is cloned for each validation. X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape (n_samples) or (n_samples, n_features), optional Target relative to X for classification or regression; None for unsupervised learning. train_sizes : array-like, shape (n_ticks,), dtype float or int Relative or absolute numbers of training examples that will be used to generate the learning curve. If the dtype is float, it is regarded as a fraction of the maximum size of the training set (that is determined by the selected validation method), i.e. it has to be within (0, 1]. Otherwise it is interpreted as absolute sizes of the training sets. Note that for classification the number of samples usually have to be big enough to contain at least one sample from each class. (default: np.linspace(0.1, 1.0, 5)) cv : int, cross-validation generator or an iterable, optional Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the default 3-fold cross-validation, - integer, to specify the number of folds. - An object to be used as a cross-validation generator. - An iterable yielding train/test splits. For integer/None inputs, if ``y`` is binary or multiclass, :class:`StratifiedKFold` used. If the estimator is a classifier or if ``y`` is neither binary nor multiclass, :class:`KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validation strategies that can be used here. scoring : string, callable or None, optional, default: None A string (see model evaluation documentation) or a scorer callable object / function with signature ``scorer(estimator, X, y)``. exploit_incremental_learning : boolean, optional, default: False If the estimator supports incremental learning, this will be used to speed up fitting for different training set sizes. n_jobs : integer, optional Number of jobs to run in parallel (default 1). pre_dispatch : integer or string, optional Number of predispatched jobs for parallel execution (default is all). The option can reduce the allocated memory. The string can be an expression like '2*n_jobs'. verbose : integer, optional Controls the verbosity: the higher, the more messages. Returns ------- train_sizes_abs : array, shape = (n_unique_ticks,), dtype int Numbers of training examples that has been used to generate the learning curve. Note that the number of ticks might be less than n_ticks because duplicate entries will be removed. train_scores : array, shape (n_ticks, n_cv_folds) Scores on training sets. test_scores : array, shape (n_ticks, n_cv_folds) Scores on test set. Notes ----- See :ref:`examples/model_selection/plot_learning_curve.py <example_model_selection_plot_learning_curve.py>` """ if exploit_incremental_learning and not hasattr(estimator, "partial_fit"): raise ValueError("An estimator must support the partial_fit interface " "to exploit incremental learning") X, y = indexable(X, y) # Make a list since we will be iterating multiple times over the folds cv = list(check_cv(cv, X, y, classifier=is_classifier(estimator))) scorer = check_scoring(estimator, scoring=scoring) # HACK as long as boolean indices are allowed in cv generators if cv[0][0].dtype == bool: new_cv = [] for i in range(len(cv)): new_cv.append((np.nonzero(cv[i][0])[0], np.nonzero(cv[i][1])[0])) cv = new_cv n_max_training_samples = len(cv[0][0]) # Because the lengths of folds can be significantly different, it is # not guaranteed that we use all of the available training data when we # use the first 'n_max_training_samples' samples. train_sizes_abs = _translate_train_sizes(train_sizes, n_max_training_samples) n_unique_ticks = train_sizes_abs.shape[0] if verbose > 0: print("[learning_curve] Training set sizes: " + str(train_sizes_abs)) parallel = Parallel(n_jobs=n_jobs, pre_dispatch=pre_dispatch, verbose=verbose) if exploit_incremental_learning: classes = np.unique(y) if is_classifier(estimator) else None out = parallel(delayed(_incremental_fit_estimator)( clone(estimator), X, y, classes, train, test, train_sizes_abs, scorer, verbose) for train, test in cv) else: out = parallel(delayed(_fit_and_score)( clone(estimator), X, y, scorer, train[:n_train_samples], test, verbose, parameters=None, fit_params=None, return_train_score=True) for train, test in cv for n_train_samples in train_sizes_abs) out = np.array(out)[:, :2] n_cv_folds = out.shape[0] // n_unique_ticks out = out.reshape(n_cv_folds, n_unique_ticks, 2) out = np.asarray(out).transpose((2, 1, 0)) return train_sizes_abs, out[0], out[1] def _translate_train_sizes(train_sizes, n_max_training_samples): """Determine absolute sizes of training subsets and validate 'train_sizes'. Examples: _translate_train_sizes([0.5, 1.0], 10) -> [5, 10] _translate_train_sizes([5, 10], 10) -> [5, 10] Parameters ---------- train_sizes : array-like, shape (n_ticks,), dtype float or int Numbers of training examples that will be used to generate the learning curve. If the dtype is float, it is regarded as a fraction of 'n_max_training_samples', i.e. it has to be within (0, 1]. n_max_training_samples : int Maximum number of training samples (upper bound of 'train_sizes'). Returns ------- train_sizes_abs : array, shape (n_unique_ticks,), dtype int Numbers of training examples that will be used to generate the learning curve. Note that the number of ticks might be less than n_ticks because duplicate entries will be removed. """ train_sizes_abs = np.asarray(train_sizes) n_ticks = train_sizes_abs.shape[0] n_min_required_samples = np.min(train_sizes_abs) n_max_required_samples = np.max(train_sizes_abs) if np.issubdtype(train_sizes_abs.dtype, np.float): if n_min_required_samples <= 0.0 or n_max_required_samples > 1.0: raise ValueError("train_sizes has been interpreted as fractions " "of the maximum number of training samples and " "must be within (0, 1], but is within [%f, %f]." % (n_min_required_samples, n_max_required_samples)) train_sizes_abs = astype(train_sizes_abs * n_max_training_samples, dtype=np.int, copy=False) train_sizes_abs = np.clip(train_sizes_abs, 1, n_max_training_samples) else: if (n_min_required_samples <= 0 or n_max_required_samples > n_max_training_samples): raise ValueError("train_sizes has been interpreted as absolute " "numbers of training samples and must be within " "(0, %d], but is within [%d, %d]." % (n_max_training_samples, n_min_required_samples, n_max_required_samples)) train_sizes_abs = np.unique(train_sizes_abs) if n_ticks > train_sizes_abs.shape[0]: warnings.warn("Removed duplicate entries from 'train_sizes'. Number " "of ticks will be less than than the size of " "'train_sizes' %d instead of %d)." % (train_sizes_abs.shape[0], n_ticks), RuntimeWarning) return train_sizes_abs def _incremental_fit_estimator(estimator, X, y, classes, train, test, train_sizes, scorer, verbose): """Train estimator on training subsets incrementally and compute scores.""" train_scores, test_scores = [], [] partitions = zip(train_sizes, np.split(train, train_sizes)[:-1]) for n_train_samples, partial_train in partitions: train_subset = train[:n_train_samples] X_train, y_train = _safe_split(estimator, X, y, train_subset) X_partial_train, y_partial_train = _safe_split(estimator, X, y, partial_train) X_test, y_test = _safe_split(estimator, X, y, test, train_subset) if y_partial_train is None: estimator.partial_fit(X_partial_train, classes=classes) else: estimator.partial_fit(X_partial_train, y_partial_train, classes=classes) train_scores.append(_score(estimator, X_train, y_train, scorer)) test_scores.append(_score(estimator, X_test, y_test, scorer)) return np.array((train_scores, test_scores)).T def validation_curve(estimator, X, y, param_name, param_range, cv=None, scoring=None, n_jobs=1, pre_dispatch="all", verbose=0): """Validation curve. Determine training and test scores for varying parameter values. Compute scores for an estimator with different values of a specified parameter. This is similar to grid search with one parameter. However, this will also compute training scores and is merely a utility for plotting the results. Read more in the :ref:`User Guide <validation_curve>`. Parameters ---------- estimator : object type that implements the "fit" and "predict" methods An object of that type which is cloned for each validation. X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape (n_samples) or (n_samples, n_features), optional Target relative to X for classification or regression; None for unsupervised learning. param_name : string Name of the parameter that will be varied. param_range : array-like, shape (n_values,) The values of the parameter that will be evaluated. cv : int, cross-validation generator or an iterable, optional Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the default 3-fold cross-validation, - integer, to specify the number of folds. - An object to be used as a cross-validation generator. - An iterable yielding train/test splits. For integer/None inputs, if ``y`` is binary or multiclass, :class:`StratifiedKFold` used. If the estimator is a classifier or if ``y`` is neither binary nor multiclass, :class:`KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validation strategies that can be used here. scoring : string, callable or None, optional, default: None A string (see model evaluation documentation) or a scorer callable object / function with signature ``scorer(estimator, X, y)``. n_jobs : integer, optional Number of jobs to run in parallel (default 1). pre_dispatch : integer or string, optional Number of predispatched jobs for parallel execution (default is all). The option can reduce the allocated memory. The string can be an expression like '2*n_jobs'. verbose : integer, optional Controls the verbosity: the higher, the more messages. Returns ------- train_scores : array, shape (n_ticks, n_cv_folds) Scores on training sets. test_scores : array, shape (n_ticks, n_cv_folds) Scores on test set. Notes ----- See :ref:`examples/model_selection/plot_validation_curve.py <example_model_selection_plot_validation_curve.py>` """ X, y = indexable(X, y) cv = check_cv(cv, X, y, classifier=is_classifier(estimator)) scorer = check_scoring(estimator, scoring=scoring) parallel = Parallel(n_jobs=n_jobs, pre_dispatch=pre_dispatch, verbose=verbose) out = parallel(delayed(_fit_and_score)( estimator, X, y, scorer, train, test, verbose, parameters={param_name: v}, fit_params=None, return_train_score=True) for train, test in cv for v in param_range) out = np.asarray(out)[:, :2] n_params = len(param_range) n_cv_folds = out.shape[0] // n_params out = out.reshape(n_cv_folds, n_params, 2).transpose((2, 1, 0)) return out[0], out[1]
# Copyright The PyTorch Lightning team. # # 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 pickle from argparse import ArgumentParser from dataclasses import dataclass from typing import Any, Dict from unittest import mock from unittest.mock import call, PropertyMock import pytest import torch from pytorch_lightning import LightningDataModule, Trainer from pytorch_lightning.callbacks import ModelCheckpoint from pytorch_lightning.utilities import AttributeDict from pytorch_lightning.utilities.exceptions import MisconfigurationException from pytorch_lightning.utilities.model_helpers import is_overridden from tests.helpers import BoringDataModule, BoringModel from tests.helpers.datamodules import ClassifDataModule from tests.helpers.runif import RunIf from tests.helpers.simple_models import ClassificationModel from tests.helpers.utils import reset_seed @mock.patch("pytorch_lightning.trainer.trainer.Trainer.node_rank", new_callable=PropertyMock) @mock.patch("pytorch_lightning.trainer.trainer.Trainer.local_rank", new_callable=PropertyMock) def test_can_prepare_data(local_rank, node_rank): dm = BoringDataModule() trainer = Trainer() trainer.datamodule = dm # 1 no DM # prepare_data_per_node = True # local rank = 0 (True) dm.random_full = None dm._has_prepared_data = False local_rank.return_value = 0 assert trainer.local_rank == 0 trainer.data_connector.prepare_data() assert dm.random_full is not None # local rank = 1 (False) dm.random_full = None dm._has_prepared_data = False local_rank.return_value = 1 assert trainer.local_rank == 1 trainer.data_connector.prepare_data() assert dm.random_full is None # prepare_data_per_node = False (prepare across all nodes) # global rank = 0 (True) dm.random_full = None dm._has_prepared_data = False dm.prepare_data_per_node = False node_rank.return_value = 0 local_rank.return_value = 0 trainer.data_connector.prepare_data() assert dm.random_full is not None # global rank = 1 (False) dm.random_full = None dm._has_prepared_data = False node_rank.return_value = 1 local_rank.return_value = 0 trainer.data_connector.prepare_data() assert dm.random_full is None node_rank.return_value = 0 local_rank.return_value = 1 trainer.data_connector.prepare_data() assert dm.random_full is None # 2 dm # prepar per node = True # local rank = 0 (True) dm.prepare_data_per_node = True local_rank.return_value = 0 with mock.patch.object(trainer.datamodule, "prepare_data") as dm_mock: # is_overridden prepare data = True # has been called # False dm._has_prepared_data = True trainer.data_connector.prepare_data() dm_mock.assert_not_called() # has not been called # True dm._has_prepared_data = False trainer.data_connector.prepare_data() dm_mock.assert_called_once() def test_hooks_no_recursion_error(): # hooks were appended in cascade every tine a new data module was instantiated leading to a recursion error. # See https://github.com/PyTorchLightning/pytorch-lightning/issues/3652 class DummyDM(LightningDataModule): def setup(self, *args, **kwargs): pass def prepare_data(self, *args, **kwargs): pass for i in range(1005): dm = DummyDM() dm.setup() dm.prepare_data() def test_helper_boringdatamodule(): dm = BoringDataModule() dm.prepare_data() dm.setup() def test_helper_boringdatamodule_with_verbose_setup(): dm = BoringDataModule() dm.prepare_data() dm.setup("fit") dm.setup("test") def test_data_hooks_called(): dm = BoringDataModule() assert not dm.has_prepared_data assert not dm.has_setup_fit assert not dm.has_setup_test assert not dm.has_setup_validate assert not dm.has_setup_predict assert not dm.has_teardown_fit assert not dm.has_teardown_test assert not dm.has_teardown_validate assert not dm.has_teardown_predict dm.prepare_data() assert dm.has_prepared_data assert not dm.has_setup_fit assert not dm.has_setup_test assert not dm.has_setup_validate assert not dm.has_setup_predict assert not dm.has_teardown_fit assert not dm.has_teardown_test assert not dm.has_teardown_validate assert not dm.has_teardown_predict dm.setup() assert dm.has_prepared_data assert dm.has_setup_fit assert dm.has_setup_test assert dm.has_setup_validate assert not dm.has_setup_predict assert not dm.has_teardown_fit assert not dm.has_teardown_test assert not dm.has_teardown_validate assert not dm.has_teardown_predict dm.teardown() assert dm.has_prepared_data assert dm.has_setup_fit assert dm.has_setup_test assert dm.has_setup_validate assert not dm.has_setup_predict assert dm.has_teardown_fit assert dm.has_teardown_test assert dm.has_teardown_validate assert not dm.has_teardown_predict @pytest.mark.parametrize("use_kwarg", (False, True)) def test_data_hooks_called_verbose(use_kwarg): dm = BoringDataModule() dm.prepare_data() assert not dm.has_setup_fit assert not dm.has_setup_test assert not dm.has_setup_validate assert not dm.has_setup_predict assert not dm.has_teardown_fit assert not dm.has_teardown_test assert not dm.has_teardown_validate assert not dm.has_teardown_predict dm.setup(stage="fit") if use_kwarg else dm.setup("fit") assert dm.has_setup_fit assert not dm.has_setup_validate assert not dm.has_setup_test assert not dm.has_setup_predict dm.setup(stage="validate") if use_kwarg else dm.setup("validate") assert dm.has_setup_fit assert dm.has_setup_validate assert not dm.has_setup_test assert not dm.has_setup_predict dm.setup(stage="test") if use_kwarg else dm.setup("test") assert dm.has_setup_fit assert dm.has_setup_validate assert dm.has_setup_test assert not dm.has_setup_predict dm.setup(stage="predict") if use_kwarg else dm.setup("predict") assert dm.has_setup_fit assert dm.has_setup_validate assert dm.has_setup_test assert dm.has_setup_predict dm.teardown(stage="fit") if use_kwarg else dm.teardown("fit") assert dm.has_teardown_fit assert not dm.has_teardown_validate assert not dm.has_teardown_test assert not dm.has_teardown_predict dm.teardown(stage="validate") if use_kwarg else dm.teardown("validate") assert dm.has_teardown_fit assert dm.has_teardown_validate assert not dm.has_teardown_test assert not dm.has_teardown_predict dm.teardown(stage="test") if use_kwarg else dm.teardown("test") assert dm.has_teardown_fit assert dm.has_teardown_validate assert dm.has_teardown_test assert not dm.has_teardown_predict dm.teardown(stage="predict") if use_kwarg else dm.teardown("predict") assert dm.has_teardown_fit assert dm.has_teardown_validate assert dm.has_teardown_test assert dm.has_teardown_predict def test_dm_add_argparse_args(tmpdir): parser = ArgumentParser() parser = BoringDataModule.add_argparse_args(parser) args = parser.parse_args(["--data_dir", str(tmpdir)]) assert args.data_dir == str(tmpdir) def test_dm_init_from_argparse_args(tmpdir): parser = ArgumentParser() parser = BoringDataModule.add_argparse_args(parser) args = parser.parse_args(["--data_dir", str(tmpdir)]) dm = BoringDataModule.from_argparse_args(args) dm.prepare_data() dm.setup() assert dm.data_dir == args.data_dir == str(tmpdir) def test_dm_pickle_after_init(): dm = BoringDataModule() pickle.dumps(dm) def test_train_loop_only(tmpdir): reset_seed() dm = ClassifDataModule() model = ClassificationModel() model.validation_step = None model.validation_step_end = None model.validation_epoch_end = None model.test_step = None model.test_step_end = None model.test_epoch_end = None trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, weights_summary=None) # fit model trainer.fit(model, datamodule=dm) assert trainer.state.finished, f"Training failed with {trainer.state}" assert trainer.callback_metrics["train_loss"] < 1.0 def test_train_val_loop_only(tmpdir): reset_seed() dm = ClassifDataModule() model = ClassificationModel() model.validation_step = None model.validation_step_end = None model.validation_epoch_end = None trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, weights_summary=None) # fit model trainer.fit(model, datamodule=dm) assert trainer.state.finished, f"Training failed with {trainer.state}" assert trainer.callback_metrics["train_loss"] < 1.0 def test_dm_checkpoint_save(tmpdir): class CustomBoringModel(BoringModel): def validation_step(self, batch, batch_idx): out = super().validation_step(batch, batch_idx) self.log("early_stop_on", out["x"]) return out class CustomBoringDataModule(BoringDataModule): def on_save_checkpoint(self, checkpoint: Dict[str, Any]) -> None: checkpoint[self.__class__.__name__] = self.__class__.__name__ def on_load_checkpoint(self, checkpoint: Dict[str, Any]) -> None: self.checkpoint_state = checkpoint.get(self.__class__.__name__) reset_seed() dm = CustomBoringDataModule() model = CustomBoringModel() trainer = Trainer( default_root_dir=tmpdir, max_epochs=1, limit_train_batches=2, limit_val_batches=1, weights_summary=None, callbacks=[ModelCheckpoint(dirpath=tmpdir, monitor="early_stop_on")], ) # fit model trainer.fit(model, dm) assert trainer.state.finished, f"Training failed with {trainer.state}" checkpoint_path = list(trainer.checkpoint_callback.best_k_models.keys())[0] checkpoint = torch.load(checkpoint_path) assert dm.__class__.__name__ in checkpoint assert checkpoint[dm.__class__.__name__] == dm.__class__.__name__ def test_full_loop(tmpdir): reset_seed() dm = ClassifDataModule() model = ClassificationModel() trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, weights_summary=None, deterministic=True) # fit model trainer.fit(model, dm) assert trainer.state.finished, f"Training failed with {trainer.state}" assert dm.trainer is not None # validate result = trainer.validate(model, dm) assert dm.trainer is not None assert result[0]["val_acc"] > 0.7 # test result = trainer.test(model, dm) assert dm.trainer is not None assert result[0]["test_acc"] > 0.6 @RunIf(min_gpus=1) @mock.patch("pytorch_lightning.accelerators.accelerator.Accelerator.lightning_module", new_callable=PropertyMock) def test_dm_apply_batch_transfer_handler(get_module_mock): expected_device = torch.device("cuda", 0) class CustomBatch: def __init__(self, data): self.samples = data[0] self.targets = data[1] class CurrentTestDM(LightningDataModule): rank = 0 transfer_batch_to_device_hook_rank = None on_before_batch_transfer_hook_rank = None on_after_batch_transfer_hook_rank = None def on_before_batch_transfer(self, batch, dataloader_idx): assert dataloader_idx == 0 self.on_before_batch_transfer_hook_rank = self.rank self.rank += 1 batch.samples += 1 return batch def on_after_batch_transfer(self, batch, dataloader_idx): assert dataloader_idx == 0 assert batch.samples.device == batch.targets.device == expected_device self.on_after_batch_transfer_hook_rank = self.rank self.rank += 1 batch.targets *= 2 return batch def transfer_batch_to_device(self, batch, device, dataloader_idx): assert dataloader_idx == 0 self.transfer_batch_to_device_hook_rank = self.rank self.rank += 1 batch.samples = batch.samples.to(device) batch.targets = batch.targets.to(device) return batch dm = CurrentTestDM() model = BoringModel() batch = CustomBatch((torch.zeros(5, 32), torch.ones(5, 1, dtype=torch.long))) trainer = Trainer(gpus=1) # running .fit() would require us to implement custom data loaders, we mock the model reference instead get_module_mock.return_value = model if is_overridden("transfer_batch_to_device", dm): model.transfer_batch_to_device = dm.transfer_batch_to_device model.on_before_batch_transfer = dm.on_before_batch_transfer model.transfer_batch_to_device = dm.transfer_batch_to_device model.on_after_batch_transfer = dm.on_after_batch_transfer batch_gpu = trainer.accelerator.batch_to_device(batch, expected_device) assert dm.on_before_batch_transfer_hook_rank == 0 assert dm.transfer_batch_to_device_hook_rank == 1 assert dm.on_after_batch_transfer_hook_rank == 2 assert batch_gpu.samples.device == batch_gpu.targets.device == expected_device assert torch.allclose(batch_gpu.samples.cpu(), torch.ones(5, 32)) assert torch.allclose(batch_gpu.targets.cpu(), torch.ones(5, 1, dtype=torch.long) * 2) def test_dm_reload_dataloaders_every_n_epochs(tmpdir): """ Test datamodule, where trainer argument reload_dataloaders_every_n_epochs is set to a non negative integer """ class CustomBoringDataModule(BoringDataModule): def __init__(self): super().__init__() self._epochs_called_for = [] def train_dataloader(self): assert self.trainer.current_epoch not in self._epochs_called_for self._epochs_called_for.append(self.trainer.current_epoch) return super().train_dataloader() dm = CustomBoringDataModule() model = BoringModel() model.validation_step = None model.validation_step_end = None model.validation_epoch_end = None model.test_step = None model.test_step_end = None model.test_epoch_end = None trainer = Trainer(default_root_dir=tmpdir, max_epochs=3, limit_train_batches=2, reload_dataloaders_every_n_epochs=2) trainer.fit(model, dm) class DummyDS(torch.utils.data.Dataset): def __getitem__(self, index): return 1 def __len__(self): return 100 class DummyIDS(torch.utils.data.IterableDataset): def __iter__(self): yield 1 @pytest.mark.parametrize("iterable", (False, True)) def test_dm_init_from_datasets_dataloaders(iterable): ds = DummyIDS if iterable else DummyDS train_ds = ds() dm = LightningDataModule.from_datasets(train_ds, batch_size=4, num_workers=0) with mock.patch("pytorch_lightning.core.datamodule.DataLoader") as dl_mock: dm.train_dataloader() dl_mock.assert_called_once_with(train_ds, batch_size=4, shuffle=not iterable, num_workers=0, pin_memory=True) with pytest.raises(NotImplementedError): _ = dm.val_dataloader() with pytest.raises(NotImplementedError): _ = dm.test_dataloader() train_ds_sequence = [ds(), ds()] dm = LightningDataModule.from_datasets(train_ds_sequence, batch_size=4, num_workers=0) with mock.patch("pytorch_lightning.core.datamodule.DataLoader") as dl_mock: dm.train_dataloader() dl_mock.assert_has_calls( [ call(train_ds_sequence[0], batch_size=4, shuffle=not iterable, num_workers=0, pin_memory=True), call(train_ds_sequence[1], batch_size=4, shuffle=not iterable, num_workers=0, pin_memory=True), ] ) with pytest.raises(NotImplementedError): _ = dm.val_dataloader() with pytest.raises(NotImplementedError): _ = dm.test_dataloader() valid_ds = ds() test_ds = ds() dm = LightningDataModule.from_datasets(val_dataset=valid_ds, test_dataset=test_ds, batch_size=2, num_workers=0) with mock.patch("pytorch_lightning.core.datamodule.DataLoader") as dl_mock: dm.val_dataloader() dl_mock.assert_called_with(valid_ds, batch_size=2, shuffle=False, num_workers=0, pin_memory=True) dm.test_dataloader() dl_mock.assert_called_with(test_ds, batch_size=2, shuffle=False, num_workers=0, pin_memory=True) with pytest.raises(NotImplementedError): _ = dm.train_dataloader() valid_dss = [ds(), ds()] test_dss = [ds(), ds()] dm = LightningDataModule.from_datasets(train_ds, valid_dss, test_dss, batch_size=4, num_workers=0) with mock.patch("pytorch_lightning.core.datamodule.DataLoader") as dl_mock: dm.val_dataloader() dm.test_dataloader() dl_mock.assert_has_calls( [ call(valid_dss[0], batch_size=4, shuffle=False, num_workers=0, pin_memory=True), call(valid_dss[1], batch_size=4, shuffle=False, num_workers=0, pin_memory=True), call(test_dss[0], batch_size=4, shuffle=False, num_workers=0, pin_memory=True), call(test_dss[1], batch_size=4, shuffle=False, num_workers=0, pin_memory=True), ] ) class DataModuleWithHparams(LightningDataModule): def __init__(self, arg0, arg1, kwarg0=None): super().__init__() self.save_hyperparameters() def test_simple_hyperparameters_saving(): data = DataModuleWithHparams(10, "foo", kwarg0="bar") assert data.hparams == AttributeDict({"arg0": 10, "arg1": "foo", "kwarg0": "bar"}) def test_define_as_dataclass(): # makes sure that no functionality is broken and the user can still manually make # super().__init__ call with parameters # also tests all the dataclass features that can be enabled without breaking anything @dataclass(init=True, repr=True, eq=True, order=True, unsafe_hash=True, frozen=False) class BoringDataModule1(LightningDataModule): batch_size: int dims: int = 2 def __post_init__(self): super().__init__(dims=self.dims) # asserts for the different dunder methods added by dataclass, when __init__ is implemented, i.e. # __repr__, __eq__, __lt__, __le__, etc. assert BoringDataModule1(batch_size=64).dims == 2 assert BoringDataModule1(batch_size=32) assert hasattr(BoringDataModule1, "__repr__") assert BoringDataModule1(batch_size=32) == BoringDataModule1(batch_size=32) # asserts inherent calling of super().__init__ in case user doesn't make the call @dataclass class BoringDataModule2(LightningDataModule): batch_size: int # asserts for the different dunder methods added by dataclass, when super class is inherently initialized, i.e. # __init__, __repr__, __eq__, __lt__, __le__, etc. assert BoringDataModule2(batch_size=32) assert hasattr(BoringDataModule2, "__repr__") assert BoringDataModule2(batch_size=32).prepare_data() is None assert BoringDataModule2(batch_size=32) == BoringDataModule2(batch_size=32) # checking for all the different multilevel inhertiance scenarios, for init call on LightningDataModule @dataclass class BoringModuleBase1(LightningDataModule): num_features: int class BoringModuleBase2(LightningDataModule): def __init__(self, num_features: int): self.num_features = num_features @dataclass class BoringModuleDerived1(BoringModuleBase1): ... class BoringModuleDerived2(BoringModuleBase1): def __init__(self): ... @dataclass class BoringModuleDerived3(BoringModuleBase2): ... class BoringModuleDerived4(BoringModuleBase2): def __init__(self): ... assert hasattr(BoringModuleDerived1(num_features=2), "_has_prepared_data") assert hasattr(BoringModuleDerived2(), "_has_prepared_data") assert hasattr(BoringModuleDerived3(), "_has_prepared_data") assert hasattr(BoringModuleDerived4(), "_has_prepared_data") def test_inconsistent_prepare_data_per_node(tmpdir): with pytest.raises(MisconfigurationException, match="Inconsistent settings found for `prepare_data_per_node`."): model = BoringModel() dm = BoringDataModule() trainer = Trainer(prepare_data_per_node=False) trainer.model = model trainer.datamodule = dm trainer.data_connector.prepare_data()
from toee import * from Co8 import * OBJ_SPELL_STENCH = 6400 STENCH_DURATION = 100 EFFECT_VAR = obj_f_item_pad_i_1 COUNT_VAR = obj_f_item_pad_i_2 STATE_VAR = obj_f_critter_pad_i_5 STATE_UNPROCESSED = 0 STATE_UNAFFECTED = 1 STATE_NOTINSTENCH = 2 STATE_NAUSEA = 3 STATE_NAUSEA_HANGOVER = 4 STATE_NAUSEA_EXPIRED = 5 # Unused. (I felt that it was only fair to get further saving throws after nausea expires) STATE_SICKNESS = 6 STATE_NOPROCESS = 7 STATE_NEUTRALISED = 8 CID = 0 COUNTER = 0 BASECASTERID = 1 casterIdNext = BASECASTERID # Main stench processing routine. def processStench(caster, spell_id): # Get caster ID, initialising if necessary. casterId = getObjVarNibble(caster, STATE_VAR, CID) if (casterId == 0): global casterIdNext casterId = casterIdNext casterIdNext = casterIdNext + 1 if (casterIdNext > 7): casterIdNext = BASECASTERID setObjVarNibble(caster, STATE_VAR, CID, casterId) # While caster is alive, concious and not destroyed or off. #print "checking caster... flags= ", caster.object_flags_get() & 0xff, " anded=", (caster.object_flags_get() & (OF_DESTROYED | OF_OFF)) if (caster.stat_level_get(stat_hp_current) > -10 and (caster.object_flags_get() & (OF_DESTROYED | OF_OFF)) == 0): print "Starting stench processing for ", caster, " id=", casterId, " spell_id=", spell_id for critter in game.obj_list_vicinity(caster.location, OLC_CRITTERS): if (critter.stat_level_get(stat_hp_current) <= -10): setObjVarNibble(critter, STATE_VAR, casterId, STATE_NOPROCESS) # Get critter status and process appropriately. status = getObjVarNibble(critter, STATE_VAR, casterId) if (status == STATE_UNPROCESSED): # Unprocessed - process critter init, and assign state. if (critter.is_category_subtype(mc_subtype_demon) or critter.is_category_type(mc_type_elemental) or critter.is_category_type(mc_type_undead) or critter.stat_level_get(stat_level_monk) > 10 or critter.stat_level_get(stat_level_druid) > 8): # Unaffected critters. (demons, elementals, undead, classes immune to poison) print critter, " unaffected" status = STATE_UNAFFECTED elif has_necklace(critter): print critter, " unaffected" status = STATE_UNAFFECTED elif (inStenchArea(caster, critter)): # In stench area - attempt save, apply the stench and take ownership. status = attemptSave(caster, spell_id, critter, status) applyStenchEffect(casterId, spell_id, critter, status) else: # Not yet in stench area. print critter, " not yet in stench area" status = STATE_NOTINSTENCH elif (status == STATE_NOTINSTENCH): # Check cured count. curedCount = getObjVarNibble(critter, STATE_VAR, COUNTER) if (curedCount > 0): print critter, " has been cured, skipping round" setObjVarNibble(critter, STATE_VAR, COUNTER, curedCount - 1) # Check if now in stink area. elif (inStenchArea(caster, critter)): # In stink area - apply the stench effect. print critter, " now in stench area, attempting save" status = attemptSave(caster, spell_id, critter, status) applyStenchEffect(casterId, spell_id, critter, status) elif (status == STATE_SICKNESS): # Check if now out of stink area. if (not inStenchArea(caster, critter)): print critter, " now out of stench area, removing sickness" status = STATE_NOPROCESS removeStenchEffect(casterId, spell_id, critter, status, false) elif (status == STATE_NAUSEA): # Check if now out of stink area. if (not inStenchArea(caster, critter)): status = STATE_NAUSEA_HANGOVER hangoverCount = game.random_range(0, 3) stench_obj = getStenchObj(critter) if (stench_obj != OBJ_HANDLE_NULL): print critter, " now out of stench area, changing to nausea hangover, count= ", hangoverCount setObjVarNibble(stench_obj, EFFECT_VAR, casterId, status) setObjVarNibble(stench_obj, COUNT_VAR, casterId, hangoverCount) else: print "Error: Can't find spell object for nausea." status = STATE_NOTINSTENCH # In case of error. elif (status == STATE_NAUSEA_HANGOVER): stench_obj = getStenchObj(critter) if (stench_obj != OBJ_HANDLE_NULL): # Check if now back in stink area. if (inStenchArea(caster, critter)): print critter, " now back in stench area, changing back to nausea" status = STATE_NAUSEA setObjVarNibble(stench_obj, EFFECT_VAR, casterId, status) else: # Maintain hangover. hangoverCount = getObjVarNibble(stench_obj, COUNT_VAR, casterId) print critter, " has nausea hangover, count= ", hangoverCount if (hangoverCount < 1): status = STATE_NOTINSTENCH removeStenchEffect(casterId, spell_id, critter, status, true) else: setObjVarNibble(stench_obj, COUNT_VAR, casterId, hangoverCount - 1) else: print "Error: Can't find spell object for hangover." status = STATE_NOTINSTENCH # In case of error. else: continue # Store critter status. setObjVarNibble(critter, STATE_VAR, casterId, status) # Setup processing for next round. game.timevent_add(processStench, (caster, spell_id), 500) else: print "Caster died or expired, ending the stench." endStench(caster, spell_id) return def inStenchArea(caster, critter): return (critter.distance_to(caster) < 10) def attemptSave(caster, spell_id, critter, status): # In stink area - attempt saving throw. if (critter.saving_throw_spell(24, D20_Save_Fortitude, D20CO8_F_POISON, caster, spell_id)): # Passed saving throw, apply sickness. status = STATE_SICKNESS print critter, " is in stench, passed saving throw - applying sickness" critter.float_mesfile_line( 'mes\\spell.mes', 30001 ) else: # Failed saving throw - apply nausea. status = STATE_NAUSEA print critter, " is in stench, failed saving throw - applying nausea" critter.float_mesfile_line( 'mes\\spell.mes', 30002 ) return status # Give the critter an effect object with the appropriate effect. def applyStenchEffect(casterId, spell_id, critter, status): stench_obj = getStenchObj(critter) if (stench_obj != OBJ_HANDLE_NULL): if (status == STATE_NAUSEA): # Check current stench effect. effectOwnerId = getObjVarNibble(stench_obj, EFFECT_VAR, CID) effectStatus = getObjVarNibble(stench_obj, EFFECT_VAR, effectOwnerId) if (effectStatus == STATE_SICKNESS): # Take ownership of effect since Nausea trumps Sickness. print "caster ", casterId, " taking ownership of effect from caster ", effectOwnerId, " on ", critter effectVar = getObjVarDWord(stench_obj, EFFECT_VAR) stench_obj.destroy() stench_obj = createStenchObject(spell_id, critter, status) setObjVarDWord(stench_obj, EFFECT_VAR, effectVar) else: stench_obj = createStenchObject(spell_id, critter, status) # Set the status & id into the effect var. setObjVarNibble(stench_obj, EFFECT_VAR, CID, casterId) setObjVarNibble(stench_obj, EFFECT_VAR, casterId, status) return def removeStenchEffect(casterId, spell_id, critter, status, unNullify): stench_obj = getStenchObj(critter) if (stench_obj != OBJ_HANDLE_NULL): print "removing effect ", stench_obj, " for ", critter, " by caster ", casterId setObjVarNibble(stench_obj, EFFECT_VAR, casterId, status) # Check current stench effect. effectOwnerId = getObjVarNibble(stench_obj, EFFECT_VAR, CID) if (casterId == effectOwnerId): # Pass ownership of effect to another stench. for otherId in xrange(BASECASTERID, 7): s = getObjVarNibble(stench_obj, EFFECT_VAR, otherId) if (s in (STATE_NAUSEA, STATE_NAUSEA_HANGOVER)): break # Nausea trumps Sickness. effectVar = getObjVarDWord(stench_obj, EFFECT_VAR) stench_obj.destroy() if (s in (STATE_NAUSEA, STATE_NAUSEA_HANGOVER, STATE_SICKNESS)): print "caster ", otherId, " taking ownership of effect from caster ", casterId, " on ", critter stench_obj = createStenchObject(spell_id, critter, s) setObjVarDWord(stench_obj, EFFECT_VAR, effectVar) setObjVarNibble(stench_obj, EFFECT_VAR, CID, otherId) if (s not in (STATE_NAUSEA, STATE_NAUSEA_HANGOVER) and unNullify): reenableWeapons(critter) else: reenableWeapons(critter) return def createStenchObject(spell_id, critter, status): stench_obj = game.obj_create(OBJ_SPELL_STENCH, critter.location) stench_obj.item_flag_set(OIF_NO_DROP) stench_obj.item_flag_set(OIF_NO_LOOT) set_spell_flag(stench_obj, OSF_IS_HEZROU_STENCH) if (status == STATE_SICKNESS): print "status: ", status, " applying sickness effect to ", stench_obj, " for ", critter stench_obj.item_condition_add_with_args('sp-Unholy Blight', spell_id, STENCH_DURATION, 0) # Doesn't penalise saves - does flag char info. stench_obj.item_condition_add_with_args('Saving Throw Resistance Bonus', 0, -2) stench_obj.item_condition_add_with_args('Saving Throw Resistance Bonus', 1, -2) stench_obj.item_condition_add_with_args('Saving Throw Resistance Bonus', 2, -2) elif (status == STATE_NAUSEA): print "status: ", status, " applying nausea effect to ", stench_obj, " for ", critter # Reduce weapon dmg since not supposed to be able to attack when nauseated. nullifyWeapons(critter) # Apply simulated nausea effects to stench obj. strength = critter.stat_level_get(stat_strength) # No strength bonus. stench_obj.item_condition_add_with_args('Attribute Enhancement Bonus', 0, 11 - strength) stench_obj.item_condition_add_with_args('sp-Chaos Hammer', spell_id, STENCH_DURATION, 0) # Only get move action. (+2 AC, -2 attack & damage rolls, +2 saves [shoddy implementation]) stench_obj.item_condition_add_with_args('sp-Feeblemind', 0,0,0) # No casting. (-4 to saves for arcane spellcasters) if (critter.stat_level_get(stat_level_sorcerer) > 0 or critter.stat_level_get(stat_level_bard) > 0 or critter.stat_level_get(stat_level_wizard) > 0): stench_obj.item_condition_add_with_args('Saving Throw Resistance Bonus', 0, 2) stench_obj.item_condition_add_with_args('Saving Throw Resistance Bonus', 1, 2) stench_obj.item_condition_add_with_args('Saving Throw Resistance Bonus', 2, 2) # Counteract feeblemind penalties for arcane casters. else: stench_obj.item_condition_add_with_args('Saving Throw Resistance Bonus', 0, -2) stench_obj.item_condition_add_with_args('Saving Throw Resistance Bonus', 1, -2) stench_obj.item_condition_add_with_args('Saving Throw Resistance Bonus', 2, -2) # Counteract hammer bonuses. critter.item_get(stench_obj) game.particles("sp-Stinking Cloud Hit", critter) return stench_obj def getStenchObj(critter): it = 0 stench_obj = critter.item_find(OBJ_SPELL_STENCH) while (stench_obj != OBJ_HANDLE_NULL and not is_spell_flag_set(stench_obj, OSF_IS_HEZROU_STENCH) and it < 217): stench_obj = critter.inventory_item(it) it += 1 if (it >= 217): print 'Search for Stench Object a lot of times!' return stench_obj def neutraliseStench(critter, duration): print "Neutralising stench on: ", critter stench_obj = getStenchObj(critter) if (stench_obj != OBJ_HANDLE_NULL): stench_obj.destroy() reenableWeapons(critter) # Add to cured count and set all stench id's to neutralised. curedCount = getObjVarNibble(critter, STATE_VAR, COUNTER) setObjVarNibble(critter, STATE_VAR, COUNTER, curedCount + 1) for casterId in xrange(BASECASTERID, 7): setObjVarNibble(critter, STATE_VAR, casterId, STATE_NEUTRALISED) # Setup processing for un-neutralisation. game.timevent_add(unNeutraliseStench, (critter), 1000 * duration) return def unNeutraliseStench(critter): curedCount = getObjVarNibble(critter, STATE_VAR, COUNTER) print "Un-neutralising stench, curedCount=", curedCount setObjVarNibble(critter, STATE_VAR, COUNTER, curedCount - 1) if (curedCount <= 1): print "Un-neutralising stench on: ", critter for casterId in xrange(BASECASTERID, 7): setObjVarNibble(critter, STATE_VAR, casterId, STATE_UNPROCESSED) return def nullifyWeapons(critter): for num in xrange(4000, 5000): weapon = critter.item_find_by_proto(num) if (weapon != OBJ_HANDLE_NULL and not is_spell_flag_set(weapon, OSF_IS_HEZROU_STENCH)): print "Nullifying weapon ", weapon, " for ", critter set_spell_flag(weapon, OSF_IS_HEZROU_STENCH) weapon.obj_set_int(obj_f_weapon_pad_i_2, weapon.obj_get_int(obj_f_weapon_damage_dice)) weapon.obj_set_int(obj_f_weapon_damage_dice, 0) weapon.item_flag_set(OIF_NO_DROP) return def reenableWeapons(critter): for num in xrange(4000, 5000): weapon = critter.item_find_by_proto(num) if (weapon != OBJ_HANDLE_NULL and is_spell_flag_set(weapon, OSF_IS_HEZROU_STENCH)): print "Enabling weapon ", weapon, " for ", critter weapon.obj_set_int(obj_f_weapon_damage_dice, weapon.obj_get_int(obj_f_weapon_pad_i_2)) unset_spell_flag(weapon, OSF_IS_HEZROU_STENCH) weapon.item_flag_unset(OIF_NO_DROP) return def endStench(caster, spell_id): casterId = 1 if (caster != OBJ_HANDLE_NULL): casterId = getObjVarNibble(caster, STATE_VAR, CID) print "Cleaning up and ending stench for ", caster, " id=", casterId else: print 'Caster is null now, trying default' caster = game.leader # just to get a location for critter in game.obj_list_vicinity(caster.location, OLC_CRITTERS): if (getObjVarNibble(critter, STATE_VAR, casterId) != STATE_UNPROCESSED): removeStenchEffect(casterId, spell_id, critter, STATE_UNPROCESSED, true) if (getObjVarNibble(critter, STATE_VAR, casterId) != STATE_NEUTRALISED): setObjVarNibble(critter, STATE_VAR, casterId, STATE_UNPROCESSED) return def has_necklace(critter): full = critter.item_worn_at(1) if full != OBJ_HANDLE_NULL and full.name == 6107: return 1 return 0
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC 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. import hashlib from numbers import Number import os import zipfile try: from StringIO import StringIO as IOStream except ImportError: # 3+ from io import BytesIO as IOStream import base64 from .command import Command from selenium.common.exceptions import WebDriverException from selenium.common.exceptions import InvalidSelectorException from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys try: str = basestring except NameError: pass class WebElement(object): """Represents a DOM element. Generally, all interesting operations that interact with a document will be performed through this interface. All method calls will do a freshness check to ensure that the element reference is still valid. This essentially determines whether or not the element is still attached to the DOM. If this test fails, then an ``StaleElementReferenceException`` is thrown, and all future calls to this instance will fail.""" def __init__(self, parent, id_, w3c=False): self._parent = parent self._id = id_ self._w3c = w3c def __repr__(self): return '<{0.__module__}.{0.__name__} (session="{1}", element="{2}")>'.format( type(self), self._parent.session_id, self._id) @property def tag_name(self): """This element's ``tagName`` property.""" return self._execute(Command.GET_ELEMENT_TAG_NAME)['value'] @property def text(self): """The text of the element.""" return self._execute(Command.GET_ELEMENT_TEXT)['value'] def click(self): """Clicks the element.""" self._execute(Command.CLICK_ELEMENT) def submit(self): """Submits a form.""" self._execute(Command.SUBMIT_ELEMENT) def clear(self): """Clears the text if it's a text entry element.""" self._execute(Command.CLEAR_ELEMENT) def get_attribute(self, name): """Gets the given attribute or property of the element. This method will first try to return the value of a property with the given name. If a property with that name doesn't exist, it returns the value of the attribute with the same name. If there's no attribute with that name, ``None`` is returned. Values which are considered truthy, that is equals "true" or "false", are returned as booleans. All other non-``None`` values are returned as strings. For attributes or properties which do not exist, ``None`` is returned. :Args: - name - Name of the attribute/property to retrieve. Example:: # Check if the "active" CSS class is applied to an element. is_active = "active" in target_element.get_attribute("class") """ resp = self._execute(Command.GET_ELEMENT_ATTRIBUTE, {'name': name}) attributeValue = '' if resp['value'] is None: attributeValue = None else: attributeValue = resp['value'] if name != 'value' and attributeValue.lower() in ('true', 'false'): attributeValue = attributeValue.lower() return attributeValue def is_selected(self): """Returns whether the element is selected. Can be used to check if a checkbox or radio button is selected. """ return self._execute(Command.IS_ELEMENT_SELECTED)['value'] def is_enabled(self): """Returns whether the element is enabled.""" return self._execute(Command.IS_ELEMENT_ENABLED)['value'] def find_element_by_id(self, id_): """Finds element within this element's children by ID. :Args: - id_ - ID of child element to locate. """ return self.find_element(by=By.ID, value=id_) def find_elements_by_id(self, id_): """Finds a list of elements within this element's children by ID. :Args: - id_ - Id of child element to find. """ return self.find_elements(by=By.ID, value=id_) def find_element_by_name(self, name): """Finds element within this element's children by name. :Args: - name - name property of the element to find. """ return self.find_element(by=By.NAME, value=name) def find_elements_by_name(self, name): """Finds a list of elements within this element's children by name. :Args: - name - name property to search for. """ return self.find_elements(by=By.NAME, value=name) def find_element_by_link_text(self, link_text): """Finds element within this element's children by visible link text. :Args: - link_text - Link text string to search for. """ return self.find_element(by=By.LINK_TEXT, value=link_text) def find_elements_by_link_text(self, link_text): """Finds a list of elements within this element's children by visible link text. :Args: - link_text - Link text string to search for. """ return self.find_elements(by=By.LINK_TEXT, value=link_text) def find_element_by_partial_link_text(self, link_text): """Finds element within this element's children by partially visible link text. :Args: - link_text - Link text string to search for. """ return self.find_element(by=By.PARTIAL_LINK_TEXT, value=link_text) def find_elements_by_partial_link_text(self, link_text): """Finds a list of elements within this element's children by link text. :Args: - link_text - Link text string to search for. """ return self.find_elements(by=By.PARTIAL_LINK_TEXT, value=link_text) def find_element_by_tag_name(self, name): """Finds element within this element's children by tag name. :Args: - name - name of html tag (eg: h1, a, span) """ return self.find_element(by=By.TAG_NAME, value=name) def find_elements_by_tag_name(self, name): """Finds a list of elements within this element's children by tag name. :Args: - name - name of html tag (eg: h1, a, span) """ return self.find_elements(by=By.TAG_NAME, value=name) def find_element_by_xpath(self, xpath): """Finds element by xpath. :Args: xpath - xpath of element to locate. "//input[@class='myelement']" Note: The base path will be relative to this element's location. This will select the first link under this element. :: myelement.find_elements_by_xpath(".//a") However, this will select the first link on the page. :: myelement.find_elements_by_xpath("//a") """ return self.find_element(by=By.XPATH, value=xpath) def find_elements_by_xpath(self, xpath): """Finds elements within the element by xpath. :Args: - xpath - xpath locator string. Note: The base path will be relative to this element's location. This will select all links under this element. :: myelement.find_elements_by_xpath(".//a") However, this will select all links in the page itself. :: myelement.find_elements_by_xpath("//a") """ return self.find_elements(by=By.XPATH, value=xpath) def find_element_by_class_name(self, name): """Finds element within this element's children by class name. :Args: - name - class name to search for. """ return self.find_element(by=By.CLASS_NAME, value=name) def find_elements_by_class_name(self, name): """Finds a list of elements within this element's children by class name. :Args: - name - class name to search for. """ return self.find_elements(by=By.CLASS_NAME, value=name) def find_element_by_css_selector(self, css_selector): """Finds element within this element's children by CSS selector. :Args: - css_selector - CSS selctor string, ex: 'a.nav#home' """ return self.find_element(by=By.CSS_SELECTOR, value=css_selector) def find_elements_by_css_selector(self, css_selector): """Finds a list of elements within this element's children by CSS selector. :Args: - css_selector - CSS selctor string, ex: 'a.nav#home' """ return self.find_elements(by=By.CSS_SELECTOR, value=css_selector) def send_keys(self, *value): """Simulates typing into the element. :Args: - value - A string for typing, or setting form fields. For setting file inputs, this could be a local file path. Use this to send simple key events or to fill out form fields:: form_textfield = driver.find_element_by_name('username') form_textfield.send_keys("admin") This can also be used to set file inputs. :: file_input = driver.find_element_by_name('profilePic') file_input.send_keys("path/to/profilepic.gif") # Generally it's better to wrap the file path in one of the methods # in os.path to return the actual path to support cross OS testing. # file_input.send_keys(os.path.abspath("path/to/profilepic.gif")) """ # transfer file to another machine only if remote driver is used # the same behaviour as for java binding if self.parent._is_remote: local_file = self.parent.file_detector.is_local_file(*value) if local_file is not None: value = self._upload(local_file) typing = [] for val in value: if isinstance(val, Keys): typing.append(val) elif isinstance(val, Number): val = val.__str__() for i in range(len(val)): typing.append(val[i]) else: for i in range(len(val)): typing.append(val[i]) self._execute(Command.SEND_KEYS_TO_ELEMENT, {'value': typing}) # RenderedWebElement Items def is_displayed(self): """Whether the element is visible to a user.""" return self._execute(Command.IS_ELEMENT_DISPLAYED)['value'] @property def location_once_scrolled_into_view(self): """THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discover where on the screen an element is so that we can click it. This method should cause the element to be scrolled into view. Returns the top lefthand corner location on the screen, or ``None`` if the element is not visible. """ return self._execute(Command.GET_ELEMENT_LOCATION_ONCE_SCROLLED_INTO_VIEW)['value'] @property def size(self): """The size of the element.""" size = self._execute(Command.GET_ELEMENT_SIZE)['value'] new_size = {} new_size["height"] = size["height"] new_size["width"] = size["width"] return new_size def value_of_css_property(self, property_name): """The value of a CSS property.""" return self._execute(Command.GET_ELEMENT_VALUE_OF_CSS_PROPERTY, {'propertyName': property_name})['value'] @property def location(self): """The location of the element in the renderable canvas.""" old_loc = self._execute(Command.GET_ELEMENT_LOCATION)['value'] new_loc = {"x": old_loc['x'], "y": old_loc['y']} return new_loc @property def rect(self): """A dictionary with the size and location of the element.""" return self._execute(Command.GET_ELEMENT_RECT)['value'] @property def screenshot_as_base64(self): """ Gets the screenshot of the current element as a base64 encoded string. :Usage: img_b64 = element.screenshot_as_base64 """ return self._execute(Command.ELEMENT_SCREENSHOT)['value'] @property def screenshot_as_png(self): """ Gets the screenshot of the current element as a binary data. :Usage: element_png = element.screenshot_as_png """ return base64.b64decode(self.screenshot_as_base64.encode('ascii')) def screenshot(self, filename): """ Gets the screenshot of the current element. Returns False if there is any IOError, else returns True. Use full paths in your filename. :Args: - filename: The full path you wish to save your screenshot to. :Usage: element.screenshot('/Screenshots/foo.png') """ png = self.screenshot_as_png try: with open(filename, 'wb') as f: f.write(png) except IOError: return False finally: del png return True @property def parent(self): """Internal reference to the WebDriver instance this element was found from.""" return self._parent @property def id(self): """Internal ID used by selenium. This is mainly for internal use. Simple use cases such as checking if 2 webelements refer to the same element, can be done using ``==``:: if element1 == element2: print("These 2 are equal") """ return self._id def __eq__(self, element): return hasattr(element, 'id') and self._id == element.id def __ne__(self, element): return not self.__eq__(element) # Private Methods def _execute(self, command, params=None): """Executes a command against the underlying HTML element. Args: command: The name of the command to _execute as a string. params: A dictionary of named parameters to send with the command. Returns: The command's JSON response loaded into a dictionary object. """ if not params: params = {} params['id'] = self._id return self._parent.execute(command, params) def find_element(self, by=By.ID, value=None): if not By.is_valid(by) or not isinstance(value, str): raise InvalidSelectorException("Invalid locator values passed in") if self._w3c: if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SELECTOR value = '[name="%s"]' % value return self._execute(Command.FIND_CHILD_ELEMENT, {"using": by, "value": value})['value'] def find_elements(self, by=By.ID, value=None): if not By.is_valid(by) or not isinstance(value, str): raise InvalidSelectorException("Invalid locator values passed in") if self._w3c: if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SELECTOR value = '[name="%s"]' % value return self._execute(Command.FIND_CHILD_ELEMENTS, {"using": by, "value": value})['value'] def __hash__(self): return int(hashlib.md5(self._id.encode('utf-8')).hexdigest(), 16) def _upload(self, filename): fp = IOStream() zipped = zipfile.ZipFile(fp, 'w', zipfile.ZIP_DEFLATED) zipped.write(filename, os.path.split(filename)[1]) zipped.close() content = base64.encodestring(fp.getvalue()) if not isinstance(content, str): content = content.decode('utf-8') try: return self._execute(Command.UPLOAD_FILE, {'file': content})['value'] except WebDriverException as e: if "Unrecognized command: POST" in e.__str__(): return filename elif "Command not found: POST " in e.__str__(): return filename elif '{"status":405,"value":["GET","HEAD","DELETE"]}' in e.__str__(): return filename else: raise e
# # # Copyright (C) 2013 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Gluster storage class. This class is very similar to FileStorage, given that Gluster when mounted behaves essentially like a regular file system. Unlike RBD, there are no special provisions for block device abstractions (yet). """ import logging import os import socket from ganeti import utils from ganeti import errors from ganeti import netutils from ganeti import constants from ganeti import ssconf from ganeti.utils import io from ganeti.storage import base from ganeti.storage.filestorage import FileDeviceHelper class GlusterVolume(object): """This class represents a Gluster volume. Volumes are uniquely identified by: - their IP address - their port - the volume name itself Two GlusterVolume objects x, y with same IP address, port and volume name are considered equal. """ def __init__(self, server_addr, port, volume, _run_cmd=utils.RunCmd, _mount_point=None): """Creates a Gluster volume object. @type server_addr: str @param server_addr: The address to connect to @type port: int @param port: The port to connect to (Gluster standard is 24007) @type volume: str @param volume: The gluster volume to use for storage. """ self.server_addr = server_addr server_ip = netutils.Hostname.GetIP(self.server_addr) self._server_ip = server_ip port = netutils.ValidatePortNumber(port) self._port = port self._volume = volume if _mount_point: # tests self.mount_point = _mount_point else: self.mount_point = ssconf.SimpleStore().GetGlusterStorageDir() self._run_cmd = _run_cmd @property def server_ip(self): return self._server_ip @property def port(self): return self._port @property def volume(self): return self._volume def __eq__(self, other): return (self.server_ip, self.port, self.volume) == \ (other.server_ip, other.port, other.volume) def __repr__(self): return """GlusterVolume("{ip}", {port}, "{volume}")""" \ .format(ip=self.server_ip, port=self.port, volume=self.volume) def __hash__(self): return (self.server_ip, self.port, self.volume).__hash__() def _IsMounted(self): """Checks if we are mounted or not. @rtype: bool @return: True if this volume is mounted. """ if not os.path.exists(self.mount_point): return False return os.path.ismount(self.mount_point) def _GuessMountFailReasons(self): """Try and give reasons why the mount might've failed. @rtype: str @return: A semicolon-separated list of problems found with the current setup suitable for display to the user. """ reasons = [] # Does the mount point exist? if not os.path.exists(self.mount_point): reasons.append("%r: does not exist" % self.mount_point) # Okay, it exists, but is it a directory? elif not os.path.isdir(self.mount_point): reasons.append("%r: not a directory" % self.mount_point) # If, for some unfortunate reason, this folder exists before mounting: # # /var/run/ganeti/gluster/gv0/10.0.0.1:30000:gv0/ # '--------- cwd ------------' # # and you _are_ trying to mount the gluster volume gv0 on 10.0.0.1:30000, # then the mount.glusterfs command parser gets confused and this command: # # mount -t glusterfs 10.0.0.1:30000:gv0 /var/run/ganeti/gluster/gv0 # '-- remote end --' '------ mountpoint -------' # # gets parsed instead like this: # # mount -t glusterfs 10.0.0.1:30000:gv0 /var/run/ganeti/gluster/gv0 # '-- mountpoint --' '----- syntax error ------' # # and if there _is_ a gluster server running locally at the default remote # end, localhost:24007, then this is not a network error and therefore... no # usage message gets printed out. All you get is a Byson parser error in the # gluster log files about an unexpected token in line 1, "". (That's stdin.) # # Not that we rely on that output in any way whatsoever... parser_confusing = io.PathJoin(self.mount_point, self._GetFUSEMountString()) if os.path.exists(parser_confusing): reasons.append("%r: please delete, rename or move." % parser_confusing) # Let's try something else: can we connect to the server? sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.connect((self.server_ip, self.port)) sock.close() except socket.error as err: reasons.append("%s:%d: %s" % (self.server_ip, self.port, err.strerror)) reasons.append("try running 'gluster volume info %s' on %s to ensure" " it exists, it is started and it is using the tcp" " transport" % (self.volume, self.server_ip)) return "; ".join(reasons) def _GetFUSEMountString(self): """Return the string FUSE needs to mount this volume. @rtype: str """ return "-o server-port={port} {ip}:/{volume}" \ .format(port=self.port, ip=self.server_ip, volume=self.volume) def GetKVMMountString(self, path): """Return the string KVM needs to use this volume. @rtype: str """ ip = self.server_ip if netutils.IPAddress.GetAddressFamily(ip) == socket.AF_INET6: ip = "[%s]" % ip return "gluster://{ip}:{port}/{volume}/{path}" \ .format(ip=ip, port=self.port, volume=self.volume, path=path) def Mount(self): """Try and mount the volume. No-op if the volume is already mounted. @raises BlockDeviceError: if the mount was unsuccessful @rtype: context manager @return: A simple context manager that lets you use this volume for short lived operations like so:: with volume.mount(): # Do operations on volume # Volume is now unmounted """ class _GlusterVolumeContextManager(object): def __init__(self, volume): self.volume = volume def __enter__(self): # We're already mounted. return self def __exit__(self, *exception_information): self.volume.Unmount() return False # do not swallow exceptions. if self._IsMounted(): return _GlusterVolumeContextManager(self) command = ["mount", "-t", "glusterfs", self._GetFUSEMountString(), self.mount_point] io.Makedirs(self.mount_point) self._run_cmd(" ".join(command), # Why set cwd? Because it's an area we control. If, # for some unfortunate reason, this folder exists: # "/%s/" % _GetFUSEMountString() # ...then the gluster parser gets confused and treats # _GetFUSEMountString() as your mount point and # self.mount_point becomes a syntax error. cwd=self.mount_point) # mount.glusterfs exits with code 0 even after failure. # https://bugzilla.redhat.com/show_bug.cgi?id=1031973 if not self._IsMounted(): reasons = self._GuessMountFailReasons() if not reasons: reasons = "%r failed." % (" ".join(command)) base.ThrowError("%r: mount failure: %s", self.mount_point, reasons) return _GlusterVolumeContextManager(self) def Unmount(self): """Try and unmount the volume. Failures are logged but otherwise ignored. @raises BlockDeviceError: if the volume was not mounted to begin with. """ if not self._IsMounted(): base.ThrowError("%r: should be mounted but isn't.", self.mount_point) result = self._run_cmd(["umount", self.mount_point]) if result.failed: logging.warning("Failed to unmount %r from %r: %s", self, self.mount_point, result.fail_reason) class GlusterStorage(base.BlockDev): """File device using the Gluster backend. This class represents a file storage backend device stored on Gluster. Ganeti mounts and unmounts the Gluster devices automatically. The unique_id for the file device is a (file_driver, file_path) tuple. """ def __init__(self, unique_id, children, size, params, dyn_params, **kwargs): """Initalizes a file device backend. """ if children: base.ThrowError("Invalid setup for file device") try: self.driver, self.path = unique_id except ValueError: # wrong number of arguments raise ValueError("Invalid configuration data %s" % repr(unique_id)) server_addr = params[constants.GLUSTER_HOST] port = params[constants.GLUSTER_PORT] volume = params[constants.GLUSTER_VOLUME] self.volume = GlusterVolume(server_addr, port, volume) self.full_path = io.PathJoin(self.volume.mount_point, self.path) self.file = None super(GlusterStorage, self).__init__(unique_id, children, size, params, dyn_params, **kwargs) self.Attach() def Assemble(self): """Assemble the device. Checks whether the file device exists, raises BlockDeviceError otherwise. """ assert self.attached, "Gluster file assembled without being attached" self.file.Exists(assert_exists=True) def Shutdown(self): """Shutdown the device. """ self.file = None self.dev_path = None self.attached = False def Open(self, force=False, exclusive=True): """Make the device ready for I/O. This is a no-op for the file type. """ assert self.attached, "Gluster file opened without being attached" def Close(self): """Notifies that the device will no longer be used for I/O. This is a no-op for the file type. """ pass def Remove(self): """Remove the file backing the block device. @rtype: boolean @return: True if the removal was successful """ with self.volume.Mount(): self.file = FileDeviceHelper(self.full_path) if self.file.Remove(): self.file = None return True else: return False def Rename(self, new_id): """Renames the file. """ # TODO: implement rename for file-based storage base.ThrowError("Rename is not supported for Gluster storage") def Grow(self, amount, dryrun, backingstore, excl_stor): """Grow the file @param amount: the amount (in mebibytes) to grow with """ self.file.Grow(amount, dryrun, backingstore, excl_stor) def Attach(self): """Attach to an existing file. Check if this file already exists. @rtype: boolean @return: True if file exists """ try: self.volume.Mount() self.file = FileDeviceHelper(self.full_path) self.dev_path = self.full_path except Exception as err: self.volume.Unmount() raise err self.attached = self.file.Exists() return self.attached def GetActualSize(self): """Return the actual disk size. @note: the device needs to be active when this is called """ return self.file.Size() def GetUserspaceAccessUri(self, hypervisor): """Generate KVM userspace URIs to be used as `-drive file` settings. @see: L{BlockDev.GetUserspaceAccessUri} @see: https://github.com/qemu/qemu/commit/8d6d89cb63c57569864ecdeb84d3a1c2eb """ if hypervisor == constants.HT_KVM: return self.volume.GetKVMMountString(self.path) else: base.ThrowError("Hypervisor %s doesn't support Gluster userspace access" % hypervisor) @classmethod def Create(cls, unique_id, children, size, spindles, params, excl_stor, dyn_params, **kwargs): """Create a new file. @param size: the size of file in MiB @rtype: L{bdev.FileStorage} @return: an instance of FileStorage """ if excl_stor: raise errors.ProgrammerError("FileStorage device requested with" " exclusive_storage") if not isinstance(unique_id, (tuple, list)) or len(unique_id) != 2: raise ValueError("Invalid configuration data %s" % str(unique_id)) full_path = unique_id[1] server_addr = params[constants.GLUSTER_HOST] port = params[constants.GLUSTER_PORT] volume = params[constants.GLUSTER_VOLUME] volume_obj = GlusterVolume(server_addr, port, volume) full_path = io.PathJoin(volume_obj.mount_point, full_path) # Possible optimization: defer actual creation to first Attach, rather # than mounting and unmounting here, then remounting immediately after. with volume_obj.Mount(): FileDeviceHelper.CreateFile(full_path, size, create_folders=True) return GlusterStorage(unique_id, children, size, params, dyn_params, **kwargs)
#!/usr/bin/env python3 # Project : From geodynamic to Seismic observations in the Earth's inner core # Author : Marine Lasbleis """ Define classes and functions to play with positions and coordinates systems. """ from __future__ import division from __future__ import absolute_import import numpy as np import sys # .float_info import epsilon # to use assert on floating point equivalence def from_seismo_to_cartesian(r, theta, phi): """ Calculate the cartesian coordinates from spherical (w/ latitude) coordinates) input: r : radius (km) theta : latitude (degree) phi : longitude (degree) output: x, y, z """ theta = (90 - theta) * np.pi / 180. # colatitude in rad phi = phi * np.pi / 180. x = r * np.sin(theta) * np.cos(phi) y = r * np.sin(theta) * np.sin(phi) z = r * np.cos(theta) return x, y, z def from_cartesian_to_seismo(x, y, z): """ Calculate the spherical coordinates (w/ latitude) from cartesian coordinates) r, theta, phi = from_cartesian_to_seismo(x, y, z) input: x, y, z (same length) output: r : radius (km) theta : latitude (degree) phi : longitude (degree) (same length as the input) """ r = np.sqrt(x**2 + y**2 + z**2) theta = np.arccos(z / r) * 180. / np.pi # colatitude, in degree if (x, y) == (0, 0): phi = 0. else: phi = np.where(y >= 0., np.arccos(x / np.sqrt(x**2 + y**2)), 2. * np.pi - np.arccos(x / np.sqrt(x**2 + y**2))) phi = phi * 180. / np.pi return r, 90. - theta, phi def angular_distance_to_point(theta1, phi1, theta2, phi2): """ angular distance between the point (theta1, phi1) and the point (theta2, phi2) at the surface of the core. Args: theta1, theta2 : latitude (degree) phi1, phi2: longitude (degree) Return phi: angle between the two points (in degree) """ if np.array([theta1]).size == 1 and np.array( [theta2]).size == 1 and theta1 == theta2 and phi1 == phi2: return 0. theta1, phi1, theta2, phi2 = theta1 * np.pi / 180., phi1 * \ np.pi / 180., theta2 * np.pi / 180., phi2 * np.pi / 180. return np.arccos(np.sin(theta1) * np.sin(theta2) + np.cos(theta1) * np.cos(theta2) * np.cos(abs(phi1 - phi2))) * 180. / np.pi def straight_trajectory(Point1, Point2, N): """ Trajectory is a straight line between Point1 and Point2, with N points. Point1, Point2: Point() N: integer (number of points on the trajectory) Use the cartesian coordinates of both points. """ _Points = [] _vector = [Point2.x - Point1.x, Point2.y - Point1.y, Point2.z - Point1.z] _length = np.sqrt(_vector[0]**2 + _vector[1]**2 + _vector[2]**2) for dx in np.linspace(0, 1, N): _Points.append(CartesianPoint( Point1.x + _vector[0] * dx, Point1.y + _vector[1] * dx, Point1.z + _vector[2] * dx)) return _Points[1:-1], _length class Point(): """ Position of a point in the Earth. can be computed in cartesian coordinates or in "seismological" coordinates. Cartesian coordinates: x,y,z (z is the NS, y is the EW and axe x cross the 0 longitude) Seismological coordinates: r, theta, phi (theta is the latitude) """ def __init__(self): self.x, self.y, self.z, self.r, self.theta, self.phi = None, None, None, None, None, None def add_cartesian(self): assert(self.r is not None) assert(self.phi is not None) assert(self.theta is not None) self.x, self.y, self.z = from_seismo_to_cartesian( self.r, self.theta, self.phi) def add_seismo(self): assert(self.x is not None) assert(self.y is not None) assert(self.z is not None) self.r, self.theta, self.phi = from_cartesian_to_seismo( self.x, self.y, self.z) def dimensionless(self, lengthscale): self.r = self.r / lengthscale self.x, self.y, self.z = self.x / lengthscale, \ self.y / lengthscale,\ self.z / lengthscale def er(self): """ return the cartesian coordinates of \vec{e}_r. """ try: assert(self.r is not None) assert(self.phi is not None) assert(self.theta is not None) except (AttributeError, NameError, AssertionError): self.add_seismo() phi = self.phi / 180. * np.pi theta = (90. - self.theta) * np.pi / 180. return np.array([np.sin(theta) * np.cos(phi), np.sin(theta) * np.sin(phi), np.cos(theta)]) def proj_er(self, vector): """ projection of a vector on e_r, the radial vector in spherical coordinates. input: vector (cartesian coordinates) output: scalar """ try: assert(self.r is not None) assert(self.phi is not None) assert(self.theta is not None) except (AttributeError, NameError, AssertionError): self.add_seismo() vx, vy, vz = vector[0], vector[1], vector[2] # cartesian coordinates phi = self.phi / 180. * np.pi theta = (90. - self.theta) * np.pi / 180. return np.sin(theta) * np.cos(phi) * vx + np.sin(theta) * \ np.sin(phi) * vy + np.cos(theta) * vz def random_point(self, set_method="uniform", depth=[0., 1.], rICB=1.): """ Create a random point (not raypath) set_method: type of the distribution. Default is uniform over the sphere of radius self.rRICB = 1221. """ r = rICB - np.random.uniform(depth[0], depth[1]) phi = np.random.uniform(-180., 180.) theta = (np.arccos(2 * np.random.uniform(0., 1.) - 1) * 180. / np.pi) - 90 return r, theta, phi # #TODO : set other methods of randomisation! class SeismoPoint(Point): """ Point instance initialized with 'seismic' coordinates a, b, c : radius, theta (latitude) and phi (longitude) in degrees """ def __init__(self, a, b, c): self.r, self.theta, self.phi = a, b, c self.add_cartesian() class CartesianPoint(Point): """ Point instance initialized with cartesian coordinates a, b, c: x, y, z """ def __init__(self, a, b, c): self.x, self.y, self.z = a, b, c self.add_seismo() class RandomPoint(Point): def __init__(self, method, depth, rIC=1.): self.r, self.theta, self.phi = self.random_point(method, depth, rIC) self.add_cartesian() class Raypath(): """ Raypath inside Inner Core. raypath are defined either by: - bottom turning point + direction (useful for random trajectories) - in and out points (at the surface of IC, useful if coming from real data set) """ def __init__(self): self.points = None self.bottom_turning_point = None self.direction = None self.in_point = None self.out_point = None def add_property(self, dict_property, brute_force=False): """ add any property to the raypath. dict_property has to be of the form {'property':value} and will give self.property= value """ for k, v in dict_property.items(): if brute_force: setattr(self, k, v) else: try: # do not set new attribute except if brute force is wanted. getattr(self, k) except AttributeError: setattr(self, k, v) else: if getattr(self, k) is None: setattr(self, k, v) else: if getattr(self, k) != v: print( 'Attribute {} already defined with value {}. It has not been changed to {}.'.format( k, getattr( self, k), v)) def add_b_t_point(self, point, brute_force=False): """ Bottom turning point of the trajectory """ if self.bottom_turning_point is None: self.bottom_turning_point = point elif brute_force: self.bottom_turning_point = point else: print("bottom_turning_point already defined. Values has not been changed.") def straight_in_out(self, N): """ Trajectory is a straight line between in and out points, with N points (in and out points not directly parts of the trajectory). """ try: self.points = [] self.points, self.length = straight_trajectory( self.in_point, self.out_point, N + 2) except(NameError, AttributeError): raise Exception("in and out points have not been defined!") def straight_in_out_bt(self, N): """ Trajectory is a straight line between in and out points, with 2(N-2) points. """ if not ( self.in_point is None or self.out_point is None or self.bottom_turning_point is None): points1, length1 = straight_trajectory( self.in_point, self.bottom_turning_point, N) points2, length2 = self.straight_trajectory( self.bottom_turning_point, self.out_point, N) self.points = [] self.length = length1 + length2 self.points = points1 + self.bottom_turning_point + points2 else: raise Exception( "in, out or bottom turning points have not been defined!") def calc_zeta(self): """ zeta is the angle with rotation (vertical) axis. in and out points are required. """ # defining the axis ax_x, ax_y, ax_z = 0, 0, 1 vec_ax = [ax_x, ax_y, ax_z] # defining the trajectory vector try: x1, y1, z1 = self.in_point.x, self.in_point.y, self.in_point.z, x2, y2, z2 = self.out_point.x, self.out_point.y, self.out_point.z, except (NameError, AttributeError): raise Exception("in and out points have not been defined!") traj_x, traj_y, traj_z = x2 - x1, y2 - y1, z2 - z1 norm = np.sqrt(traj_x**2 + traj_y**2 + traj_z**2) traj_x, traj_y, traj_z = traj_x / norm, traj_y / norm, traj_z / norm vec_traj = [traj_x, traj_y, traj_z] def angle_btwn(vec_a, vec_b): """ angle between vector a and vector b return angle in degree """ costheta = np.dot(vec_a, vec_b) angle = np.arccos(costheta) * 180 / np.pi if angle > 90.: angle = 180. - angle return angle # np.abs(angle) self.direction = angle_btwn(vec_ax, vec_traj) return self.direction def calc_in_out_with_zeta_bt(self, rIC): """ Calculate in and out points from the BT point + zeta value zeta = self.direction Hypotheses are norm(v)=1, v.e_z=cos(zeta), v.e_r=0 (perpendicular to the e_r at the BT point) There is a bias in the calculation, with vectors always pointing same way... TODO better. """ x, y, z = self.bottom_turning_point.x, self.bottom_turning_point.y, self.bottom_turning_point.z def calc_vec(x, y, z, zeta): """ Calculate the vector direction of the path """ zeta = np.pi / 180 * zeta # to have radians v_z = np.cos(zeta) if x == 0 and y == 0: print("Error, the bt point is exactly on the rotation axis") return [0, 0, 0] else: if x == 0: v_y = -z / y * v_z v_x = np.sqrt(1 - v_z**2 - v_y**2) else: # v_z is solution of a quadratic equation, and v_x is # calculated from v_z polynome = [ y**2 / x**2 + 1, 2 * z * y / x**2 * v_z, z**2 / x**2 * v_z**2 + v_z**2 - 1] sol_v_y = np.roots(polynome) v_y = sol_v_y[0] # test what is the other root? print( "roots of the quadratic equation: {}. Root used: {}".format( sol_v_y, v_y)) v_x = -y / x * v_y - z / x * v_z return v_x, v_y, v_z v_x, v_y, v_z = calc_vec(x, y, z, self.direction) # intersection between the trajectory and the rIC polynome = [v_x**2 + v_y**2 + v_z**2, 2 * (v_x * x + v_y * y + v_z * z), x**2 + y**2 + z**2 - rIC**2] solutions = np.roots(polynome) # 2 solutions, 1 for in, for out. # Here we have no difference between in and out, so we just say first # is in. self.in_point = CartesianPoint( x + solutions[0] * v_x, y + solutions[0] * v_y, z + solutions[0] * v_z) self.out_point = CartesianPoint( x + solutions[1] * v_x, y + solutions[1] * v_y, z + solutions[1] * v_z)
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for ragged_factory_ops.constant.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np from tensorflow.python.framework import dtypes from tensorflow.python.framework import test_util from tensorflow.python.ops import ragged from tensorflow.python.ops.ragged import ragged_factory_ops from tensorflow.python.ops.ragged import ragged_tensor from tensorflow.python.platform import googletest @test_util.run_all_in_graph_and_eager_modes class RaggedConstOpTest(test_util.TensorFlowTestCase, parameterized.TestCase): @parameterized.parameters( #========================================================================= # 0-dimensional tensors. dict(pylist=b'x', expected_shape=()), #========================================================================= # 1-dimensional tensors. dict(pylist=[1, 2, 3], expected_shape=(3,)), #========================================================================= # 2-dimensional tensors. dict(pylist=[[1, 2, 3], [4], [5, 6]], expected_shape=(3, None)), dict(pylist=[[1, 2, 3], [4, 5, 6], [7, 8, 9]], expected_shape=(3, None)), #========================================================================= # 3-dimensional tensors. dict( pylist=[[[1, 2], [3, 4]], [], [[5, 6], [7, 8], [9, 0]]], expected_shape=(3, None, None)), dict( pylist=[[[1, 2], [3, 4]], [], [[5, 6], [7, 8], [9, 0]]], ragged_rank=1, expected_shape=(3, None, 2)), dict( pylist=[[[1, 2], [3, 4]], [], [[5, 6], [7, 8], [9, 0]]], inner_shape=(2,), expected_shape=(3, None, 2)), dict( pylist=[[[1, 2], [3, 4]], [], [[5, 6], [7, 8], [9, 0]]], ragged_rank=1, inner_shape=(2,), expected_shape=(3, None, 2)), # 3-dimensional tensors with numpy arrays dict( pylist=[[[1, 2], np.array([3, np.array(4)])], np.array([]), [[5, 6], [7, 8], [9, 0]]], expected_shape=(3, None, None)), dict( pylist=[[[1, 2], np.array([3, np.array(4)])], np.array([]), [[5, 6], [7, 8], [9, 0]]], ragged_rank=1, expected_shape=(3, None, 2)), dict( pylist=[[[1, 2], np.array([3, np.array(4)])], np.array([]), [[5, 6], [7, 8], [9, 0]]], inner_shape=(2,), expected_shape=(3, None, 2)), dict( pylist=[[[1, 2], np.array([3, np.array(4)])], np.array([]), [[5, 6], [7, 8], [9, 0]]], ragged_rank=1, inner_shape=(2,), expected_shape=(3, None, 2)), #========================================================================= # 4-dimensional tensors. dict( pylist=[[[[1, 2], [3, 4]], [[5, 6], [7, 8]]], [[[2, 4], [6, 8]], [[1, 5], [7, 9]]]], expected_shape=(2, None, None, None)), dict( pylist=[[[[1, 2], [3, 4]], [[5, 6], [7, 8]]], [[[2, 4], [6, 8]], [[1, 5], [7, 9]]]], ragged_rank=1, expected_shape=(2, None, 2, 2)), dict( pylist=[[[[1, 2], [3, 4]], [[5, 6], [7, 8]]], [[[2, 4], [6, 8]], [[1, 5], [7, 9]]]], inner_shape=(2,), expected_shape=(2, None, None, 2)), dict( pylist=[[[[1, 2], [3, 4]], [[5, 6], [7, 8]]], [[[2, 4], [6, 8]], [[1, 5], [7, 9]]]], inner_shape=(2, 2), expected_shape=(2, None, 2, 2)), # 4-dimensional tensors with numpy arrays dict( pylist=np.array([[[np.array([1, 2]), [3, 4]], [[5, 6], [7, 8]]], np.array([[[2, 4], [6, 8]], [[1, 5], [7, 9]]])]), expected_shape=(2, None, None, None)), #========================================================================= # Empty tensors (no scalar values) w/ default ragged_rank and inner_shape dict(pylist=[], expected_shape=(0,)), dict(pylist=[[], [], np.array([])], expected_shape=(3, None)), dict( pylist=[[[], []], [], [[], [[]]]], expected_shape=(3, None, None, None)), dict( pylist=np.array([np.array([[], []]), np.array([]), [[], [[]]]]), expected_shape=(3, None, None, None)), #========================================================================= # Empty tensors (no scalar values) w/ explicit ragged_rank or inner_shape dict(pylist=[], ragged_rank=1, expected_shape=(0, None)), dict(pylist=[], ragged_rank=2, expected_shape=(0, None, None)), dict(pylist=[], inner_shape=(0, 100, 20), expected_shape=(0, 100, 20)), dict( pylist=[], ragged_rank=1, inner_shape=(100, 20), expected_shape=(0, None, 100, 20)), dict( pylist=[], ragged_rank=2, inner_shape=(100, 20), expected_shape=(0, None, None, 100, 20)), dict(pylist=[[], [], []], ragged_rank=2, expected_shape=(3, None, None)), dict(pylist=[], inner_shape=(0,), expected_shape=(0,)), dict(pylist=[[]], inner_shape=(1, 0), expected_shape=(1, 0)), dict( pylist=np.array([]), ragged_rank=1, inner_shape=(100, 20), expected_shape=(0, None, 100, 20)), #========================================================================= # default/inferred dtypes dict(pylist=[], expected_dtype=dtypes.float32), dict(pylist=[[[], [[[]], []]]], expected_dtype=dtypes.float32), dict(pylist=[[1, 2], [3], [4, 5, 6]], expected_dtype=dtypes.int32), dict(pylist=[[1., 2.], [], [4., 5., 6.]], expected_dtype=dtypes.float32), dict(pylist=[[1, 2], [3.], [4, 5, 6]], expected_dtype=dtypes.float32), dict(pylist=[[b'a', b'b'], [b'c']], expected_dtype=dtypes.string), dict(pylist=[[True]], expected_dtype=dtypes.bool), dict( pylist=[np.array([1, 2]), np.array([3.]), [4, 5, 6]], expected_dtype=dtypes.float32), #========================================================================= # explicit dtypes dict(pylist=[], dtype=dtypes.float32), dict(pylist=[], dtype=dtypes.string), dict(pylist=[[1, 2], [3], [4, 5, 6]], dtype=dtypes.int64), dict(pylist=[[1, 2], [3], [4, 5, 6]], dtype=dtypes.int32), dict(pylist=[[1, 2], [3], [4, 5, 6]], dtype=dtypes.float32), dict(pylist=[[1., 2.], [3.], [4., 5., 6.]], dtype=dtypes.float16), dict(pylist=[[1., 2.], [3.], [4., 5., 6.]], dtype=dtypes.float32), dict( pylist=[[b'a', b'b'], [b'c'], [b'd', b'e', b'f']], dtype=dtypes.string), ) def testRaggedConst(self, pylist, dtype=None, ragged_rank=None, inner_shape=None, expected_shape=None, expected_dtype=None): """Tests that `ragged_const(pylist).eval().tolist() == pylist`. Args: pylist: The `pylist` argument for `ragged_const()`. dtype: The `dtype` argument for `ragged_const()`. If not None, then also test that the resulting ragged tensor has this `dtype`. ragged_rank: The `ragged_rank` argument for `ragged_const()`. If not None, then also test that the resulting ragged tensor has this `ragged_rank`. inner_shape: The `inner_shape` argument for `ragged_const()`. If not None, then also test that the resulting ragged tensor has this `inner_shape`. expected_shape: The expected shape for the resulting ragged tensor. expected_dtype: The expected dtype for the resulting ragged tensor (used to test default/inferred types when dtype=None). """ rt = ragged_factory_ops.constant( pylist, dtype=dtype, ragged_rank=ragged_rank, inner_shape=inner_shape) # Normalize the pylist, i.e., convert all np.arrays to list. # E.g., [np.array((1,2))] --> [[1,2]] pylist = _normalize_pylist(pylist) # If dtype was explicitly specified, check it. if dtype is not None: self.assertEqual(rt.dtype, dtype) if expected_dtype is not None: self.assertEqual(rt.dtype, expected_dtype) # If ragged_rank was explicitly specified, check it. if ragged_rank is not None: if isinstance(rt, ragged_tensor.RaggedTensor): self.assertEqual(rt.ragged_rank, ragged_rank) else: self.assertEqual(0, ragged_rank) # If inner_shape was explicitly specified, check it. if inner_shape is not None: if isinstance(rt, ragged_tensor.RaggedTensor): self.assertEqual(rt.flat_values.shape.as_list()[1:], list(inner_shape)) else: self.assertEqual(rt.shape.as_list(), list(inner_shape)) if expected_shape is not None: self.assertEqual(tuple(rt.shape.as_list()), expected_shape) if (expected_shape and expected_shape[0] == 0 and None not in expected_shape): pylist = np.zeros(expected_shape, rt.dtype.as_numpy_dtype) self.assertAllEqual(rt, pylist) @parameterized.parameters( dict( pylist=12, ragged_rank=1, exception=ValueError, message='Invalid pylist=12: incompatible with ragged_rank=1'), dict( pylist=12, inner_shape=(1,), exception=ValueError, message='Invalid pylist=12: incompatible with ' 'dim\\(inner_shape\\)=1'), dict( pylist=[[[1], [2]]], ragged_rank=-1, exception=ValueError, message='Invalid ragged_rank=-1: must be nonnegative'), dict( pylist=[[1, [2]]], exception=ValueError, message='all scalar values must have the same nesting depth'), dict( pylist=[[[1]], [[[2]]]], exception=ValueError, message='all scalar values must have the same nesting depth'), dict( pylist=[[1], [[]]], exception=ValueError, message='Invalid pylist=.*: empty list nesting is greater ' 'than scalar value nesting'), dict( pylist=[1, 2, 3], ragged_rank=1, exception=ValueError, message='pylist has scalar values depth 1, but ragged_rank=1 ' 'requires scalar value depth greater than 1'), dict( pylist=[[1, 2, 3], [4, 5, 6], [7, 8, 9]], ragged_rank=2, exception=ValueError, message='pylist has scalar values depth 2, but ragged_rank=2 ' 'requires scalar value depth greater than 2'), dict(pylist=[1, 2, 3], inner_shape=(1, 1), exception=TypeError), dict( pylist=[[[1, 2], [3, 4]], [[5, 6], [7, 8]]], inner_shape=(2, 2), ragged_rank=1, exception=ValueError, message='Invalid pylist=.*: incompatible with ragged_rank=1 and ' 'dim\\(inner_shape\\)=2'), dict( pylist=[[[1, 2], [3, 4]], [[5, 6], [7, 8, 9]]], ragged_rank=1, exception=ValueError, message='inner values have inconsistent shape'), dict( pylist=[[[], [[]]]], ragged_rank=1, exception=ValueError, message='inner values have inconsistent shape'), ) def testRaggedConstError(self, pylist, dtype=None, ragged_rank=None, inner_shape=None, exception=None, message=None): """Tests that `ragged_const()` raises an expected exception.""" self.assertRaisesRegex( exception, message, ragged_factory_ops.constant, pylist, dtype=dtype, ragged_rank=ragged_rank, inner_shape=inner_shape) @parameterized.parameters([ dict(pylist=9, scalar_depth=0, max_depth=0), dict(pylist=[9], scalar_depth=1, max_depth=1), dict(pylist=[1, 2, 3], scalar_depth=1, max_depth=1), dict(pylist=[[1], [2]], scalar_depth=2, max_depth=2), dict(pylist=[[[1], [2]], [[3]]], scalar_depth=3, max_depth=3), dict(pylist=[], scalar_depth=None, max_depth=1), dict(pylist=[[]], scalar_depth=None, max_depth=2), dict(pylist=[[], [], []], scalar_depth=None, max_depth=2), dict(pylist=[[[], []], [[], [[[]]]], []], scalar_depth=None, max_depth=5), dict( pylist=[1, [2]], exception=ValueError, message='all scalar values must have the same nesting depth'), dict( pylist=[[1], 2], exception=ValueError, message='all scalar values must have the same nesting depth'), dict( pylist=[[[[1]], []], [[2]]], exception=ValueError, message='all scalar values must have the same nesting depth'), ]) def testScalarAndMaxDepthHelper(self, pylist, scalar_depth=None, max_depth=None, exception=None, message=None): """Tests for the _find_scalar_and_max_depth helper function.""" if exception is not None: self.assertRaisesRegex(exception, message, ragged_factory_ops._find_scalar_and_max_depth, pylist) else: self.assertEqual( ragged_factory_ops._find_scalar_and_max_depth(pylist), (scalar_depth, max_depth)) @parameterized.parameters([ dict(pylist=[[1], [2, 3]], ragged_rank=1, inner_shape=()), dict( pylist=[[[1], [2]], [[3], [4], [5]]], ragged_rank=1, inner_shape=(1,)), dict(pylist=[[[1], [2]], [[3], [4], [5]]], ragged_rank=2, inner_shape=()), dict( pylist=[[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [2, 4, 6]]]], ragged_rank=1, inner_shape=(2, 3)), dict( pylist=[[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [2, 4, 6]]]], ragged_rank=2, inner_shape=(3,)), dict( pylist=[[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [2, 4, 6]]]], ragged_rank=3, inner_shape=()), dict( pylist=[[[1], [2, 3]]], ragged_rank=1, exception=ValueError, message='inner values have inconsistent shape'), dict( pylist=[[[1], [[2]]]], ragged_rank=1, exception=ValueError, message='inner values have inconsistent shape'), dict( pylist=[[[[1]], [2]]], ragged_rank=1, exception=ValueError, message='inner values have inconsistent shape'), ]) def testDefaultInnerShapeForPylistHelper(self, pylist, ragged_rank, inner_shape=None, exception=None, message=None): """Tests for the _default_inner_shape_for_pylist helper function.""" if exception is not None: self.assertRaisesRegex( exception, message, ragged.ragged_factory_ops._default_inner_shape_for_pylist, pylist, ragged_rank) else: self.assertEqual( ragged.ragged_factory_ops._default_inner_shape_for_pylist( pylist, ragged_rank), inner_shape) def _normalize_pylist(item): """Convert all (possibly nested) np.arrays contained in item to list.""" # convert np.arrays in current level to list if np.ndim(item) == 0: return item level = (x.tolist() if isinstance(x, np.ndarray) else x for x in item) return [_normalize_pylist(el) if np.ndim(el) != 0 else el for el in level] if __name__ == '__main__': googletest.main()
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.18 (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "$Format:%d$" git_full = "$Format:%H$" git_date = "$Format:%ci$" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_prefix = "" cfg.parentdir_prefix = "pyutrack-" cfg.versionfile_source = "pyutrack/_version.py" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%s*" % tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None}
# -*- coding: utf-8 -*- """ terminal.color ~~~~~~~~~~~~~~ ANSI color control for terminal. :copyright: (c) 2013 by Hsiaoming Yang. """ # http://en.wikipedia.org/wiki/ANSI_escape_code # http://en.wikipedia.org/wiki/Web_colors # https://gist.github.com/MicahElliott/719710 import os import sys # Python 3 if sys.version_info[0] == 3: string_type = str unicode = str else: string_type = (unicode, str) def is_color_supported(): "Find out if your terminal environment supports color." # shinx.util.console if not hasattr(sys.stdout, 'isatty'): return False if not sys.stdout.isatty() and 'TERMINAL-COLOR' not in os.environ: return False if sys.platform == 'win32': # pragma: no cover try: import colorama colorama.init() return True except ImportError: return False if 'COLORTERM' in os.environ: return True term = os.environ.get('TERM', 'dumb').lower() return term in ('xterm', 'linux') or 'color' in term def is_256color_supported(): "Find out if your terminal environment supports 256 color." if not is_color_supported(): return False term = os.environ.get('TERM', 'dumb').lower() return '256' in term def rgb2ansi(r, g, b): """ Convert an RGB color to 256 ansi graphics. """ # Thanks to # https://github.com/tehmaze/ansi/blob/master/ansi/colour/rgb.py grayscale = False poss = True step = 2.5 while poss: if min(r, g, b) < step: grayscale = max(r, g, b) < step poss = False step += 42.5 if grayscale: return 232 + int(float(sum((r, g, b)) / 33.0)) m = ((r, 36), (g, 6), (b, 1)) return 16 + sum(int(6 * float(val) / 256) * mod for val, mod in m) def hex2ansi(code): """ Convert hex code to ansi. """ if code.startswith('#'): code = code[1:] if len(code) == 3: # efc -> eeffcc return rgb2ansi(*map(lambda o: int(o * 2, 16), code)) if len(code) != 6: raise ValueError('invalid color code') rgb = (code[:2], code[2:4], code[4:]) return rgb2ansi(*map(lambda o: int(o, 16), rgb)) _reset = '\x1b[0;39;49m' _styles = ( 'bold', 'faint', 'italic', 'underline', 'blink', 'overline', 'inverse', 'conceal', 'strike', ) _colors = ( 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white' ) def _color2ansi(color): if color in _colors: return _colors.index(color) if isinstance(color, string_type): return hex2ansi(color) elif isinstance(color, (tuple, list)): return rgb2ansi(*color) raise ValueError('invalid color: %s' % color) class Color(object): """ Color object for painters. You should always use the high-level API of colors and styles, such as :class:`red` and :class:`bold`. But if you are so interested in this module, you are welcome to use some advanced features:: s = Color('text') print(s.bold.red.italic) All ANSI colors and styles are available on Color. """ def __init__(self, *items): self.items = items self.styles = [] self.fgcolor = None self.bgcolor = None def __getattr__(self, key): if key.endswith('_bg'): name = key[:-3] if name not in _colors: raise AttributeError("Color has no attribute '%s'" % key) self.bgcolor = _colors.index(name) return self if key in _colors: self.fgcolor = _colors.index(key) return self if key in _styles: code = _styles.index(key) self.styles.append(code + 1) return self try: return object.__getattribute__(self, key) except AttributeError: raise AttributeError("Color has no attribute '%s'" % key) def __str__(self): text = ''.join(unicode(item) for item in self.items) if unicode != str: text = text.encode('utf-8') if not is_color_supported(): return text is256 = is_256color_supported() if self.fgcolor and not isinstance(self.fgcolor, int): self.fgcolor = _color2ansi(self.fgcolor) if self.bgcolor and not isinstance(self.bgcolor, int): self.bgcolor = _color2ansi(self.bgcolor) if is256: if self.fgcolor is not None: text = '\x1b[38;5;%im%s%s' % (self.fgcolor, text, _reset) if self.bgcolor is not None: text = '\x1b[48;5;%im%s%s' % (self.bgcolor, text, _reset) else: if self.fgcolor is not None and self.fgcolor < 8: text = '\x1b[%im%s%s' % (30 + self.fgcolor, text, _reset) if self.bgcolor is not None and self.bgcolor < 8: text = '\x1b[%im%s%s' % (40 + self.bgcolor, text, _reset) if self.styles: code = ';'.join(str(i) for i in self.styles) text = '\x1b[%sm%s%s' % (code, text, _reset) return text def __repr__(self): return repr(str(self)) def __len__(self): return sum([len(item) for item in self.items]) def __add__(self, s): if not isinstance(s, (string_type, Color)): msg = "Concatenatation failed: %r + %r (Not a ColorString or str)" raise TypeError(msg % (type(s), type(self))) return Color(self, s) def __radd__(self, s): if not isinstance(s, (string_type, Color)): msg = "Concatenatation failed: %r + %r (Not a ColorString or str)" raise TypeError(msg % (type(s), type(self))) return Color(s, self) def colorize(text, color, background=False): """ Colorize text with hex code. :param text: the text you want to paint :param color: a hex color or rgb color :param background: decide to colorize background :: colorize('hello', 'ff0000') colorize('hello', '#ff0000') colorize('hello', (255, 0, 0)) """ if color in _styles: c = Color(text) c.styles = [_styles.index(color) + 1] return c c = Color(text) if background: c.bgcolor = _color2ansi(color) else: c.fgcolor = _color2ansi(color) return c def _create_color_func(text, fgcolor=None, bgcolor=None, *styles): c = Color(text) c.fgcolor = fgcolor c.bgcolor = bgcolor c.styles = styles return c def bold(text): """ Bold style. """ return _create_color_func(text, None, None, 1) def faint(text): """ Faint style. """ return _create_color_func(text, None, None, 2) def italic(text): """ Italic style. """ return _create_color_func(text, None, None, 3) def underline(text): """ Underline style. """ return _create_color_func(text, None, None, 4) def blink(text): """ Blink style. """ return _create_color_func(text, None, None, 5) def overline(text): """ Overline style. """ return _create_color_func(text, None, None, 6) def inverse(text): """ Inverse style. """ return _create_color_func(text, None, None, 7) def conceal(text): """ Conceal style. """ return _create_color_func(text, None, None, 8) def strike(text): """ Strike style. """ return _create_color_func(text, None, None, 9) def black(text): """ Black color. """ return _create_color_func(text, fgcolor=0) def red(text): """ Red color. """ return _create_color_func(text, fgcolor=1) def green(text): """ Green color. """ return _create_color_func(text, fgcolor=2) def yellow(text): """ Yellow color. """ return _create_color_func(text, fgcolor=3) def blue(text): """ Blue color. """ return _create_color_func(text, fgcolor=4) def magenta(text): """ Magenta color. """ return _create_color_func(text, fgcolor=5) def cyan(text): """ Cyan color. """ return _create_color_func(text, fgcolor=6) def white(text): """ White color. """ return _create_color_func(text, fgcolor=7) def gray(text): """ Gray color. """ if is_256color_supported(): return _create_color_func(text, fgcolor=8) return _create_color_func(text, 0, None, 8) def grey(text): """ Alias of gray. """ return gray(text) def black_bg(text): """ Black background. """ return _create_color_func(text, bgcolor=0) def red_bg(text): """ Red background. """ return _create_color_func(text, bgcolor=1) def green_bg(text): """ Green background. """ return _create_color_func(text, bgcolor=2) def yellow_bg(text): """ Yellow background. """ return _create_color_func(text, bgcolor=3) def blue_bg(text): """ Blue background. """ return _create_color_func(text, bgcolor=4) def magenta_bg(text): """ Magenta background. """ return _create_color_func(text, bgcolor=5) def cyan_bg(text): """ Cyan background. """ return _create_color_func(text, bgcolor=6) def white_bg(text): """ White background. """ return _create_color_func(text, bgcolor=7) def gray_bg(text): """ Gray background. """ if is_256color_supported(): return _create_color_func(text, bgcolor=8) return _create_color_func(text, None, 0, 1) def grey_bg(text): """ Alias of gray_bg. """ return gray_bg(text)
#!/usr/bin/env python # # Copyright 2007 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. # """Monitors a directory tree for changes using win32 APIs.""" import ctypes import logging import os import threading # FindNextChangeNotification constants (defined in FileAPI.h): _FILE_NOTIFY_CHANGE_FILE_NAME = 0x00000001 _FILE_NOTIFY_CHANGE_DIR_NAME = 0x00000002 _FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x00000004 _FILE_NOTIFY_CHANGE_SIZE = 0x00000008 _FILE_NOTIFY_CHANGE_LAST_WRITE = 0x00000010 _FILE_NOTIFY_CHANGE_CREATION = 0x00000040 _FILE_NOTIFY_CHANGE_SECURITY = 0x00000100 _FILE_NOTIFY_CHANGE_ANY = (_FILE_NOTIFY_CHANGE_FILE_NAME | _FILE_NOTIFY_CHANGE_DIR_NAME | _FILE_NOTIFY_CHANGE_ATTRIBUTES | _FILE_NOTIFY_CHANGE_SIZE | _FILE_NOTIFY_CHANGE_LAST_WRITE | _FILE_NOTIFY_CHANGE_CREATION | _FILE_NOTIFY_CHANGE_SECURITY) # pylint: disable=invalid-name _INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value _FILE_LIST_DIRECTORY = 1 _FILE_SHARE_READ = 0x1 _FILE_SHARE_WRITE = 0x2 _FILE_SHARE_DELETE = 0x4 _OPEN_EXISTING = 0x3 _FILE_FLAG_BACKUP_SEMANTICS = 0x02000000 _ERROR_NOTIFY_ENUM_DIR = 1022 _COMMON_FILE_NOTIFY_FIELDS = [ ('NextEntryOffset', ctypes.c_ulong), ('Action', ctypes.c_ulong), ('FileNameLength', ctypes.c_ulong) ] class FileNotifyInformationShort(ctypes.Structure): """This is the partial translation of the FILE_NOTIFY_INFORMATION struct. typedef struct _FILE_NOTIFY_INFORMATION { DWORD NextEntryOffset; DWORD Action; DWORD FileNameLength; WCHAR FileName[1]; } FILE_NOTIFY_INFORMATION It is partial because it doesn't include the variable-length FileName field. Another ctypes.Structure subclass is needed once we know the FileNameLength. """ _fields_ = _COMMON_FILE_NOTIFY_FIELDS _WCHAR_BYTESIZE = ctypes.sizeof(ctypes.c_wchar) def _parse_file_notification_information(buff, offset): """Parse FileNotificationInformation from a c_char buffer. Args: buff: a ctypes string buffer that contains a FileNotificationInformation structure. offset: the offset you want to parse the struct from. Returns: a class matching the structure. """ notify_information_short = ctypes.cast( ctypes.addressof(buff) + offset, ctypes.POINTER(FileNotifyInformationShort)).contents # This is a variable length structure so we need to do a 2 steps parse to # create a perfectly matching result. chr_len = notify_information_short.FileNameLength / _WCHAR_BYTESIZE class FileNotifyInformation(ctypes.Structure): _fields_ = ( _COMMON_FILE_NOTIFY_FIELDS + [('FileName', ctypes.c_wchar * chr_len)]) return ctypes.cast(ctypes.addressof(buff) + offset, ctypes.POINTER(FileNotifyInformation)).contents # we want to be sure that at least one notification fits even if it is a big # one. _BUFF_SIZE = 64 * 1024 def _parse_buffer(buff): """Parses a FileNotifyInformation out of a ctypes array of c_char.""" response = set() offset = 0 while True: notify_information = _parse_file_notification_information(buff, offset) response.add(notify_information.FileName) if notify_information.NextEntryOffset == 0: return response offset += notify_information.NextEntryOffset class Win32FileWatcher(object): """Monitors a directory tree for changes using win32 API.""" SUPPORTS_MULTIPLE_DIRECTORIES = False def __init__(self, directory): """Initializer for Win32FileWatcher. Args: directory: A string representing the path to a directory that should be monitored for changes i.e. files and directories added, renamed, deleted or changed. """ self._directory = os.path.abspath(directory) self._directory_handle = None self._change_set = set() self._lock = threading.Lock() # protects self._change_set self._stop = threading.Event() self._change_event = threading.Event() self._thread = None def start(self): """Start watching the directory for changes.""" self._directory_handle = ctypes.windll.kernel32.CreateFileW( ctypes.c_wchar_p(self._directory), ctypes.c_ulong(_FILE_LIST_DIRECTORY), ctypes.c_ulong(_FILE_SHARE_READ | _FILE_SHARE_WRITE), None, ctypes.c_ulong(_OPEN_EXISTING), # required to monitor changes. ctypes.c_ulong(_FILE_FLAG_BACKUP_SEMANTICS), None) if self._directory_handle == _INVALID_HANDLE_VALUE: raise ctypes.WinError() self._thread = threading.Thread( target=self._monitor, name='Win32 File Watcher') self._thread.start() def quit(self): """Stop watching the directory for changes.""" self._stop.set() # Note: this will unlock the blocking ReadDirectoryChangesW call. ctypes.windll.kernel32.CancelIoEx(self._directory_handle, None) self._thread.join() ctypes.windll.kernel32.CloseHandle(self._directory_handle) def changes(self, timeout_ms=0): """Returns the paths changed in the watched directory since the last call. start() must be called before this method. Args: timeout_ms: the maximum number of milliseconds you allow this function to wait for a filesystem change. Returns: Returns an iterable of changed directories/files. """ if timeout_ms != 0: self._change_event.wait(timeout_ms / 1000.0) with self._lock: result = self._change_set self._change_set = set() self._change_event.clear() return result def _monitor(self): buff = ctypes.create_string_buffer(_BUFF_SIZE) while not self._stop.isSet(): size_returned = ctypes.c_ulong(0) result = ctypes.windll.kernel32.ReadDirectoryChangesW( self._directory_handle, buff, ctypes.c_ulong(_BUFF_SIZE), True, # recursive. ctypes.c_ulong(_FILE_NOTIFY_CHANGE_ANY), ctypes.byref(size_returned), None, None) # this is a blocking call. if result == 0 and ctypes.GetLastError() == _ERROR_NOTIFY_ENUM_DIR: logging.warning('Buffer overflow while monitoring for file changes.') # we need to notify that something changed anyway with self._lock: self._change_set |= {'Unknown file'} if result != 0 and size_returned.value != 0: additional_changes = _parse_buffer(buff) with self._lock: self._change_set |= additional_changes self._change_event.set()
# 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. # ============================================================================== """Functions to build DetectionModel training optimizers.""" import tensorflow as tf from object_detection.utils import learning_schedules def build_optimizers_tf_v1(optimizer_config, global_step=None): """Create a TF v1 compatible optimizer based on config. Args: optimizer_config: A Optimizer proto message. global_step: A variable representing the current step. If None, defaults to tf.train.get_or_create_global_step() Returns: An optimizer and a list of variables for summary. Raises: ValueError: when using an unsupported input data type. """ optimizer_type = optimizer_config.WhichOneof('optimizer') optimizer = None summary_vars = [] if optimizer_type == 'rms_prop_optimizer': config = optimizer_config.rms_prop_optimizer learning_rate = _create_learning_rate(config.learning_rate, global_step=global_step) summary_vars.append(learning_rate) optimizer = tf.train.RMSPropOptimizer( learning_rate, decay=config.decay, momentum=config.momentum_optimizer_value, epsilon=config.epsilon) if optimizer_type == 'momentum_optimizer': config = optimizer_config.momentum_optimizer learning_rate = _create_learning_rate(config.learning_rate, global_step=global_step) summary_vars.append(learning_rate) optimizer = tf.train.MomentumOptimizer( learning_rate, momentum=config.momentum_optimizer_value) if optimizer_type == 'adam_optimizer': config = optimizer_config.adam_optimizer learning_rate = _create_learning_rate(config.learning_rate, global_step=global_step) summary_vars.append(learning_rate) optimizer = tf.train.AdamOptimizer(learning_rate) if optimizer is None: raise ValueError('Optimizer %s not supported.' % optimizer_type) if optimizer_config.use_moving_average: optimizer = tf.contrib.opt.MovingAverageOptimizer( optimizer, average_decay=optimizer_config.moving_average_decay) return optimizer, summary_vars def build_optimizers_tf_v2(optimizer_config, global_step=None): """Create a TF v2 compatible optimizer based on config. Args: optimizer_config: A Optimizer proto message. global_step: A variable representing the current step. If None, defaults to tf.train.get_or_create_global_step() Returns: An optimizer and a list of variables for summary. Raises: ValueError: when using an unsupported input data type. """ optimizer_type = optimizer_config.WhichOneof('optimizer') optimizer = None summary_vars = [] if optimizer_type == 'rms_prop_optimizer': config = optimizer_config.rms_prop_optimizer learning_rate = _create_learning_rate(config.learning_rate, global_step=global_step) summary_vars.append(learning_rate) optimizer = tf.keras.optimizers.RMSprop( learning_rate, decay=config.decay, momentum=config.momentum_optimizer_value, epsilon=config.epsilon) if optimizer_type == 'momentum_optimizer': config = optimizer_config.momentum_optimizer learning_rate = _create_learning_rate(config.learning_rate, global_step=global_step) summary_vars.append(learning_rate) optimizer = tf.keras.optimizers.SGD( learning_rate, momentum=config.momentum_optimizer_value) if optimizer_type == 'adam_optimizer': config = optimizer_config.adam_optimizer learning_rate = _create_learning_rate(config.learning_rate, global_step=global_step) summary_vars.append(learning_rate) optimizer = tf.keras.optimizers.Adam(learning_rate) if optimizer is None: raise ValueError('Optimizer %s not supported.' % optimizer_type) if optimizer_config.use_moving_average: raise ValueError('Moving average not supported in eager mode.') return optimizer, summary_vars def build(config, global_step=None): if tf.executing_eagerly(): return build_optimizers_tf_v2(config, global_step) else: return build_optimizers_tf_v1(config, global_step) def _create_learning_rate(learning_rate_config, global_step=None): """Create optimizer learning rate based on config. Args: learning_rate_config: A LearningRate proto message. global_step: A variable representing the current step. If None, defaults to tf.train.get_or_create_global_step() Returns: A learning rate. Raises: ValueError: when using an unsupported input data type. """ if global_step is None: global_step = tf.train.get_or_create_global_step() learning_rate = None learning_rate_type = learning_rate_config.WhichOneof('learning_rate') if learning_rate_type == 'constant_learning_rate': config = learning_rate_config.constant_learning_rate learning_rate = tf.constant(config.learning_rate, dtype=tf.float32, name='learning_rate') if learning_rate_type == 'exponential_decay_learning_rate': config = learning_rate_config.exponential_decay_learning_rate learning_rate = learning_schedules.exponential_decay_with_burnin( global_step, config.initial_learning_rate, config.decay_steps, config.decay_factor, burnin_learning_rate=config.burnin_learning_rate, burnin_steps=config.burnin_steps, min_learning_rate=config.min_learning_rate, staircase=config.staircase) if learning_rate_type == 'manual_step_learning_rate': config = learning_rate_config.manual_step_learning_rate if not config.schedule: raise ValueError('Empty learning rate schedule.') learning_rate_step_boundaries = [x.step for x in config.schedule] learning_rate_sequence = [config.initial_learning_rate] learning_rate_sequence += [x.learning_rate for x in config.schedule] learning_rate = learning_schedules.manual_stepping( global_step, learning_rate_step_boundaries, learning_rate_sequence, config.warmup) if learning_rate_type == 'cosine_decay_learning_rate': config = learning_rate_config.cosine_decay_learning_rate learning_rate = learning_schedules.cosine_decay_with_warmup( global_step, config.learning_rate_base, config.total_steps, config.warmup_learning_rate, config.warmup_steps, config.hold_base_rate_steps) if learning_rate is None: raise ValueError('Learning_rate %s not supported.' % learning_rate_type) return learning_rate
# encoding=utf8 import datetime from distutils.version import StrictVersion import hashlib import os.path import random from seesaw.config import realize, NumberConfigValue from seesaw.externalprocess import ExternalProcess from seesaw.item import ItemInterpolation, ItemValue from seesaw.task import SimpleTask, LimitConcurrent from seesaw.tracker import GetItemFromTracker, PrepareStatsForTracker, \ UploadWithTracker, SendDoneToTracker import shutil import socket import subprocess import sys import time import string import seesaw from seesaw.externalprocess import WgetDownload from seesaw.pipeline import Pipeline from seesaw.project import Project from seesaw.util import find_executable # check the seesaw version if StrictVersion(seesaw.__version__) < StrictVersion("0.8.5"): raise Exception("This pipeline needs seesaw version 0.8.5 or higher.") ########################################################################### # Find a useful Wget+Lua executable. # # WGET_LUA will be set to the first path that # 1. does not crash with --version, and # 2. prints the required version string WGET_LUA = find_executable( "Wget+Lua", ["GNU Wget 1.14.lua.20130523-9a5c", "GNU Wget 1.14.lua.20160530-955376b"], [ "./wget-lua", "./wget-lua-warrior", "./wget-lua-local", "../wget-lua", "../../wget-lua", "/home/warrior/wget-lua", "/usr/bin/wget-lua" ] ) if not WGET_LUA: raise Exception("No usable Wget+Lua found.") ########################################################################### # The version number of this pipeline definition. # # Update this each time you make a non-cosmetic change. # It will be added to the WARC files and reported to the tracker. VERSION = "20170219.01" USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3' TRACKER_ID = 'imdb' TRACKER_HOST = 'tracker.archiveteam.org' ########################################################################### # This section defines project-specific tasks. # # Simple tasks (tasks that do not need any concurrency) are based on the # SimpleTask class and have a process(item) method that is called for # each item. class CheckIP(SimpleTask): def __init__(self): SimpleTask.__init__(self, "CheckIP") self._counter = 0 def process(self, item): # NEW for 2014! Check if we are behind firewall/proxy if self._counter <= 0: item.log_output('Checking IP address.') ip_set = set() ip_set.add(socket.gethostbyname('twitter.com')) ip_set.add(socket.gethostbyname('facebook.com')) ip_set.add(socket.gethostbyname('youtube.com')) ip_set.add(socket.gethostbyname('microsoft.com')) ip_set.add(socket.gethostbyname('icanhas.cheezburger.com')) ip_set.add(socket.gethostbyname('archiveteam.org')) if len(ip_set) != 6: item.log_output('Got IP addresses: {0}'.format(ip_set)) item.log_output( 'Are you behind a firewall/proxy? That is a big no-no!') raise Exception( 'Are you behind a firewall/proxy? That is a big no-no!') # Check only occasionally if self._counter <= 0: self._counter = 10 else: self._counter -= 1 class PrepareDirectories(SimpleTask): def __init__(self, warc_prefix): SimpleTask.__init__(self, "PrepareDirectories") self.warc_prefix = warc_prefix def process(self, item): item_name = item["item_name"] escaped_item_name = item_name.replace(':', '_').replace('/', '_').replace('~', '_') dirname = "/".join((item["data_dir"], escaped_item_name)) if os.path.isdir(dirname): shutil.rmtree(dirname) os.makedirs(dirname) item["item_dir"] = dirname item["warc_file_base"] = "%s-%s-%s" % (self.warc_prefix, escaped_item_name, time.strftime("%Y%m%d-%H%M%S")) open("%(item_dir)s/%(warc_file_base)s.warc.gz" % item, "w").close() class MoveFiles(SimpleTask): def __init__(self): SimpleTask.__init__(self, "MoveFiles") def process(self, item): # NEW for 2014! Check if wget was compiled with zlib support if os.path.exists("%(item_dir)s/%(warc_file_base)s.warc" % item): raise Exception('Please compile wget with zlib support!') os.rename("%(item_dir)s/%(warc_file_base)s.warc.gz" % item, "%(data_dir)s/%(warc_file_base)s.warc.gz" % item) shutil.rmtree("%(item_dir)s" % item) def get_hash(filename): with open(filename, 'rb') as in_file: return hashlib.sha1(in_file.read()).hexdigest() CWD = os.getcwd() PIPELINE_SHA1 = get_hash(os.path.join(CWD, 'pipeline.py')) LUA_SHA1 = get_hash(os.path.join(CWD, 'imdb.lua')) def stats_id_function(item): # NEW for 2014! Some accountability hashes and stats. d = { 'pipeline_hash': PIPELINE_SHA1, 'lua_hash': LUA_SHA1, 'python_version': sys.version, } return d class WgetArgs(object): def realize(self, item): wget_args = [ WGET_LUA, "-U", USER_AGENT, "-nv", "--no-cookies", "--lua-script", "imdb.lua", "-o", ItemInterpolation("%(item_dir)s/wget.log"), "--no-check-certificate", "--output-document", ItemInterpolation("%(item_dir)s/wget.tmp"), "--truncate-output", "-e", "robots=off", "--rotate-dns", "--recursive", "--level=inf", "--no-parent", "--page-requisites", "--timeout", "30", "--tries", "inf", "--domains", "imdb.com", "--span-hosts", "--waitretry", "30", "--warc-file", ItemInterpolation("%(item_dir)s/%(warc_file_base)s"), "--warc-header", "operator: Archive Team", "--warc-header", "imdb-dld-script-version: " + VERSION, "--warc-header", ItemInterpolation("imdb-item: %(item_name)s"), "--warc-header", "pipeline.py-hash: " + PIPELINE_SHA1, "--warc-header", "imdb.lua-hash: " + LUA_SHA1 ] item_name = item['item_name'] assert ':' in item_name item_type, item_value = item_name.split(':', 1) item['item_type'] = item_type item['item_value'] = item_value if item_type == 'title': wget_args.extend(["--warc-header", "imdb-title: " + item_value]) wget_args.append('http://www.imdb.com/title/{item_value}/'.format(**locals())) #wget_args.append('http://m.imdb.com/title/{item_value}/'.format(**locals())) elif item_type == 'title_board': new_item_value = 'tt' + item_value.zfill(7) wget_args.extend(["--warc-header", "imdb-board-title: " + new_item_value]) wget_args.extend(["--warc-header", "imdb-board-title-id: " + item_value]) wget_args.append('http://www.imdb.com/title/{new_item_value}/'.format(**locals())) wget_args.append('http://www.imdb.com/title/{new_item_value}/board/'.format(**locals())) wget_args.append('http://www.imdb.com/title/{new_item_value}/board/?ref_=tt_bd_sm'.format(**locals())) #wget_args.append('http://m.imdb.com/title/{new_item_value}/'.format(**locals())) #wget_args.append('http://m.imdb.com/title/{new_item_value}/board/'.format(**locals())) #wget_args.append('http://m.imdb.com/title/{new_item_value}/board/?ref_=tt_bd_sm'.format(**locals())) elif item_type == '10_name_boards': start, stop = item_value.split('-') for i in range(int(start), int(stop)+1): new_item_value = 'nm' + str(i).zfill(7) wget_args.extend(["--warc-header", "imdb-board-name: " + new_item_value]) wget_args.extend(["--warc-header", "imdb-board-name-id: " + str(i)]) wget_args.append('http://www.imdb.com/name/{new_item_value}/'.format(**locals())) wget_args.append('http://www.imdb.com/name/{new_item_value}/board/'.format(**locals())) wget_args.append('http://www.imdb.com/name/{new_item_value}/board/?ref_=tt_bd_sm'.format(**locals())) else: raise Exception('Unknown item') if 'bind_address' in globals(): wget_args.extend(['--bind-address', globals()['bind_address']]) print('') print('*** Wget will bind address at {0} ***'.format( globals()['bind_address'])) print('') return realize(wget_args, item) ########################################################################### # Initialize the project. # # This will be shown in the warrior management panel. The logo should not # be too big. The deadline is optional. project = Project( title="imdb", project_html=""" <img class="project-logo" alt="Project logo" src="http://archiveteam.org/images/thumb/e/e6/Imdb_logo.png/320px-Imdb_logo.png" height="50px" title=""/> <h2>imdb.com <span class="links"><a href="http://imdb.com/">Website</a> &middot; <a href="http://tracker.archiveteam.org/imdb/">Leaderboard</a></span></h2> <p>IMDb removes the message boards, so we're getting a full copy!</p> """ ) pipeline = Pipeline( CheckIP(), GetItemFromTracker("http://%s/%s" % (TRACKER_HOST, TRACKER_ID), downloader, VERSION), PrepareDirectories(warc_prefix="imdb"), WgetDownload( WgetArgs(), max_tries=2, accept_on_exit_code=[0, 4, 8], env={ "item_dir": ItemValue("item_dir"), "item_value": ItemValue("item_value"), "item_type": ItemValue("item_type"), "warc_file_base": ItemValue("warc_file_base"), } ), PrepareStatsForTracker( defaults={"downloader": downloader, "version": VERSION}, file_groups={ "data": [ ItemInterpolation("%(item_dir)s/%(warc_file_base)s.warc.gz") ] }, id_function=stats_id_function, ), MoveFiles(), LimitConcurrent(NumberConfigValue(min=1, max=4, default="1", name="shared:rsync_threads", title="Rsync threads", description="The maximum number of concurrent uploads."), UploadWithTracker( "http://%s/%s" % (TRACKER_HOST, TRACKER_ID), downloader=downloader, version=VERSION, files=[ ItemInterpolation("%(data_dir)s/%(warc_file_base)s.warc.gz") ], rsync_target_source_path=ItemInterpolation("%(data_dir)s/"), rsync_extra_args=[ "--recursive", "--partial", "--partial-dir", ".rsync-tmp", ] ), ), SendDoneToTracker( tracker_url="http://%s/%s" % (TRACKER_HOST, TRACKER_ID), stats=ItemValue("stats") ) )
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # =================================================================== """TPU Feature Column Library.""" import copy import math import enum from tensorflow.python.feature_column import feature_column as fc from tensorflow.python.feature_column import feature_column_lib as fc_lib from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import embedding_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import sparse_ops from tensorflow.python.ops import variable_scope from tensorflow.python.tpu import tpu from tensorflow.python.tpu.feature_column import _is_running_on_cpu from tensorflow.python.tpu.feature_column import _record_variable_scope_and_name from tensorflow.python.tpu.feature_column import _SUPPORTED_CATEGORICAL_COLUMNS_V2 from tensorflow.python.tpu.feature_column import _SUPPORTED_SEQUENCE_COLUMNS from tensorflow.python.tpu.feature_column import _TPUBaseEmbeddingColumn from tensorflow.python.util.tf_export import tf_export # pylint: disable=protected-access _ALLOWED_DEVICES = ['cpu', 'tpu_tensor_core', 'tpu_embedding_core'] _TENSOR_CORE_MASK_KEY_SUFFIX = '__TENSOR_CORE_MASK' class EmbeddingDevice(enum.Enum): CPU = 1 TPU_TENSOR_CORE = 2 TPU_EMBEDDING_CORE = 3 @tf_export(v1=['tpu.experimental.embedding_column']) def embedding_column_v2(categorical_column, dimension, combiner='mean', initializer=None, max_sequence_length=0, learning_rate_fn=None, embedding_lookup_device=None, tensor_core_shape=None, use_safe_embedding_lookup=True): """TPU version of `tf.compat.v1.feature_column.embedding_column`. Note that the interface for `tf.tpu.experimental.embedding_column` is different from that of `tf.compat.v1.feature_column.embedding_column`: The following arguments are NOT supported: `ckpt_to_load_from`, `tensor_name_in_ckpt`, `max_norm` and `trainable`. Use this function in place of `tf.compat.v1.feature_column.embedding_column` when you want to use the TPU to accelerate your embedding lookups via TPU embeddings. ``` column = tf.feature_column.categorical_column_with_identity(...) tpu_column = tf.tpu.experimental.embedding_column(column, 10) ... def model_fn(features): dense_feature = tf.keras.layers.DenseFeature(tpu_column) embedded_feature = dense_feature(features) ... estimator = tf.estimator.tpu.TPUEstimator( model_fn=model_fn, ... embedding_config_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec( column=[tpu_column], ...)) ``` Args: categorical_column: A categorical column returned from `categorical_column_with_identity`, `weighted_categorical_column`, `categorical_column_with_vocabulary_file`, `categorical_column_with_vocabulary_list`, `sequence_categorical_column_with_identity`, `sequence_categorical_column_with_vocabulary_file`, `sequence_categorical_column_with_vocabulary_list` dimension: An integer specifying dimension of the embedding, must be > 0. combiner: A string specifying how to reduce if there are multiple entries in a single row for a non-sequence column. For more information, see `tf.feature_column.embedding_column`. initializer: A variable initializer function to be used in embedding variable initialization. If not specified, defaults to `tf.compat.v1.truncated_normal_initializer` with mean `0.0` and standard deviation `1/sqrt(dimension)`. max_sequence_length: An non-negative integer specifying the max sequence length. Any sequence shorter then this will be padded with 0 embeddings and any sequence longer will be truncated. This must be positive for sequence features and 0 for non-sequence features. learning_rate_fn: A function that takes global step and returns learning rate for the embedding table. If you intend to use the same learning rate for multiple embedding tables, please ensure that you pass the exact same python function to all calls of embedding_column, otherwise performence may suffer. embedding_lookup_device: The device on which to run the embedding lookup. Valid options are "cpu", "tpu_tensor_core", and "tpu_embedding_core". If specifying "tpu_tensor_core", a tensor_core_shape must be supplied. If not specified, the default behavior is embedding lookup on "tpu_embedding_core" for training and "cpu" for inference. Valid options for training : ["tpu_embedding_core", "tpu_tensor_core"] Valid options for serving : ["cpu", "tpu_tensor_core"] For training, tpu_embedding_core is good for large embedding vocab (>1M), otherwise, tpu_tensor_core is often sufficient. For serving, doing embedding lookup on tpu_tensor_core during serving is a way to reduce host cpu usage in cases where that is a bottleneck. tensor_core_shape: If supplied, a list of integers which specifies the intended dense shape to run embedding lookup for this feature on TensorCore. The batch dimension can be left None or -1 to indicate a dynamic shape. Only rank 2 shapes currently supported. use_safe_embedding_lookup: If true, uses safe_embedding_lookup_sparse instead of embedding_lookup_sparse. safe_embedding_lookup_sparse ensures there are no empty rows and all weights and ids are positive at the expense of extra compute cost. This only applies to rank 2 (NxM) shaped input tensors. Defaults to true, consider turning off if the above checks are not needed. Note that having empty rows will not trigger any error though the output result might be 0 or omitted. Returns: A `_TPUEmbeddingColumnV2`. Raises: ValueError: if `dimension` not > 0. ValueError: if `initializer` is specified but not callable. """ if not isinstance(categorical_column, _SUPPORTED_CATEGORICAL_COLUMNS_V2): raise TypeError( 'categorical_column for tpu ' 'embedding_column must be type {}, got {}.'.format(' or '.join([ cc.__name__ for cc in _SUPPORTED_CATEGORICAL_COLUMNS_V2 ]), type(categorical_column))) if (dimension is None) or (dimension < 1): raise ValueError('Invalid dimension {}.'.format(dimension)) if tensor_core_shape and len(tensor_core_shape) != 2: raise ValueError( 'tensor_core_shape must be size 2. Got {}.'.format(tensor_core_shape)) if (initializer is not None) and (not callable(initializer)): raise ValueError('initializer must be callable if specified. ' 'Embedding of column_name: {}'.format( categorical_column.name)) if initializer is None: initializer = init_ops.truncated_normal_initializer( mean=0.0, stddev=1 / math.sqrt(dimension)) if (embedding_lookup_device and embedding_lookup_device not in _ALLOWED_DEVICES): raise ValueError( f'If set, embedding_lookup_device must be in {_ALLOWED_DEVICES}') if embedding_lookup_device == 'cpu': embedding_lookup_device = EmbeddingDevice.CPU elif embedding_lookup_device == 'tpu_tensor_core': embedding_lookup_device = EmbeddingDevice.TPU_TENSOR_CORE elif embedding_lookup_device == 'tpu_embedding_core': embedding_lookup_device = EmbeddingDevice.TPU_EMBEDDING_CORE if embedding_lookup_device == EmbeddingDevice.TPU_TENSOR_CORE: if not tensor_core_shape: raise ValueError('Using embedding_lookup_device=tpu_tensor_core requires ' 'tensor_core_shape to be set.') if isinstance(categorical_column, _SUPPORTED_SEQUENCE_COLUMNS): raise ValueError('embedding_lookup_device=tpu_tensor_core currently does ' 'not support sequence columns.') if not embedding_lookup_device: return _TPUEmbeddingColumnV2( categorical_column=categorical_column, dimension=dimension, combiner=combiner, initializer=initializer, max_sequence_length=max_sequence_length, learning_rate_fn=learning_rate_fn, use_safe_embedding_lookup=use_safe_embedding_lookup) else: return _TPUDeviceSpecificEmbeddingColumnV2( categorical_column=categorical_column, dimension=dimension, combiner=combiner, initializer=initializer, max_sequence_length=max_sequence_length, learning_rate_fn=learning_rate_fn, embedding_lookup_device=embedding_lookup_device, tensor_core_shape=tensor_core_shape, use_safe_embedding_lookup=use_safe_embedding_lookup) @tf_export(v1=['tpu.experimental.shared_embedding_columns']) def shared_embedding_columns_v2(categorical_columns, dimension, combiner='mean', initializer=None, shared_embedding_collection_name=None, max_sequence_lengths=None, learning_rate_fn=None, embedding_lookup_device=None, tensor_core_shape=None, use_safe_embedding_lookup=True): """TPU version of `tf.compat.v1.feature_column.shared_embedding_columns`. Note that the interface for `tf.tpu.experimental.shared_embedding_columns` is different from that of `tf.compat.v1.feature_column.shared_embedding_columns`: The following arguments are NOT supported: `ckpt_to_load_from`, `tensor_name_in_ckpt`, `max_norm` and `trainable`. Use this function in place of tf.compat.v1.feature_column.shared_embedding_columns` when you want to use the TPU to accelerate your embedding lookups via TPU embeddings. ``` column_a = tf.feature_column.categorical_column_with_identity(...) column_b = tf.feature_column.categorical_column_with_identity(...) tpu_columns = tf.tpu.experimental.shared_embedding_columns( [column_a, column_b], 10) ... def model_fn(features): dense_feature = tf.keras.layers.DenseFeature(tpu_columns) embedded_feature = dense_feature(features) ... estimator = tf.estimator.tpu.TPUEstimator( model_fn=model_fn, ... embedding_config_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec( column=tpu_columns, ...)) ``` Args: categorical_columns: A list of categorical columns returned from `categorical_column_with_identity`, `weighted_categorical_column`, `categorical_column_with_vocabulary_file`, `categorical_column_with_vocabulary_list`, `sequence_categorical_column_with_identity`, `sequence_categorical_column_with_vocabulary_file`, `sequence_categorical_column_with_vocabulary_list` dimension: An integer specifying dimension of the embedding, must be > 0. combiner: A string specifying how to reduce if there are multiple entries in a single row for a non-sequence column. For more information, see `tf.feature_column.embedding_column`. initializer: A variable initializer function to be used in embedding variable initialization. If not specified, defaults to `tf.truncated_normal_initializer` with mean `0.0` and standard deviation `1/sqrt(dimension)`. shared_embedding_collection_name: Optional name of the collection where shared embedding weights are added. If not given, a reasonable name will be chosen based on the names of `categorical_columns`. This is also used in `variable_scope` when creating shared embedding weights. max_sequence_lengths: An list of non-negative integers, either None or empty or the same length as the argument categorical_columns. Entries corresponding to non-sequence columns must be 0 and entries corresponding to sequence columns specify the max sequence length for the column. Any sequence shorter then this will be padded with 0 embeddings and any sequence longer will be truncated. learning_rate_fn: A function that takes global step and returns learning rate for the embedding table. If you intend to use the same learning rate for multiple embedding tables, please ensure that you pass the exact same python function to all calls of shared_embedding_columns, otherwise performence may suffer. embedding_lookup_device: The device on which to run the embedding lookup. Valid options are "cpu", "tpu_tensor_core", and "tpu_embedding_core". If specifying "tpu_tensor_core", a tensor_core_shape must be supplied. Defaults to "cpu". If not specified, the default behavior is embedding lookup on "tpu_embedding_core" for training and "cpu" for inference. Valid options for training : ["tpu_embedding_core", "tpu_tensor_core"] Valid options for serving : ["cpu", "tpu_tensor_core"] For training, tpu_embedding_core is good for large embedding vocab (>1M), otherwise, tpu_tensor_core is often sufficient. For serving, doing embedding lookup on tpu_tensor_core during serving is a way to reduce host cpu usage in cases where that is a bottleneck. tensor_core_shape: If supplied, a list of integers which specifies the intended dense shape to run embedding lookup for this feature on TensorCore. The batch dimension can be left None or -1 to indicate a dynamic shape. Only rank 2 shapes currently supported. use_safe_embedding_lookup: If true, uses safe_embedding_lookup_sparse instead of embedding_lookup_sparse. safe_embedding_lookup_sparse ensures there are no empty rows and all weights and ids are positive at the expense of extra compute cost. This only applies to rank 2 (NxM) shaped input tensors. Defaults to true, consider turning off if the above checks are not needed. Note that having empty rows will not trigger any error though the output result might be 0 or omitted. Returns: A list of `_TPUSharedEmbeddingColumnV2`. Raises: ValueError: if `dimension` not > 0. ValueError: if `initializer` is specified but not callable. ValueError: if `max_sequence_lengths` is specified and not the same length as `categorical_columns`. ValueError: if `max_sequence_lengths` is positive for a non sequence column or 0 for a sequence column. """ for categorical_column in categorical_columns: if not isinstance(categorical_column, _SUPPORTED_CATEGORICAL_COLUMNS_V2): raise TypeError( 'categorical_column for tpu ' ' shared_embedding_columns must be type {}, got {}.'.format( ' or '.join( [cc.__name__ for cc in _SUPPORTED_CATEGORICAL_COLUMNS_V2]), type(categorical_column))) if not max_sequence_lengths: max_sequence_lengths = [0] * len(categorical_columns) if len(max_sequence_lengths) != len(categorical_columns): raise ValueError('max_sequence_lengths and categorical_columns must be of ' 'the same length. len(max_sequence_lengths)={} ' 'len(categorical_columns)={}.'.format( len(max_sequence_lengths), len(categorical_columns))) if (dimension is None) or (dimension < 1): raise ValueError('Invalid dimension {}.'.format(dimension)) if tensor_core_shape and len(tensor_core_shape) != 2: raise ValueError( 'tensor_core_shape must be size 2. Got {}.'.format(tensor_core_shape)) if (initializer is not None) and (not callable(initializer)): raise ValueError('initializer must be callable if specified. ') if initializer is None: initializer = init_ops.truncated_normal_initializer( mean=0.0, stddev=1 / math.sqrt(dimension)) # Sort the columns so the default collection name is deterministic even if the # user passes columns from an unsorted collection, such as dict.values(). sorted_columns = sorted(categorical_columns, key=lambda x: x.name) num_buckets = sorted_columns[0]._num_buckets # pylint: disable=protected-access for c in sorted_columns[1:]: if num_buckets != c._num_buckets: # pylint: disable=protected-access raise ValueError( 'To use shared_embedding_column, all categorical_columns must have ' 'the same number of buckets. Given column: {} with buckets: {} does ' 'not match column: {} with buckets: {}'.format( sorted_columns[0], num_buckets, c, c._num_buckets)) # pylint: disable=protected-access if not shared_embedding_collection_name: shared_embedding_collection_name = '_'.join(c.name for c in sorted_columns) shared_embedding_collection_name += '_shared_embedding' tpu_columns = [] column_creator = fc_lib.SharedEmbeddingColumnCreator( dimension=dimension, initializer=initializer, ckpt_to_load_from=None, tensor_name_in_ckpt=None, num_buckets=num_buckets, trainable=None, name=shared_embedding_collection_name) if (embedding_lookup_device and embedding_lookup_device not in _ALLOWED_DEVICES): raise ValueError( f'If set, embedding_lookup_device must be in {_ALLOWED_DEVICES}') if embedding_lookup_device == 'cpu': embedding_lookup_device = EmbeddingDevice.CPU elif embedding_lookup_device == 'tpu_tensor_core': embedding_lookup_device = EmbeddingDevice.TPU_TENSOR_CORE elif embedding_lookup_device == 'tpu_embedding_core': embedding_lookup_device = EmbeddingDevice.TPU_EMBEDDING_CORE if embedding_lookup_device == EmbeddingDevice.TPU_TENSOR_CORE: if not tensor_core_shape: raise ValueError('Using embedding_lookup_device=tpu_tensor_core requires ' 'tensor_core_shape to be set.') for c in sorted_columns: if isinstance(c, _SUPPORTED_SEQUENCE_COLUMNS): raise ValueError('embedding_lookup_device=tpu_tensor_core currently ' 'does not support sequence columns.') # Create the state (_SharedEmbeddingColumnLayer) here. for categorical_column, max_sequence_length in zip( categorical_columns, max_sequence_lengths): if not embedding_lookup_device: column = _TPUSharedEmbeddingColumnV2( categorical_column=categorical_column, shared_embedding_column_creator=column_creator, combiner=combiner, initializer=initializer, shared_embedding_collection_name=shared_embedding_collection_name, max_sequence_length=max_sequence_length, learning_rate_fn=learning_rate_fn, use_safe_embedding_lookup=use_safe_embedding_lookup) else: column = _TPUSharedDeviceSpecificEmbeddingColumnV2( categorical_column=categorical_column, shared_embedding_column_creator=column_creator, combiner=combiner, initializer=initializer, shared_embedding_collection_name=shared_embedding_collection_name, max_sequence_length=max_sequence_length, learning_rate_fn=learning_rate_fn, embedding_lookup_device=embedding_lookup_device, tensor_core_shape=tensor_core_shape, use_safe_embedding_lookup=use_safe_embedding_lookup) tpu_columns.append(column) return tpu_columns class _TPUEmbeddingColumnV2(_TPUBaseEmbeddingColumn, fc_lib.EmbeddingColumn): """Core Embedding Column.""" def __new__(cls, categorical_column, dimension, combiner='mean', initializer=None, max_sequence_length=0, learning_rate_fn=None, use_safe_embedding_lookup=True, bypass_scope_validation=False): del bypass_scope_validation # pylint: disable=redundant-keyword-arg return fc_lib.EmbeddingColumn.__new__( cls, categorical_column, dimension, combiner=combiner, initializer=initializer, ckpt_to_load_from=None, tensor_name_in_ckpt=None, max_norm=None, trainable=True, use_safe_embedding_lookup=use_safe_embedding_lookup) def __getnewargs__(self): return (self._tpu_categorical_column, self.dimension, self.combiner, self.initializer, self._max_sequence_length, self._learning_rate_fn, self.use_safe_embedding_lookup, self._bypass_scope_validation) def __deepcopy__(self, memo): return _TPUEmbeddingColumnV2( *(copy.deepcopy(a, memo) for a in self.__getnewargs__())) def __init__(self, categorical_column, dimension, combiner='mean', initializer=None, max_sequence_length=0, learning_rate_fn=None, use_safe_embedding_lookup=True, bypass_scope_validation=False): _TPUBaseEmbeddingColumn.__init__( self, categorical_column, max_sequence_length=max_sequence_length, learning_rate_fn=learning_rate_fn) self._key = None # If true, scope validation is skipped to allow the same column to be used # in multiple variable scopes. By default, this is False, and we expect a # 1:1 mapping between feature columns and scopes. self._bypass_scope_validation = bypass_scope_validation def get_combiner(self): return self.combiner def get_embedding_table_size(self): """Returns num_ids and width.""" return (self.categorical_column._num_buckets, self.dimension) def get_feature_key_name(self): """get_feature_key_name.""" if self.is_categorical_column_weighted(): return self.categorical_column.categorical_column.name return self.categorical_column.name def get_weight_key_name(self): """get_weight_key_name.""" if self.is_categorical_column_weighted(): return self.categorical_column.weight_feature_key return None def get_embedding_var_name(self): """get_embedding_var_name.""" return self.categorical_column.name def get_initializer(self): return self.initializer def is_categorical_column_weighted(self): """Check if the categorical column of the embedding column is weighted.""" if isinstance( self.categorical_column, ( fc._WeightedCategoricalColumn, # pylint: disable=protected-access fc_lib.WeightedCategoricalColumn)): return True return False def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): if tpu.under_tpu_inference_context(): def host_computation(): return fc_lib.EmbeddingColumn._get_dense_tensor( self, inputs, weight_collections, trainable) return tpu.outside_compilation(host_computation) if _is_running_on_cpu(): return fc_lib.EmbeddingColumn._get_dense_tensor( self, inputs, weight_collections, trainable) # TPU mode # Get the embeddings from the LazyBuilder. tensor = inputs.get(self.get_feature_key_name()) # Add to collection for _create_tpu_embedding_variables_and_ops _record_variable_scope_and_name( self.get_embedding_var_name(), 'embedding_weights', bypass_scope_validation=self._bypass_scope_validation) return tensor def create_state(self, state_manager): if _is_running_on_cpu(): return fc_lib.EmbeddingColumn.create_state( self, state_manager) # Create state is called for the EmbeddingColumn to create its embedding # variables under feature column V2, if we are on TPU so record the scope # here. _record_variable_scope_and_name( self.get_embedding_var_name(), 'embedding_weights', bypass_scope_validation=self._bypass_scope_validation) def get_dense_tensor(self, transformation_cache, state_manager): if tpu.under_tpu_inference_context(): def host_computation(): return fc_lib.EmbeddingColumn.get_dense_tensor( self, transformation_cache, state_manager) return tpu.outside_compilation(host_computation) if _is_running_on_cpu(): return fc_lib.EmbeddingColumn.get_dense_tensor( self, transformation_cache, state_manager) # TPU mode # Get the embeddings from the FeatureTransformationCache. tensor = transformation_cache.get(self.get_feature_key_name(), state_manager) return tensor def _get_sequence_dense_tensor( self, inputs, weight_collections=None, trainable=None): if tpu.under_tpu_inference_context(): def host_computation(): return fc_lib.EmbeddingColumn._get_sequence_dense_tensor( self, inputs, weight_collections, trainable) return tpu.outside_compilation(host_computation) if _is_running_on_cpu(): return fc_lib.EmbeddingColumn._get_sequence_dense_tensor( self, inputs, weight_collections, trainable) tensor = inputs.get(self.get_feature_key_name()) tensor_lengths = inputs.get(self.get_sequence_length_feature_key_name()) # inputs is a _LazyBuilder and for rank 1 tensors, it calls expand_dims(-1). # We need to undo this to match the standard CPU sequence embedding. tensor_lengths = array_ops.squeeze(tensor_lengths, -1) # Add to collection for _create_tpu_embedding_variables_and_ops _record_variable_scope_and_name( self.get_embedding_var_name(), 'embedding_weights', bypass_scope_validation=self._bypass_scope_validation) return fc_lib.SequenceDenseColumn.TensorSequenceLengthPair( dense_tensor=tensor, sequence_length=tensor_lengths) def get_sequence_dense_tensor(self, transformation_cache, state_manager): if tpu.under_tpu_inference_context(): def host_computation(): return fc_lib.EmbeddingColumn.get_sequence_dense_tensor( self, transformation_cache, state_manager) return tpu.outside_compilation(host_computation) if _is_running_on_cpu(): return fc_lib.EmbeddingColumn.get_sequence_dense_tensor( self, transformation_cache, state_manager) tensor = transformation_cache.get(self.get_feature_key_name(), state_manager) tensor_lengths = transformation_cache.get( self.get_sequence_length_feature_key_name(), state_manager) # FeatureTransformationCache expands rank 1 tensors (like sequence length) # to rank 2. We need to undo this to match the standard CPU sequence # embedding. tensor_lengths = array_ops.squeeze(tensor_lengths, -1) return fc_lib.SequenceDenseColumn.TensorSequenceLengthPair( dense_tensor=tensor, sequence_length=tensor_lengths) class _TPUSharedEmbeddingColumnV2(_TPUBaseEmbeddingColumn, fc_lib.SharedEmbeddingColumn): """Core Shared Embedding Column.""" def __new__(cls, categorical_column, shared_embedding_column_creator, combiner='mean', initializer=None, shared_embedding_collection_name=None, max_sequence_length=0, learning_rate_fn=None, use_safe_embedding_lookup=True): # pylint: disable=redundant-keyword-arg return fc_lib.SharedEmbeddingColumn.__new__( cls, categorical_column, combiner=combiner, shared_embedding_column_creator=shared_embedding_column_creator, max_norm=None, use_safe_embedding_lookup=use_safe_embedding_lookup) def __getnewargs__(self): return (self._tpu_categorical_column, self.shared_embedding_column_creator, self.combiner, self._initializer, self._shared_embedding_collection_name, self._max_sequence_length, self._learning_rate_fn) def __deepcopy__(self, memo): return _TPUSharedEmbeddingColumnV2( *(copy.deepcopy(a, memo) for a in self.__getnewargs__())) def __init__(self, categorical_column, shared_embedding_column_creator, combiner='mean', initializer=None, shared_embedding_collection_name=None, max_sequence_length=0, learning_rate_fn=None, use_safe_embedding_lookup=True): _TPUBaseEmbeddingColumn.__init__( self, categorical_column, max_sequence_length=max_sequence_length, learning_rate_fn=learning_rate_fn) self._initializer = initializer self._shared_embedding_collection_name = shared_embedding_collection_name def get_combiner(self): return self.combiner def get_embedding_table_size(self): """Returns num_ids and width.""" return (self.categorical_column._num_buckets, self.shared_embedding_column_creator.dimension) def get_feature_key_name(self): """get_feature_key_name.""" if self.is_categorical_column_weighted(): return self.categorical_column.categorical_column.name return self.categorical_column.name def get_weight_key_name(self): """get_weight_key_name.""" if self.is_categorical_column_weighted(): return self.categorical_column.weight_feature_key return None def get_embedding_var_name(self): """get_embedding_var_name.""" return self._shared_embedding_collection_name def get_initializer(self): return self._initializer def is_categorical_column_weighted(self): """Check if the categorical column of the embedding column is weighted.""" if isinstance( self.categorical_column, ( fc._WeightedCategoricalColumn, # pylint: disable=protected-access fc_lib.WeightedCategoricalColumn)): return True return False def _get_dense_tensor_internal( self, transformation_cache, state_manager): if tpu.under_tpu_inference_context(): def host_computation(): return fc_lib.SharedEmbeddingColumn._get_dense_tensor_internal( self, transformation_cache, state_manager) return tpu.outside_compilation(host_computation) if _is_running_on_cpu(): return fc_lib.SharedEmbeddingColumn._get_dense_tensor_internal( self, transformation_cache, state_manager) # TPU mode # Get the embeddings from the FeatureTransformationCache. tensor = transformation_cache.get(self.get_feature_key_name(), state_manager) # Add to collection for _create_tpu_embedding_variables_and_ops # Note that in Feature Column V2, shared embeddings have no scope. _record_variable_scope_and_name( self.get_embedding_var_name(), self.shared_embedding_column_creator._name, is_shared_embedding=True) return tensor def get_sequence_dense_tensor( self, transformation_cache, state_manager): if tpu.under_tpu_inference_context(): def host_computation(): return fc_lib.SharedEmbeddingColumn.get_sequence_dense_tensor( self, transformation_cache, state_manager) return tpu.outside_compilation(host_computation) if _is_running_on_cpu(): return fc_lib.SharedEmbeddingColumn.get_sequence_dense_tensor( self, transformation_cache, state_manager) tensor = self._get_dense_tensor_internal( transformation_cache, state_manager) tensor_lengths = transformation_cache.get( self.get_sequence_length_feature_key_name(), state_manager) # FeatureTransformationCache expands rank 1 tensors (like sequence length) # to rank 2. We need to undo this to match the standard CPU sequence # embedding. tensor_lengths = array_ops.squeeze(tensor_lengths, -1) return fc_lib.SequenceDenseColumn.TensorSequenceLengthPair( dense_tensor=tensor, sequence_length=tensor_lengths) def split_sequence_columns_v2(feature_columns): """Split a list of _TPUEmbeddingColumn into sequence and non-sequence columns. For use in a TPUEstimator model_fn function. E.g. def model_fn(features): sequence_columns, feature_columns = ( tf.tpu.feature_column.split_sequence_columns(feature_columns)) input = tf.feature_column.input_layer( features=features, feature_columns=feature_columns) sequence_features, sequence_lengths = ( tf.contrib.feature_column.sequence_input_layer( features=features, feature_columns=sequence_columns)) Args: feature_columns: A list of _TPUEmbeddingColumns to split. Returns: Two lists of _TPUEmbeddingColumns, the first is the sequence columns and the second is the non-sequence columns. """ sequence_columns = [] non_sequence_columns = [] for column in feature_columns: if not isinstance(column, (_TPUEmbeddingColumnV2, _TPUSharedEmbeddingColumnV2)): raise TypeError( 'column must be a _TPUEmbeddingColumnV2 or ' f'_TPUSharedEmbeddingColumnV2 but got {type(column)} instead.') if column.is_sequence_column(): sequence_columns.append(column) else: non_sequence_columns.append(column) return sequence_columns, non_sequence_columns def sparse_embedding_aggregate_slice(params, values_and_values_mask, combiner='mean', name='sparse_embedding_aggregate_slice'): """Uses XLA's dynamic slice operations to perform embedding lookups. From third_party/cloud_tpu/models/movielens/tpu_embedding.py Args: params: Tensor of embedding table. Rank 2 (table_size x embedding dim) values_and_values_mask: is a two-tuple that contains: values - Tensor of embedding indices. Rank 2 (batch x n_indices) values_mask - Tensor of mask / weights. Rank 2 (batch x n_indices) combiner: The combiner to use for the embedding lookup. Currently supports 'sum' and 'mean'. name: Optional name scope for created ops Returns: Rank 2 tensor of aggregated (per batch element) embedding vectors. Raises: ValueError: Combiner is not supported. """ values, values_mask = values_and_values_mask # unpack the two-tuple with ops.name_scope(name): _, embedding_dimension = params.get_shape().as_list() n_batch, n_indices_padded = values.get_shape().as_list() if not n_batch: n_batch = -1 emb_lookup = array_ops.reshape( embedding_ops.embedding_lookup( params, array_ops.reshape(values, [n_batch, n_indices_padded])), [n_batch, n_indices_padded, embedding_dimension]) values_mask_broadcast = array_ops.reshape(values_mask, [n_batch, n_indices_padded, 1]) aggregate_emb = math_ops.reduce_sum( emb_lookup * values_mask_broadcast, axis=1) if combiner == 'sum': return aggregate_emb elif combiner == 'mean': # In the case we have an empty row, both aggregate_emb and # math_ops.reduce_sum(values_mask_broadcast, axis=1) will be 0. Thus, # we can take max it with a non-zero value to prevent NaNs. Note that # math_ops.reduce_sum(values_mask_broadcast, axis=1) will have integer # values so 1.0 is the smallest value. return aggregate_emb / math_ops.maximum( math_ops.reduce_sum(values_mask_broadcast, axis=1), 1.0) else: raise ValueError('Dense TPU Embedding does not support combiner ' 'other than sum and mean.') def pad_sparse_embedding_lookup_indices(sparse_indices, padded_size): """Creates statically-sized Tensors containing indices and weights. From third_party/cloud_tpu/models/movielens/tpu_embedding.py Also computes sparse_indices.values % embedding_table_size, for equivalent functionality to sparse_column_with_integerized_feature. The returned padded weight Tensor also doubles as a mask indicating which values in the returned padded indices Tensor are indices versus padded zeros. Args: sparse_indices: SparseTensor of embedding lookup indices. padded_size: Number of columns of the returned Tensors. Indices which fall out of bounds will be truncated to the padded size. Returns: (sparse_indices.values padded to the specified size, a mask the same size as the returned padded values in which 0s indicate padded locations and 1s (or values from sparse_weights) indicate actual values) """ batch_size = sparse_indices.dense_shape[0] sparse_indices = sparse_ops.sparse_slice(sparse_indices, [0, 0], [batch_size, padded_size]) indices, values = sparse_indices.indices, sparse_indices.values padded_values = array_ops.scatter_nd( indices, math_ops.cast(values, dtypes.int32), shape=(batch_size, padded_size)) weights = array_ops.ones_like(values, dtype=dtypes.float32) padded_mask = array_ops.scatter_nd( indices, weights, shape=(batch_size, padded_size)) return padded_values, padded_mask def _check_invalid_cases(embedding_lookup_device): """Checks for invalid embedding_lookup_device configurations.""" if (tpu.under_tpu_inference_context() and embedding_lookup_device == EmbeddingDevice.TPU_EMBEDDING_CORE): raise ValueError( 'Using embedding_lookup_device=tpu_embedding_core during inference ' 'is not supported.') if embedding_lookup_device == EmbeddingDevice.CPU: if not tpu.under_tpu_inference_context(): raise ValueError( 'Using TPUEmbeddingColumn with embedding_lookup_device="cpu" ' 'during training is not supported.') class _TPUDeviceSpecificEmbeddingColumnV2(_TPUEmbeddingColumnV2): """TPUEmbeddingColumn which allows serving on TensorCore.""" def __new__(cls, *args, **kwargs): # For __new__, just capture the inference dense shape and call parent. if 'tensor_core_shape' in kwargs: cls._tensor_core_shape = kwargs['tensor_core_shape'] del kwargs['tensor_core_shape'] if 'embedding_lookup_device' in kwargs: cls._embedding_lookup_device = kwargs['embedding_lookup_device'] del kwargs['embedding_lookup_device'] return _TPUEmbeddingColumnV2.__new__(cls, *args, **kwargs) def __init__(self, *args, **kwargs): # For __init__, just capture the inference dense shape and call parent. if 'tensor_core_shape' in kwargs: self._tensor_core_shape = kwargs['tensor_core_shape'] del kwargs['tensor_core_shape'] if 'embedding_lookup_device' in kwargs: self._embedding_lookup_device = kwargs['embedding_lookup_device'] del kwargs['embedding_lookup_device'] _TPUEmbeddingColumnV2.__init__(self, *args, **kwargs) def __deepcopy__(self, memo): return _TPUDeviceSpecificEmbeddingColumnV2( *(copy.deepcopy(a, memo) for a in self.__getnewargs__()), tensor_core_shape=self._tensor_core_shape, embedding_lookup_device=self._embedding_lookup_device) def create_state(self, state_manager): _check_invalid_cases(self._embedding_lookup_device) # CPU case. is_cpu = self._embedding_lookup_device == EmbeddingDevice.CPU is_cpu = is_cpu or _is_running_on_cpu() if is_cpu: return fc_lib.EmbeddingColumn.create_state(self, state_manager) # TPU_EMBEDDING_CORE case. elif self._embedding_lookup_device == EmbeddingDevice.TPU_EMBEDDING_CORE: return super(_TPUDeviceSpecificEmbeddingColumnV2, self).create_state(state_manager) # TPU_EMBEDDING_CORE case. return fc_lib.EmbeddingColumn.create_state(self, state_manager) def get_dense_tensor(self, transformation_cache, state_manager): """Private method that follows get_dense_tensor.""" _check_invalid_cases(self._embedding_lookup_device) # CPU Case. is_cpu = self._embedding_lookup_device == EmbeddingDevice.CPU is_cpu = is_cpu or _is_running_on_cpu() if is_cpu: return super(_TPUDeviceSpecificEmbeddingColumnV2, self).get_dense_tensor(transformation_cache, state_manager) # TPU_EMBEDDING_CORE case. elif self._embedding_lookup_device == EmbeddingDevice.TPU_EMBEDDING_CORE: return super(_TPUDeviceSpecificEmbeddingColumnV2, self).get_dense_tensor(transformation_cache, state_manager) # TPU_EMBEDDING_CORE cases. if tpu.under_tpu_inference_context(): # For inference, use outside compile to densify and pad the input tensors. sparse_tensor = transformation_cache.get(self.categorical_column.name, state_manager) def host_computation(): return pad_sparse_embedding_lookup_indices(sparse_tensor, self._tensor_core_shape[1]) values, mask = tpu.outside_compilation(host_computation) else: # For training, the inputs should already have been densified and padded. values = transformation_cache.get(self.categorical_column.name, state_manager) mask = transformation_cache.get( self.categorical_column.name + _TENSOR_CORE_MASK_KEY_SUFFIX, state_manager) embedding_weights = state_manager.get_variable( self, name='embedding_weights') return sparse_embedding_aggregate_slice(embedding_weights, (values, mask), self.get_combiner()) def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): _check_invalid_cases(self._embedding_lookup_device) # CPU Case. is_cpu = self._embedding_lookup_device == EmbeddingDevice.CPU is_cpu = is_cpu or _is_running_on_cpu() if is_cpu: return super(_TPUDeviceSpecificEmbeddingColumnV2, self)._get_dense_tensor(inputs, weight_collections, trainable) # TPU_EMBEDDING_CORE case. elif self._embedding_lookup_device == EmbeddingDevice.TPU_EMBEDDING_CORE: return super(_TPUDeviceSpecificEmbeddingColumnV2, self)._get_dense_tensor(inputs, weight_collections, trainable) # TPU_EMBEDDING_CORE cases. if tpu.under_tpu_inference_context(): # For inference, use outside compile to densify and pad the input tensors. sparse_tensor = inputs.get(self.get_feature_key_name()) def host_computation(): return pad_sparse_embedding_lookup_indices(sparse_tensor, self._tensor_core_shape[1]) values, mask = tpu.outside_compilation(host_computation) else: # For training, the inputs should already have been densified and padded. values = inputs.get(self.get_feature_key_name()) mask = inputs.get(self.get_feature_key_name() + _TENSOR_CORE_MASK_KEY_SUFFIX) embedding_shape = (self.categorical_column._num_buckets, self.dimension) # pylint: disable=protected-access if (weight_collections and ops.GraphKeys.GLOBAL_VARIABLES not in weight_collections): weight_collections.append(ops.GraphKeys.GLOBAL_VARIABLES) embedding_weights = variable_scope.get_variable( name='embedding_weights', shape=embedding_shape, dtype=dtypes.float32, initializer=self.initializer, trainable=self.trainable and trainable, collections=weight_collections) return sparse_embedding_aggregate_slice(embedding_weights, (values, mask), self.get_combiner()) class _TPUSharedDeviceSpecificEmbeddingColumnV2(_TPUSharedEmbeddingColumnV2): """TPUSharedEmbeddingColumnV2 which allows serving on TensorCore.""" def __new__(cls, *args, **kwargs): # For __new__, just capture the inference dense shape and call parent. if 'tensor_core_shape' in kwargs: cls._tensor_core_shape = kwargs['tensor_core_shape'] del kwargs['tensor_core_shape'] if 'embedding_lookup_device' in kwargs: cls._embedding_lookup_device = kwargs['embedding_lookup_device'] del kwargs['embedding_lookup_device'] return _TPUSharedEmbeddingColumnV2.__new__(cls, *args, **kwargs) def __init__(self, *args, **kwargs): # For __init__, just capture the inference dense shape and call parent. if 'tensor_core_shape' in kwargs: self._tensor_core_shape = kwargs['tensor_core_shape'] del kwargs['tensor_core_shape'] if 'embedding_lookup_device' in kwargs: self._embedding_lookup_device = kwargs['embedding_lookup_device'] del kwargs['embedding_lookup_device'] _TPUSharedEmbeddingColumnV2.__init__(self, *args, **kwargs) def __deepcopy__(self, memo): return _TPUSharedDeviceSpecificEmbeddingColumnV2( *(copy.deepcopy(a, memo) for a in self.__getnewargs__()), tensor_core_shape=self._tensor_core_shape, embedding_lookup_device=self._embedding_lookup_device) def _get_dense_tensor_internal(self, transformation_cache, state_manager): """Private method that follows _get_dense_tensor_internal.""" _check_invalid_cases(self._embedding_lookup_device) # CPU Case. is_cpu = self._embedding_lookup_device == EmbeddingDevice.CPU is_cpu = is_cpu or _is_running_on_cpu() if is_cpu: return super(_TPUSharedDeviceSpecificEmbeddingColumnV2, self)._get_dense_tensor_internal(transformation_cache, state_manager) # TPU_EMBEDDING_CORE case. if self._embedding_lookup_device == EmbeddingDevice.TPU_EMBEDDING_CORE: return super(_TPUSharedDeviceSpecificEmbeddingColumnV2, self)._get_dense_tensor_internal(transformation_cache, state_manager) # TPU_EMBEDDING_CORE cases. if tpu.under_tpu_inference_context(): # For inference, use outside compile to densify and pad the input tensors. sparse_tensor = transformation_cache.get(self.categorical_column.name, state_manager) def host_computation(): return pad_sparse_embedding_lookup_indices(sparse_tensor, self._tensor_core_shape[1]) values, mask = tpu.outside_compilation(host_computation) else: # For training, the inputs should already have been densified and padded. values = transformation_cache.get(self.categorical_column.name, state_manager) mask = transformation_cache.get( self.categorical_column.name + _TENSOR_CORE_MASK_KEY_SUFFIX, state_manager) # Do a dense embedding lookup on TensorCore. embedding_weights = self.shared_embedding_column_creator.embedding_weights return sparse_embedding_aggregate_slice(embedding_weights, (values, mask), self.get_combiner())
from django.db import IntegrityError from django.db.models import ProtectedError, Q, Sum from django.forms.models import modelform_factory from django.test import TestCase, skipIfDBFeature from .models import ( A, Address, B, Board, C, Cafe, CharLink, Company, Contact, Content, D, Developer, Guild, HasLinkThing, Link, Node, Note, OddRelation1, OddRelation2, Organization, Person, Place, Related, Restaurant, Tag, Team, TextLink, ) class GenericRelationTests(TestCase): def test_inherited_models_content_type(self): """ GenericRelations on inherited classes use the correct content type. """ p = Place.objects.create(name="South Park") r = Restaurant.objects.create(name="Chubby's") l1 = Link.objects.create(content_object=p) l2 = Link.objects.create(content_object=r) self.assertEqual(list(p.links.all()), [l1]) self.assertEqual(list(r.links.all()), [l2]) def test_reverse_relation_pk(self): """ The correct column name is used for the primary key on the originating model of a query. See #12664. """ p = Person.objects.create(account=23, name='Chef') Address.objects.create(street='123 Anywhere Place', city='Conifer', state='CO', zipcode='80433', content_object=p) qs = Person.objects.filter(addresses__zipcode='80433') self.assertEqual(1, qs.count()) self.assertEqual('Chef', qs[0].name) def test_charlink_delete(self): oddrel = OddRelation1.objects.create(name='clink') CharLink.objects.create(content_object=oddrel) oddrel.delete() def test_textlink_delete(self): oddrel = OddRelation2.objects.create(name='tlink') TextLink.objects.create(content_object=oddrel) oddrel.delete() def test_coerce_object_id_remote_field_cache_persistence(self): restaurant = Restaurant.objects.create() CharLink.objects.create(content_object=restaurant) charlink = CharLink.objects.latest('pk') self.assertIs(charlink.content_object, charlink.content_object) # If the model (Cafe) uses more than one level of multi-table inheritance. cafe = Cafe.objects.create() CharLink.objects.create(content_object=cafe) charlink = CharLink.objects.latest('pk') self.assertIs(charlink.content_object, charlink.content_object) def test_q_object_or(self): """ SQL query parameters for generic relations are properly grouped when OR is used (#11535). In this bug the first query (below) works while the second, with the query parameters the same but in reverse order, does not. The issue is that the generic relation conditions do not get properly grouped in parentheses. """ note_contact = Contact.objects.create() org_contact = Contact.objects.create() Note.objects.create(note='note', content_object=note_contact) org = Organization.objects.create(name='org name') org.contacts.add(org_contact) # search with a non-matching note and a matching org name qs = Contact.objects.filter(Q(notes__note__icontains=r'other note') | Q(organizations__name__icontains=r'org name')) self.assertIn(org_contact, qs) # search again, with the same query parameters, in reverse order qs = Contact.objects.filter( Q(organizations__name__icontains=r'org name') | Q(notes__note__icontains=r'other note')) self.assertIn(org_contact, qs) def test_join_reuse(self): qs = Person.objects.filter( addresses__street='foo' ).filter( addresses__street='bar' ) self.assertEqual(str(qs.query).count('JOIN'), 2) def test_generic_relation_ordering(self): """ Ordering over a generic relation does not include extraneous duplicate results, nor excludes rows not participating in the relation. """ p1 = Place.objects.create(name="South Park") p2 = Place.objects.create(name="The City") c = Company.objects.create(name="Chubby's Intl.") Link.objects.create(content_object=p1) Link.objects.create(content_object=c) places = list(Place.objects.order_by('links__id')) def count_places(place): return len([p for p in places if p.id == place.id]) self.assertEqual(len(places), 2) self.assertEqual(count_places(p1), 1) self.assertEqual(count_places(p2), 1) def test_target_model_is_unsaved(self): """Test related to #13085""" # Fails with another, ORM-level error dev1 = Developer(name='Joe') note = Note(note='Deserves promotion', content_object=dev1) with self.assertRaises(IntegrityError): note.save() def test_target_model_len_zero(self): """ Saving a model with a GenericForeignKey to a model instance whose __len__ method returns 0 (Team.__len__() here) shouldn't fail (#13085). """ team1 = Team.objects.create(name='Backend devs') note = Note(note='Deserve a bonus', content_object=team1) note.save() def test_target_model_bool_false(self): """ Saving a model with a GenericForeignKey to a model instance whose __bool__ method returns False (Guild.__bool__() here) shouldn't fail (#13085). """ g1 = Guild.objects.create(name='First guild') note = Note(note='Note for guild', content_object=g1) note.save() @skipIfDBFeature('interprets_empty_strings_as_nulls') def test_gfk_to_model_with_empty_pk(self): """Test related to #13085""" # Saving model with GenericForeignKey to model instance with an # empty CharField PK b1 = Board.objects.create(name='') tag = Tag(label='VP', content_object=b1) tag.save() def test_ticket_20378(self): # Create a couple of extra HasLinkThing so that the autopk value # isn't the same for Link and HasLinkThing. hs1 = HasLinkThing.objects.create() hs2 = HasLinkThing.objects.create() hs3 = HasLinkThing.objects.create() hs4 = HasLinkThing.objects.create() l1 = Link.objects.create(content_object=hs3) l2 = Link.objects.create(content_object=hs4) self.assertSequenceEqual(HasLinkThing.objects.filter(links=l1), [hs3]) self.assertSequenceEqual(HasLinkThing.objects.filter(links=l2), [hs4]) self.assertSequenceEqual(HasLinkThing.objects.exclude(links=l2), [hs1, hs2, hs3]) self.assertSequenceEqual(HasLinkThing.objects.exclude(links=l1), [hs1, hs2, hs4]) def test_ticket_20564(self): b1 = B.objects.create() b2 = B.objects.create() b3 = B.objects.create() c1 = C.objects.create(b=b1) c2 = C.objects.create(b=b2) c3 = C.objects.create(b=b3) A.objects.create(flag=None, content_object=b1) A.objects.create(flag=True, content_object=b2) self.assertSequenceEqual(C.objects.filter(b__a__flag=None), [c1, c3]) self.assertSequenceEqual(C.objects.exclude(b__a__flag=None), [c2]) def test_ticket_20564_nullable_fk(self): b1 = B.objects.create() b2 = B.objects.create() b3 = B.objects.create() d1 = D.objects.create(b=b1) d2 = D.objects.create(b=b2) d3 = D.objects.create(b=b3) d4 = D.objects.create() A.objects.create(flag=None, content_object=b1) A.objects.create(flag=True, content_object=b1) A.objects.create(flag=True, content_object=b2) self.assertSequenceEqual(D.objects.exclude(b__a__flag=None), [d2]) self.assertSequenceEqual(D.objects.filter(b__a__flag=None), [d1, d3, d4]) self.assertSequenceEqual(B.objects.filter(a__flag=None), [b1, b3]) self.assertSequenceEqual(B.objects.exclude(a__flag=None), [b2]) def test_extra_join_condition(self): # A crude check that content_type_id is taken in account in the # join/subquery condition. self.assertIn("content_type_id", str(B.objects.exclude(a__flag=None).query).lower()) # No need for any joins - the join from inner query can be trimmed in # this case (but not in the above case as no a objects at all for given # B would then fail). self.assertNotIn(" join ", str(B.objects.exclude(a__flag=True).query).lower()) self.assertIn("content_type_id", str(B.objects.exclude(a__flag=True).query).lower()) def test_annotate(self): hs1 = HasLinkThing.objects.create() hs2 = HasLinkThing.objects.create() HasLinkThing.objects.create() b = Board.objects.create(name=str(hs1.pk)) Link.objects.create(content_object=hs2) link = Link.objects.create(content_object=hs1) Link.objects.create(content_object=b) qs = HasLinkThing.objects.annotate(Sum('links')).filter(pk=hs1.pk) # If content_type restriction isn't in the query's join condition, # then wrong results are produced here as the link to b will also match # (b and hs1 have equal pks). self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].links__sum, link.id) link.delete() # Now if we don't have proper left join, we will not produce any # results at all here. # clear cached results qs = qs.all() self.assertEqual(qs.count(), 1) # Note - 0 here would be a nicer result... self.assertIs(qs[0].links__sum, None) # Finally test that filtering works. self.assertEqual(qs.filter(links__sum__isnull=True).count(), 1) self.assertEqual(qs.filter(links__sum__isnull=False).count(), 0) def test_filter_targets_related_pk(self): # Use hardcoded PKs to ensure different PKs for "link" and "hs2" # objects. HasLinkThing.objects.create(pk=1) hs2 = HasLinkThing.objects.create(pk=2) link = Link.objects.create(content_object=hs2, pk=1) self.assertNotEqual(link.object_id, link.pk) self.assertSequenceEqual(HasLinkThing.objects.filter(links=link.pk), [hs2]) def test_editable_generic_rel(self): GenericRelationForm = modelform_factory(HasLinkThing, fields='__all__') form = GenericRelationForm() self.assertIn('links', form.fields) form = GenericRelationForm({'links': None}) self.assertTrue(form.is_valid()) form.save() links = HasLinkThing._meta.get_field('links') self.assertEqual(links.save_form_data_calls, 1) def test_ticket_22998(self): related = Related.objects.create() content = Content.objects.create(related_obj=related) Node.objects.create(content=content) # deleting the Related cascades to the Content cascades to the Node, # where the pre_delete signal should fire and prevent deletion. with self.assertRaises(ProtectedError): related.delete() def test_ticket_22982(self): place = Place.objects.create(name='My Place') self.assertIn('GenericRelatedObjectManager', str(place.links)) def test_filter_on_related_proxy_model(self): place = Place.objects.create() Link.objects.create(content_object=place) self.assertEqual(Place.objects.get(link_proxy__object_id=place.id), place) def test_generic_reverse_relation_with_mti(self): """ Filtering with a reverse generic relation, where the GenericRelation comes from multi-table inheritance. """ place = Place.objects.create(name='Test Place') link = Link.objects.create(content_object=place) result = Link.objects.filter(places=place) self.assertCountEqual(result, [link]) def test_generic_reverse_relation_with_abc(self): """ The reverse generic relation accessor (targets) is created if the GenericRelation comes from an abstract base model (HasLinks). """ thing = HasLinkThing.objects.create() link = Link.objects.create(content_object=thing) self.assertCountEqual(link.targets.all(), [thing])
import StringIO import json import logging import random import urllib import urllib2 import random from json import loads from time import strptime, localtime import time import datetime from datetime import date, timedelta if __import__('sys').version_info[0] == 2: from urllib2 import urlopen else: from urllib.request import urlopen # for sending images from PIL import Image import multipart # standard app engine imports from google.appengine.api import urlfetch from google.appengine.ext import ndb import webapp2 TOKEN = 'Enter Token here' BASE_URL = 'https://api.telegram.org/bot' + TOKEN + '/' # ================================ class EnableStatus(ndb.Model): # key name: str(chat_id) enabled = ndb.BooleanProperty(indexed=False, default=False) # ================================ def setEnabled(chat_id, yes): es = EnableStatus.get_or_insert(str(chat_id)) es.enabled = yes es.put() def getEnabled(chat_id): es = EnableStatus.get_by_id(str(chat_id)) if es: return es.enabled return False # ================================ class MeHandler(webapp2.RequestHandler): def get(self): urlfetch.set_default_fetch_deadline(60) self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'getMe')))) class GetUpdatesHandler(webapp2.RequestHandler): def get(self): urlfetch.set_default_fetch_deadline(60) self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'getUpdates')))) class SetWebhookHandler(webapp2.RequestHandler): def get(self): urlfetch.set_default_fetch_deadline(60) url = self.request.get('url') if url: self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'setWebhook', urllib.urlencode({'url': url}))))) class WebhookHandler(webapp2.RequestHandler): def post(self): urlfetch.set_default_fetch_deadline(60) body = json.loads(self.request.body) logging.info('request body:') logging.info(body) self.response.write(json.dumps(body)) update_id = body['update_id'] message = body['message'] message_id = message.get('message_id') date = message.get('date') text = message.get('text') fr = message.get('from') chat = message['chat'] chat_id = chat['id'] if not text: logging.info('no text') return def reply(msg=None, img=None): if msg: resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({ 'chat_id': str(chat_id), 'text': msg, 'disable_web_page_preview': 'true', 'reply_to_message_id': str(message_id), })).read() elif img: resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [ ('chat_id', str(chat_id)), ('reply_to_message_id', str(message_id)), ], [ ('photo', 'image.jpg', img), ]) else: logging.error('no msg or img specified') resp = None logging.info('send response:') logging.info(resp) if text.startswith('/'): if text == '/start': reply('Bot enabled') setEnabled(chat_id, True) elif text == '/stop': reply('Bot disabled') setEnabled(chat_id, False) elif text == '/today': todayEvents = [] req = urlopen("http ://adigov. stud.if .ktu.lt/wordpress/?json=1".replace(' ', '')+'?'+str(random.random())) content = req.read().decode("utf-8") jsonObj = loads(content) if jsonObj["status"] and jsonObj["status"] == "ok": posts = jsonObj["posts"] if posts: for post in posts: if post["categories"] and len(post["categories"]) > 0: category = post["categories"][0] parseTime = strptime(category["title"], "%m/%d/%Y") today = localtime() # Far shorter. :P if parseTime[:3] == today[:3]: todayEvents.append(post["title"]) def concateEvents(todayEventsarg): if len(todayEventsarg) == 1: return ("Today there is one event:\n {0}".format(todayEventsarg[0])) elif len(todayEventsarg) > 1: concatString = "Today there are the following events:" for i in range(len(todayEventsarg)): concatString = "{0}\n{1}. {2}".format(concatString, (i+1), todayEventsarg[i]) return concatString else: return "There are no Events today" reply(concateEvents(todayEvents)) elif text == '/about': reply('KTUeventBot : A simple free chat messenger bot to keep you updated on all events at KTU.\n\nKTUeventbot Version : 1 Release : 2\n\nSource code is availabe and open source on Github, type "/source" as command.\n\nCredits :GAE, Members of HF, Nathaniel, Steven, Yukuku(Telebot starter Kit), StackOverFlow, My dear friend Hilko.') elif text == '/week': eventdaysofthisweek = [] one_day = datetime.timedelta(days=1) def get_week(date): #"""Return the full week (Sunday first) of the week containing the given date. #'date' may be a datetime or date instance (the same type is returned). #""" day_idx = (date.weekday() + 1) % 7 # turn sunday into 0, monday into 1, etc. sunday = date - datetime.timedelta(days=day_idx) date = sunday for n in xrange(7): yield date date += one_day a = list(get_week(datetime.datetime.now().date())) b = [d.isoformat() for d in get_week(datetime.datetime.now().date())] daysofthisweek = [] daysofthisweek = b for i in daysofthisweek: parsedate = strptime(i, "%Y-%m-%d") req = urlopen("http ://adigov. stud.if .ktu.lt/wordpress/?json=1".replace(' ', '')+'?'+str(random.random())) content = req.read().decode("utf-8") jsonObj = loads(content) if jsonObj["status"] and jsonObj["status"] == "ok": posts = jsonObj["posts"] if posts: for post in posts: if post["categories"] and len(post["categories"]) > 0: category = post["categories"][0] parseTime = strptime(category["title"], "%m/%d/%Y") if parseTime == parsedate: eventdaysofthisweek.append(post["title"]+" ("+(category["title"]+")")) def concateweekEvents(eventdaysofthisweek): if len(eventdaysofthisweek) == 1: return ("Today there is one event this week:\n {0}".format(eventdaysofthisweek[0])) elif len(eventdaysofthisweek) > 1: concatweekString = "This week there are the following events:" for i in range(len(eventdaysofthisweek)): concatweekString = "{0}\n{1}. {2}".format(concatweekString, (i+1), eventdaysofthisweek[i]) return concatweekString else: return "There are no Events this week" reply(concateweekEvents(eventdaysofthisweek)) elif text == '/month': eventdaysofthismonth = [] year = int(time.strftime("%Y")) month = int(time.strftime("%m")) date1 = datetime.date(year, month, 1) if month+1 > 12: date2 = datetime.date(year+1, 1, 1) else: date2 = datetime.date(year, month+1, 1) delta = date2 - date1 monthdays = ["{:%d/%m/%Y}".format(date1 + datetime.timedelta(days=i)) for i in range(delta.days)] for i in monthdays: parsemonth = strptime(i, "%d/%m/%Y") req = urlopen("http ://adigov. stud.if .ktu.lt/wordpress/?json=1".replace(' ', '')+'?'+str(random.random())) content = req.read().decode("utf-8") jsonObj = loads(content) if jsonObj["status"] and jsonObj["status"] == "ok": posts = jsonObj["posts"] if posts: for post in posts: if post["categories"] and len(post["categories"]) > 0: category = post["categories"][0] parseTime = strptime(category["title"], "%m/%d/%Y") if parseTime == parsemonth: eventdaysofthismonth.append(post["title"]+" ("+(category["title"])+")") def concatemonthEvents(eventdaysofthismonth): if len(eventdaysofthismonth) == 1: return ("Today there is one event this month:\n {0}".format(eventdaysofthismonth[0])) elif len(eventdaysofthismonth) > 1: concatmonthString = "This month there are the following events:" for i in range(len(eventdaysofthismonth)): concatmonthString = "{0}\n{1}. {2}".format(concatmonthString, (i+1), eventdaysofthismonth[i]) return concatmonthString else: return "There are no Events this month" reply(concatemonthEvents(eventdaysofthismonth)) elif text == '/image': img = Image.new('RGB', (512, 512)) base = random.randint(0, 16777216) pixels = [base+i*j for i in range(512) for j in range(512)] # generate sample image img.putdata(pixels) output = StringIO.StringIO() img.save(output, 'JPEG') reply(img=output.getvalue()) elif text == '/source': reply('www.goo.gl/O3wZtD') else: reply('What command?') # CUSTOMIZE FROM HERE elif 'who are you' in text: reply('telegrambot') elif 'who invented you' in text: reply('My creator is Adithya :)') elif 'Who invented you' in text: reply('My creator is Adithya :)He is my god') elif 'what time' in text: reply('look at the top-right corner of your screen!') else: if getEnabled(chat_id): try: resp1 = json.load(urllib2.urlopen('http://www.simsimi.com/requestChat?lc=en&ft=1.0&req=' + urllib.quote_plus(text.encode('utf-8')))) back = resp1.get('res').get('msg') except urllib2.HTTPError, err: logging.error(err) back = str(err) if not back: reply('okay...') elif 'I HAVE NO RESPONSE' in back: reply('you said something with no meaning') else: reply(back) else: logging.info('not enabled for chat_id {}'.format(chat_id)) app = webapp2.WSGIApplication([ ('/me', MeHandler), ('/updates', GetUpdatesHandler), ('/set_webhook', SetWebhookHandler), ('/webhook', WebhookHandler), ], debug=True)
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/user.ui' # # Created: Mon Aug 31 11:36:01 2015 # by: PyQt4 UI code generator 4.11.1 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName(_fromUtf8("Dialog")) Dialog.resize(457, 269) Dialog.setStyleSheet(_fromUtf8("QPushButton{ \n" " background-color: rgb(255, 255, 255);\n" " border-style: outset;\n" " border-width: 1px;\n" " border-radius: 6px;\n" " border-color: rgb(193, 193, 193);\n" " border-style: solid;\n" " padding: 2px;\n" " min-width: 44px;\n" " min-height: 44px;\n" " \n" "}\n" "QPushButton:default{ \n" " background-color: rgb(48, 131, 251);\n" " color: rgb(255, 255, 255);\n" " border-width: 1px;\n" " border-radius: 6px;\n" " border-color: rgb(193, 193, 193);\n" " border-style: solid;\n" " padding: 2px;\n" " min-width: 44px;\n" " min-height: 44px;\n" "}\n" "\n" "QPushButton:pressed { \n" " border-style: solid;\n" " border-width: 1px;\n" " border-radius: 6px;\n" " background-color: rgb(48, 131, 251);\n" " color: rgb(255, 255, 255);\n" " min-width: 44px;\n" " min-height: 44px;\n" "}\n" "\n" "QPushButton:hover{\n" " border-color: rgb(164, 205, 255);\n" " border-radius: 6px;\n" " border-width: 3px;\n" " border-style: solid;\n" " min-width: 44px;\n" " min-height: 44px;\n" "}\n" "\n" "QToolButton:checked{ \n" " border-color: rgb(48, 131, 251);\n" " color: rgb(0, 0, 0);\n" " border-width: 3px;\n" " border-radius: 6px;\n" " background-color: rgb(255, 255, 255);\n" " border-style: solid;\n" " padding: 2px;\n" "}\n" "QToolButton{ \n" " background-color: rgb(255, 255, 255);\n" " border-style: outset;\n" " border-width: 1px;\n" " border-radius: 6px;\n" " border-color: rgb(193, 193, 193);\n" " border-style: solid;\n" " padding: 6px;\n" " \n" "}\n" "QToolButton:pressed { \n" " border-style: solid;\n" " border-width: 1px;\n" " border-radius: 6px;\n" " background-color: rgb(48, 131, 251);\n" " color: rgb(255, 255, 255);\n" "}\n" "\n" "QToolButton:hover{\n" " border-color: rgb(164, 205, 255);\n" " border-radius: 6px;\n" " border-width: 3px;\n" " border-style: solid;\n" "}")) self.gridLayout = QtGui.QGridLayout(Dialog) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.label = QtGui.QLabel(Dialog) font = QtGui.QFont() font.setPointSize(14) self.label.setFont(font) self.label.setObjectName(_fromUtf8("label")) self.gridLayout.addWidget(self.label, 2, 0, 1, 1) self.label_2 = QtGui.QLabel(Dialog) font = QtGui.QFont() font.setPointSize(14) self.label_2.setFont(font) self.label_2.setObjectName(_fromUtf8("label_2")) self.gridLayout.addWidget(self.label_2, 3, 0, 1, 1) self.user = QtGui.QLineEdit(Dialog) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.user.sizePolicy().hasHeightForWidth()) self.user.setSizePolicy(sizePolicy) self.user.setEchoMode(QtGui.QLineEdit.Normal) self.user.setObjectName(_fromUtf8("user")) self.gridLayout.addWidget(self.user, 2, 1, 1, 1) self.password = QtGui.QLineEdit(Dialog) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.password.sizePolicy().hasHeightForWidth()) self.password.setSizePolicy(sizePolicy) self.password.setEchoMode(QtGui.QLineEdit.Password) self.password.setObjectName(_fromUtf8("password")) self.gridLayout.addWidget(self.password, 3, 1, 1, 1) self.teamLeaderProfile = QtGui.QToolButton(Dialog) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.teamLeaderProfile.sizePolicy().hasHeightForWidth()) self.teamLeaderProfile.setSizePolicy(sizePolicy) self.teamLeaderProfile.setMinimumSize(QtCore.QSize(135, 135)) font = QtGui.QFont() font.setPointSize(14) self.teamLeaderProfile.setFont(font) self.teamLeaderProfile.setStyleSheet(_fromUtf8("")) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/user")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.teamLeaderProfile.setIcon(icon) self.teamLeaderProfile.setIconSize(QtCore.QSize(90, 100)) self.teamLeaderProfile.setCheckable(True) self.teamLeaderProfile.setAutoExclusive(True) self.teamLeaderProfile.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon) self.teamLeaderProfile.setObjectName(_fromUtf8("teamLeaderProfile")) self.buttonGroup = QtGui.QButtonGroup(Dialog) self.buttonGroup.setObjectName(_fromUtf8("buttonGroup")) self.buttonGroup.addButton(self.teamLeaderProfile) self.gridLayout.addWidget(self.teamLeaderProfile, 0, 0, 1, 1) self.operatorProfile = QtGui.QToolButton(Dialog) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.operatorProfile.sizePolicy().hasHeightForWidth()) self.operatorProfile.setSizePolicy(sizePolicy) self.operatorProfile.setMinimumSize(QtCore.QSize(135, 135)) font = QtGui.QFont() font.setPointSize(14) self.operatorProfile.setFont(font) self.operatorProfile.setIcon(icon) self.operatorProfile.setIconSize(QtCore.QSize(90, 100)) self.operatorProfile.setCheckable(True) self.operatorProfile.setChecked(True) self.operatorProfile.setAutoExclusive(True) self.operatorProfile.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon) self.operatorProfile.setObjectName(_fromUtf8("operatorProfile")) self.buttonGroup.addButton(self.operatorProfile) self.gridLayout.addWidget(self.operatorProfile, 0, 1, 1, 1) self.infieldProfile = QtGui.QToolButton(Dialog) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.infieldProfile.sizePolicy().hasHeightForWidth()) self.infieldProfile.setSizePolicy(sizePolicy) self.infieldProfile.setMinimumSize(QtCore.QSize(135, 135)) font = QtGui.QFont() font.setPointSize(14) self.infieldProfile.setFont(font) self.infieldProfile.setStyleSheet(_fromUtf8("")) self.infieldProfile.setIcon(icon) self.infieldProfile.setIconSize(QtCore.QSize(90, 100)) self.infieldProfile.setCheckable(True) self.infieldProfile.setAutoExclusive(True) self.infieldProfile.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon) self.infieldProfile.setObjectName(_fromUtf8("infieldProfile")) self.buttonGroup.addButton(self.infieldProfile) self.gridLayout.addWidget(self.infieldProfile, 0, 3, 1, 1) self.loginButton = QtGui.QPushButton(Dialog) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.loginButton.sizePolicy().hasHeightForWidth()) self.loginButton.setSizePolicy(sizePolicy) self.loginButton.setMinimumSize(QtCore.QSize(50, 50)) self.loginButton.setDefault(True) self.loginButton.setObjectName(_fromUtf8("loginButton")) self.gridLayout.addWidget(self.loginButton, 4, 3, 1, 1) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): Dialog.setWindowTitle(_translate("Dialog", "User Profile", None)) self.label.setText(_translate("Dialog", "User", None)) self.label_2.setText(_translate("Dialog", "Password", None)) self.teamLeaderProfile.setText(_translate("Dialog", "Team Leader", None)) self.operatorProfile.setText(_translate("Dialog", "Operator", None)) self.infieldProfile.setText(_translate("Dialog", "Infield Responder", None)) self.loginButton.setText(_translate("Dialog", "Login", None)) import resources_rc if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) Dialog = QtGui.QDialog() ui = Ui_Dialog() ui.setupUi(Dialog) Dialog.show() sys.exit(app.exec_())
# Copyright 2017 Veritas Technologies LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Unit tests for Veritas Manila driver. """ import hashlib import json import mock from oslo_config import cfg import requests import six from manila import context from manila import exception from manila.share import configuration as conf from manila.share.drivers.veritas import veritas_isa from manila import test CONF = cfg.CONF FAKE_BACKEND = 'fake_backend' class MockResponse(object): def __init__(self): self.status_code = 200 def json(self): data = {'fake_key': 'fake_val'} return json.dumps(data) class ACCESSShareDriverTestCase(test.TestCase): """Tests ACCESSShareDriver.""" share = { 'id': 'fakeid', 'name': 'fakename', 'size': 1, 'share_proto': 'NFS', 'export_locations': [{'path': '10.20.30.40:/vx/fake_location'}], 'snapshot_id': False } share2 = { 'id': 'fakeid2', 'name': 'fakename2', 'size': 4, 'share_proto': 'NFS', } share3 = { 'id': 'fakeid3', 'name': 'fakename3', 'size': 2, 'share_proto': 'NFS', 'export_location': '/vx/fake_location', 'snapshot_id': True } snapshot = { 'id': 'fakesnapshotid', 'share_name': 'fakename', 'share_id': 'fakeid', 'name': 'fakesnapshotname', 'share_size': 1, 'share_proto': 'NFS', 'snapshot_id': 'fake_snap_id', } access = { 'id': 'fakeaccid', 'access_type': 'ip', 'access_to': '10.0.0.2', 'access_level': 'rw', 'state': 'active', } access2 = { 'id': 'fakeaccid2', 'access_type': 'user', 'access_to': '10.0.0.3', 'access_level': 'rw', 'state': 'active', } access3 = { 'id': 'fakeaccid3', 'access_type': 'ip', 'access_to': '10.0.0.4', 'access_level': 'rw+', 'state': 'active', } access4 = { 'id': 'fakeaccid', 'access_type': 'ip', 'access_to': '10.0.0.2', 'access_level': 'ro', 'state': 'active', } def setUp(self): super(ACCESSShareDriverTestCase, self).setUp() self._create_fake_config() lcfg = self.configuration self._context = context.get_admin_context() self._driver = veritas_isa.ACCESSShareDriver(False, configuration=lcfg) self._driver.do_setup(self._context) def _create_fake_config(self): def _safe_get(opt): return getattr(self.configuration, opt) self.mock_object(veritas_isa.ACCESSShareDriver, '_authenticate_access') self.configuration = mock.Mock(spec=conf.Configuration) self.configuration.safe_get = mock.Mock(side_effect=_safe_get) self.configuration.va_server_ip = '1.1.1.1' self.configuration.va_pool = 'pool1' self.configuration.va_user = 'user' self.configuration.va_pwd = 'passwd' self.configuration.va_port = 14161 self.configuration.va_ssl = 'False' self.configuration.va_fstype = 'simple' self.configuration.network_config_group = 'fake_network_config_group' self.configuration.admin_network_config_group = ( 'fake_admin_network_config_group') self.configuration.driver_handles_share_servers = False self.configuration.share_backend_name = FAKE_BACKEND self.configuration.replication_domain = 'Disable' self.configuration.filter_function = 'Disable' self.configuration.goodness_function = 'Disable' def test_create_share(self): self.mock_object(self._driver, '_get_va_share_name') self.mock_object(self._driver, '_get_va_share_path') self.mock_object(self._driver, '_get_vip') self.mock_object(self._driver, '_access_api') length = len(self.share['name']) index = int(length / 2) name1 = self.share['name'][:index] name2 = self.share['name'][index:] crc1 = hashlib.md5(name1.encode('utf-8')).hexdigest()[:8] crc2 = hashlib.md5(name2.encode('utf-8')).hexdigest()[:8] share_name_to_ret = crc1 + '-' + crc2 share_path_to_ret = '/vx/' + crc1 + '-' + crc2 self._driver._get_va_share_name.return_value = share_name_to_ret self._driver._get_va_share_path.return_value = share_path_to_ret self._driver._get_vip.return_value = '1.1.1.1' self._driver.create_share(self._context, self.share) self.assertEqual(1, self._driver._get_vip.call_count) self.assertEqual(1, self._driver._get_va_share_name.call_count) self.assertEqual(1, self._driver._get_va_share_path.call_count) def test_create_share_negative(self): self.mock_object(self._driver, '_access_api') self._driver._access_api.return_value = False self.assertRaises(exception.ShareBackendException, self._driver.create_share, self._context, self.share) def test_create_share_from_snapshot(self): self.mock_object(self._driver, '_get_vip') sharename = self._driver._get_va_share_name( self.snapshot['share_name']) snapname = self._driver._get_va_snap_name(self.snapshot['name']) sharepath = self._driver._get_va_share_path(sharename) self._driver._get_vip.return_value = '1.1.1.1' vip = self._driver._get_vip() location = (six.text_type(vip) + ':' + six.text_type(sharepath) + ':' + six.text_type(snapname)) ret = self._driver.create_share_from_snapshot(self._context, self.share, self.snapshot) self.assertEqual(location, ret) def test_delete_share(self): self.mock_object(self._driver, '_access_api') self.mock_object(self._driver, '_does_item_exist_at_va_backend') self._driver._does_item_exist_at_va_backend.return_value = True self._driver.delete_share(self._context, self.share) self.assertEqual(2, self._driver._access_api.call_count) def test_delete_share_negative(self): self.mock_object(self._driver, '_access_api') self.mock_object(self._driver, '_does_item_exist_at_va_backend') self._driver._does_item_exist_at_va_backend.return_value = True self._driver._access_api.return_value = False self.assertRaises(exception.ShareBackendException, self._driver.delete_share, self._context, self.share) def test_delete_share_if_share_created_from_snap(self): self.mock_object(self._driver, '_access_api') self.mock_object(self._driver, '_does_item_exist_at_va_backend') self._driver.delete_share(self._context, self.share3) self.assertEqual(0, (self._driver. _does_item_exist_at_va_backend.call_count)) self.assertEqual(0, self._driver._access_api.call_count) def test_delete_share_if_not_present_at_backend(self): self.mock_object(self._driver, '_does_item_exist_at_va_backend') self.mock_object(self._driver, '_access_api') self._driver._does_item_exist_at_va_backend.return_value = False self._driver.delete_share(self._context, self.share) self.assertEqual(1, (self._driver. _does_item_exist_at_va_backend.call_count)) self.assertEqual(0, self._driver._access_api.call_count) def test_create_snapshot(self): self.mock_object(self._driver, '_access_api') self._driver.create_snapshot(self._context, self.snapshot) self.assertEqual(2, self._driver._access_api.call_count) def test_create_snapshot_negative(self): self.mock_object(self._driver, '_access_api') self._driver._access_api.return_value = False self.assertRaises(exception.ShareBackendException, self._driver.create_snapshot, self._context, self.snapshot) def test_delete_snapshot(self): self.mock_object(self._driver, '_access_api') self.mock_object(self._driver, '_does_item_exist_at_va_backend') self._driver._does_item_exist_at_va_backend.return_value = True self._driver.delete_snapshot(self._context, self.snapshot) self.assertEqual(2, self._driver._access_api.call_count) def test_delete_snapshot_negative(self): self.mock_object(self._driver, '_access_api') self.mock_object(self._driver, '_does_item_exist_at_va_backend') self._driver._does_item_exist_at_va_backend.return_value = True self._driver._access_api.return_value = False self.assertRaises(exception.ShareBackendException, self._driver.delete_snapshot, self._context, self.snapshot) def test_delete_snapshot_if_not_present_at_backend(self): self.mock_object(self._driver, '_does_item_exist_at_va_backend') self.mock_object(self._driver, '_access_api') self._driver._does_item_exist_at_va_backend.return_value = False self._driver.delete_snapshot(self._context, self.snapshot) self.assertEqual(1, (self._driver. _does_item_exist_at_va_backend.call_count)) self.assertEqual(0, self._driver._access_api.call_count) def test_update_access_for_allow(self): self.mock_object(self._driver, '_access_api') self._driver.update_access(self._context, self.share, [], [self.access], []) self.assertEqual(2, self._driver._access_api.call_count) def test_update_access_for_allow_negative(self): self.mock_object(self._driver, '_access_api') self._driver._access_api.return_value = False self.assertRaises(exception.ShareBackendException, self._driver.update_access, self._context, self.share, [], [self.access], []) self.assertRaises(exception.InvalidShareAccess, self._driver.update_access, self._context, self.share, [], [self.access2], []) self.assertRaises(exception.InvalidShareAccessLevel, self._driver.update_access, self._context, self.share, [], [self.access3], []) def test_update_access_for_deny(self): self.mock_object(self._driver, '_access_api') self._driver.update_access(self._context, self.share, [], [], [self.access]) self.assertEqual(2, self._driver._access_api.call_count) def test_update_access_for_deny_negative(self): self.mock_object(self._driver, '_access_api') self._driver._access_api.return_value = False self.assertRaises(exception.ShareBackendException, self._driver.update_access, self._context, self.share, [], [], [self.access]) def test_update_access_for_deny_for_invalid_access_type(self): self.mock_object(self._driver, '_access_api') self._driver.update_access(self._context, self.share, [], [], [self.access2]) self.assertEqual(0, self._driver._access_api.call_count) def test_update_access_for_empty_rule_list(self): self.mock_object(self._driver, '_allow_access') self.mock_object(self._driver, '_deny_access') self._driver.update_access(self._context, self.share, [], [], []) self.assertEqual(0, self._driver._allow_access.call_count) self.assertEqual(0, self._driver._deny_access.call_count) def test_update_access_for_access_rules(self): self.mock_object(self._driver, '_fetch_existing_rule') self.mock_object(self._driver, '_allow_access') self.mock_object(self._driver, '_deny_access') existing_a_rules = [{'access_level': 'rw', 'access_type': 'ip', 'access_to': '10.0.0.2'}, {'access_level': 'rw', 'access_type': 'ip', 'access_to': '10.0.0.3'}] self._driver._fetch_existing_rule.return_value = existing_a_rules d_rule = self._driver._return_access_lists_difference(existing_a_rules, [self.access4]) a_rule = self._driver._return_access_lists_difference([self.access4], existing_a_rules) self._driver.update_access(self._context, self.share, [self.access4], [], []) self.assertEqual(d_rule, existing_a_rules) self.assertEqual(a_rule, [self.access4]) self.assertEqual(1, self._driver._allow_access.call_count) self.assertEqual(2, self._driver._deny_access.call_count) def test_extend_share(self): self.mock_object(self._driver, '_access_api') new_size = 3 self._driver.extend_share(self.share, new_size) self.assertEqual(1, self._driver._access_api.call_count) def test_extend_share_negative(self): self.mock_object(self._driver, '_access_api') new_size = 3 self._driver._access_api.return_value = False self.assertRaises(exception.ShareBackendException, self._driver.extend_share, self.share, new_size) def test_shrink_share(self): self.mock_object(self._driver, '_access_api') new_size = 3 self._driver.shrink_share(self.share2, new_size) self.assertEqual(1, self._driver._access_api.call_count) def test_shrink_share_negative(self): self.mock_object(self._driver, '_access_api') new_size = 3 self._driver._access_api.return_value = False self.assertRaises(exception.ShareBackendException, self._driver.shrink_share, self.share2, new_size) def test__get_access_pool_details(self): self.mock_object(self._driver, '_access_api') pool_details = [] pool_details_dict = {} pool_details_dict['device_group_name'] = 'fake_pool' pool_details_dict['capacity'] = 10737418240 pool_details_dict['used_size'] = 9663676416 pool_details.append(pool_details_dict) pool_details_dict2 = {} pool_details_dict2['device_group_name'] = self.configuration.va_pool pool_details_dict2['capacity'] = 10737418240 pool_details_dict2['used_size'] = 9663676416 pool_details.append(pool_details_dict2) self._driver._access_api.return_value = pool_details total_space, free_space = self._driver._get_access_pool_details() self.assertEqual(10, total_space) self.assertEqual(1, free_space) def test__get_access_pool_details_negative(self): self.mock_object(self._driver, '_access_api') pool_details = [] self._driver._access_api.return_value = pool_details self.assertRaises(exception.ShareBackendException, self._driver._get_access_pool_details) def test__update_share_stats(self): self.mock_object(self._driver, '_authenticate_access') self.mock_object(self._driver, '_get_access_pool_details') self._driver._get_access_pool_details.return_value = (10, 9) self._driver._update_share_stats() data = { 'share_backend_name': FAKE_BACKEND, 'vendor_name': 'Veritas', 'driver_version': '1.0', 'storage_protocol': 'NFS', 'total_capacity_gb': 10, 'free_capacity_gb': 9, 'reserved_percentage': 0, 'QoS_support': False, 'create_share_from_snapshot_support': True, 'driver_handles_share_servers': False, 'filter_function': 'Disable', 'goodness_function': 'Disable', 'ipv4_support': True, 'ipv6_support': False, 'mount_snapshot_support': False, 'pools': None, 'qos': False, 'replication_domain': 'Disable', 'revert_to_snapshot_support': False, 'share_group_stats': {'consistent_snapshot_support': None}, 'snapshot_support': True } self.assertEqual(data, self._driver._stats) def test__get_vip(self): self.mock_object(self._driver, '_get_access_ips') pool_list = [] ip1 = {'isconsoleip': 1, 'type': 'Virtual', 'status': 'ONLINE', 'ip': '1.1.1.2'} ip2 = {'isconsoleip': 0, 'type': 'Virtual', 'status': 'ONLINE', 'ip': '1.1.1.4'} ip3 = {'isconsoleip': 0, 'type': 'Virtual', 'status': 'OFFLINE', 'ip': '1.1.1.5'} ip4 = {'isconsoleip': 0, 'type': 'Physical', 'status': 'OFFLINE', 'ip': '1.1.1.6'} pool_list = [ip1, ip2, ip3, ip4] self._driver._get_access_ips.return_value = pool_list vip = self._driver._get_vip() self.assertEqual('1.1.1.4', vip) def test__get_access_ips(self): self.mock_object(self._driver, '_access_api') ip_list = ['1.1.1.2', '1.1.2.3', '1.1.1.4'] self._driver._access_api.return_value = ip_list ret_value = self._driver._get_access_ips(self._driver.session, self._driver.host) self.assertEqual(ret_value, ip_list) def test__access_api(self): self.mock_object(requests, 'session') provider = '%s:%s' % (self._driver.host, self._driver._port) path = '/fake/path' input_data = {} mock_response = MockResponse() session = requests.session data = {'fake_key': 'fake_val'} json_data = json.dumps(data) session.request.return_value = mock_response ret_value = self._driver._access_api(session, provider, path, json.dumps(input_data), 'GET') self.assertEqual(json_data, ret_value) def test__access_api_ret_for_update_object(self): self.mock_object(requests, 'session') provider = '%s:%s' % (self._driver.host, self._driver._port) path = self._driver._update_object input_data = None mock_response = MockResponse() session = requests.session session.request.return_value = mock_response ret = self._driver._access_api(session, provider, path, input_data, 'GET') self.assertTrue(ret) def test__access_api_negative(self): session = self._driver.session provider = '%s:%s' % (self._driver.host, self._driver._port) path = '/fake/path' input_data = {} ret_value = self._driver._access_api(session, provider, path, json.dumps(input_data), 'GET') self.assertEqual(False, ret_value) def test__get_api(self): provider = '%s:%s' % (self._driver.host, self._driver._port) tail = '/fake/path' ret = self._driver._get_api(provider, tail) api_root = 'https://%s/api' % (provider) to_be_ret = api_root + tail self.assertEqual(to_be_ret, ret) def test__does_item_exist_at_va_backend(self): self.mock_object(self._driver, '_access_api') item_name = 'fake_item' path = '/fake/path' fake_item_list = [{'name': item_name}] self._driver._access_api.return_value = fake_item_list ret_value = self._driver._does_item_exist_at_va_backend(item_name, path) self.assertTrue(ret_value) def test__does_item_exist_at_va_backend_negative(self): self.mock_object(self._driver, '_access_api') item_name = 'fake_item' path = '/fake/path' fake_item_list = [{'name': 'item2'}] self._driver._access_api.return_value = fake_item_list ret_value = self._driver._does_item_exist_at_va_backend(item_name, path) self.assertEqual(False, ret_value) def test__fetch_existing_rule(self): self.mock_object(self._driver, '_access_api') fake_share = 'fake-share' fake_access_list = [] list1 = [] list1.append({ 'status': 'online', 'name': '/vx/fake-share', 'host_name': '10.0.0.1', 'privilege': 'rw' }) list1.append({ 'status': 'online', 'name': '/vx/fake-share', 'host_name': '10.0.0.2', 'privilege': 'rw' }) list1.append({ 'status': 'online', 'name': '/vx/fake-share', 'host_name': '10.0.0.3', 'privilege': 'ro' }) list1.append({ 'status': 'online', 'name': '/vx/fake-share2', 'host_name': '10.0.0.4', 'privilege': 'rw' }) fake_access_list.append({ 'shareType': 'NFS', 'shares': list1 }) fake_access_list.append({ 'shareType': 'CIFS', 'shares': [] }) ret_access_list = [] ret_access_list.append({ 'access_to': '10.0.0.1', 'access_level': 'rw', 'access_type': 'ip' }) ret_access_list.append({ 'access_to': '10.0.0.2', 'access_level': 'rw', 'access_type': 'ip' }) ret_access_list.append({ 'access_to': '10.0.0.3', 'access_level': 'ro', 'access_type': 'ip' }) self._driver._access_api.return_value = fake_access_list ret_value = self._driver._fetch_existing_rule(fake_share) self.assertEqual(ret_access_list, ret_value)
#!/usr/bin/env python # # Copyright 2007 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. # """Stub version of the memcache API, keeping all data in process memory.""" import logging import time from google.appengine.api import apiproxy_stub from google.appengine.api import memcache from google.appengine.api.memcache import memcache_service_pb MemcacheSetResponse = memcache_service_pb.MemcacheSetResponse MemcacheSetRequest = memcache_service_pb.MemcacheSetRequest MemcacheIncrementRequest = memcache_service_pb.MemcacheIncrementRequest MemcacheIncrementResponse = memcache_service_pb.MemcacheIncrementResponse MemcacheDeleteResponse = memcache_service_pb.MemcacheDeleteResponse class CacheEntry(object): """An entry in the cache.""" def __init__(self, value, expiration, flags, gettime): """Initializer. Args: value: String containing the data for this entry. expiration: Number containing the expiration time or offset in seconds for this entry. flags: Opaque flags used by the memcache implementation. gettime: Used for testing. Function that works like time.time(). """ assert isinstance(value, basestring) assert len(value) <= memcache.MAX_VALUE_SIZE assert isinstance(expiration, (int, long)) self._gettime = gettime self.value = value self.flags = flags self.created_time = self._gettime() self.will_expire = expiration != 0 self.locked = False self._SetExpiration(expiration) def _SetExpiration(self, expiration): """Sets the expiration for this entry. Args: expiration: Number containing the expiration time or offset in seconds for this entry. If expiration is above one month, then it's considered an absolute time since the UNIX epoch. """ if expiration > (86400 * 30): self.expiration_time = expiration else: self.expiration_time = self._gettime() + expiration def CheckExpired(self): """Returns True if this entry has expired; False otherwise.""" return self.will_expire and self._gettime() >= self.expiration_time def ExpireAndLock(self, timeout): """Marks this entry as deleted and locks it for the expiration time. Used to implement memcache's delete timeout behavior. Args: timeout: Parameter originally passed to memcache.delete or memcache.delete_multi to control deletion timeout. """ self.will_expire = True self.locked = True self._SetExpiration(timeout) def CheckLocked(self): """Returns True if this entry was deleted but has not yet timed out.""" return self.locked and not self.CheckExpired() class MemcacheServiceStub(apiproxy_stub.APIProxyStub): """Python only memcache service stub. This stub keeps all data in the local process' memory, not in any external servers. """ def __init__(self, gettime=time.time, service_name='memcache'): """Initializer. Args: gettime: time.time()-like function used for testing. service_name: Service name expected for all calls. """ super(MemcacheServiceStub, self).__init__(service_name) self._gettime = gettime self._ResetStats() self._the_cache = {} def _ResetStats(self): """Resets statistics information.""" self._hits = 0 self._misses = 0 self._byte_hits = 0 self._cache_creation_time = self._gettime() def _GetKey(self, namespace, key): """Retrieves a CacheEntry from the cache if it hasn't expired. Does not take deletion timeout into account. Args: namespace: The namespace that keys are stored under. key: The key to retrieve from the cache. Returns: The corresponding CacheEntry instance, or None if it was not found or has already expired. """ namespace_dict = self._the_cache.get(namespace, None) if namespace_dict is None: return None entry = namespace_dict.get(key, None) if entry is None: return None elif entry.CheckExpired(): del namespace_dict[key] return None else: return entry def _Dynamic_Get(self, request, response): """Implementation of MemcacheService::Get(). Args: request: A MemcacheGetRequest. response: A MemcacheGetResponse. """ namespace = request.name_space() keys = set(request.key_list()) for key in keys: entry = self._GetKey(namespace, key) if entry is None or entry.CheckLocked(): self._misses += 1 continue self._hits += 1 self._byte_hits += len(entry.value) item = response.add_item() item.set_key(key) item.set_value(entry.value) item.set_flags(entry.flags) def _Dynamic_Set(self, request, response): """Implementation of MemcacheService::Set(). Args: request: A MemcacheSetRequest. response: A MemcacheSetResponse. """ namespace = request.name_space() for item in request.item_list(): key = item.key() set_policy = item.set_policy() old_entry = self._GetKey(namespace, key) set_status = MemcacheSetResponse.NOT_STORED if ((set_policy == MemcacheSetRequest.SET) or (set_policy == MemcacheSetRequest.ADD and old_entry is None) or (set_policy == MemcacheSetRequest.REPLACE and old_entry is not None)): if (old_entry is None or set_policy == MemcacheSetRequest.SET or not old_entry.CheckLocked()): if namespace not in self._the_cache: self._the_cache[namespace] = {} self._the_cache[namespace][key] = CacheEntry(item.value(), item.expiration_time(), item.flags(), gettime=self._gettime) set_status = MemcacheSetResponse.STORED response.add_set_status(set_status) def _Dynamic_Delete(self, request, response): """Implementation of MemcacheService::Delete(). Args: request: A MemcacheDeleteRequest. response: A MemcacheDeleteResponse. """ namespace = request.name_space() for item in request.item_list(): key = item.key() entry = self._GetKey(namespace, key) delete_status = MemcacheDeleteResponse.DELETED if entry is None: delete_status = MemcacheDeleteResponse.NOT_FOUND elif item.delete_time() == 0: del self._the_cache[namespace][key] else: entry.ExpireAndLock(item.delete_time()) response.add_delete_status(delete_status) def _internal_increment(self, namespace, request): """Internal function for incrementing from a MemcacheIncrementRequest. Args: namespace: A string containing the namespace for the request, if any. Pass an empty string if there is no namespace. request: A MemcacheIncrementRequest instance. Returns: An integer or long if the offset was successful, None on error. """ key = request.key() entry = self._GetKey(namespace, key) if entry is None: if not request.has_initial_value(): return None if namespace not in self._the_cache: self._the_cache[namespace] = {} self._the_cache[namespace][key] = CacheEntry(str(request.initial_value()), expiration=0, flags=0, gettime=self._gettime) entry = self._GetKey(namespace, key) assert entry is not None try: old_value = long(entry.value) if old_value < 0: raise ValueError except ValueError: logging.error('Increment/decrement failed: Could not interpret ' 'value for key = "%s" as an unsigned integer.', key) return None delta = request.delta() if request.direction() == MemcacheIncrementRequest.DECREMENT: delta = -delta new_value = old_value + delta if not (0 <= new_value < 2**64): new_value = 0 entry.value = str(new_value) return new_value def _Dynamic_Increment(self, request, response): """Implementation of MemcacheService::Increment(). Args: request: A MemcacheIncrementRequest. response: A MemcacheIncrementResponse. """ namespace = request.name_space() response.set_new_value(self._internal_increment(namespace, request)) def _Dynamic_BatchIncrement(self, request, response): """Implementation of MemcacheService::BatchIncrement(). Args: request: A MemcacheBatchIncrementRequest. response: A MemcacheBatchIncrementResponse. """ namespace = request.name_space() for request_item in request.item_list(): new_value = self._internal_increment(namespace, request_item) item = response.add_item() if new_value is None: item.set_increment_status(MemcacheIncrementResponse.NOT_CHANGED) else: item.set_increment_status(MemcacheIncrementResponse.OK) item.set_new_value(new_value) def _Dynamic_FlushAll(self, request, response): """Implementation of MemcacheService::FlushAll(). Args: request: A MemcacheFlushRequest. response: A MemcacheFlushResponse. """ self._the_cache.clear() self._ResetStats() def _Dynamic_Stats(self, request, response): """Implementation of MemcacheService::Stats(). Args: request: A MemcacheStatsRequest. response: A MemcacheStatsResponse. """ stats = response.mutable_stats() stats.set_hits(self._hits) stats.set_misses(self._misses) stats.set_byte_hits(self._byte_hits) items = 0 total_bytes = 0 for namespace in self._the_cache.itervalues(): items += len(namespace) for entry in namespace.itervalues(): total_bytes += len(entry.value) stats.set_items(items) stats.set_bytes(total_bytes) stats.set_oldest_item_age(self._gettime() - self._cache_creation_time) def _Dynamic_GrabTail(self, request, response): """Implementation of MemcacheService::GrabTail(). Args: request: A MemcacheGrabTailRequest. response: A MemcacheGrabTailResponse. """ if request.item_count() <= 0: return namespace = request.name_space() if not namespace: return namespace_dict = self._the_cache.get(namespace, None) if namespace_dict is None: return items = namespace_dict.items() items.sort(None, lambda (key, entry): entry.created_time) item_count = 0 for (key, entry) in items: if entry.CheckExpired(): del namespace_dict[key] elif not entry.CheckLocked(): del namespace_dict[key] item = response.add_item() item.set_value(entry.value) item.set_flags(entry.flags) item_count += 1 self._hits += 1 self._byte_hits += len(entry.value) if item_count == request.item_count(): return
##################################################################################### # # Copyright (c) Microsoft Corporation. All rights reserved. # # This source code is subject to terms and conditions of the Apache License, Version 2.0. A # copy of the license can be found in the License.html file at the root of this distribution. If # you cannot locate the Apache License, Version 2.0, please send an email to # ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound # by the terms of the Apache License, Version 2.0. # # You must not remove this notice, or any other, from this software. # # ##################################################################################### from iptest.assert_util import * skiptest("silverlight") skiptest("win32") from iptest.console_util import IronPythonInstance remove_ironpython_dlls(testpath.public_testdir) from sys import executable from System import Environment from sys import exec_prefix extraArgs = "" if "-X:LightweightScopes" in Environment.GetCommandLineArgs(): extraArgs += " -X:LightweightScopes" def test_strings(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) # String exception response = ipi.ExecuteLine("raise 'foo'", True) AreEqual(response.replace("\r\r\n", "\n").replace("\r", ""), """Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: exceptions must be classes, or instances, not str""") # Multi-line string literal ipi.ExecutePartialLine("\"\"\"Hello") ipi.ExecutePartialLine("") ipi.ExecutePartialLine("") AreEqual("'Hello\\n\\n\\nWorld'", ipi.ExecuteLine("World\"\"\"")) ipi.ExecutePartialLine("if False: print 3") ipi.ExecutePartialLine("else: print 'hello'") AreEqual(r'hello', ipi.ExecuteLine("")) # Empty line AreEqual("", ipi.ExecuteLine("")) ipi.End() def test_exceptions(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) # parameterless exception response = ipi.ExecuteLine("raise Exception", True) AreEqual(response, '''Traceback (most recent call last): File "<stdin>", line 1, in <module> Exception'''.replace("\n", "\r\r\n") + "\r") ipi.End() def test_exceptions_nested(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) ipi.ExecutePartialLine("def a(): return b()") ipi.ExecuteLine("") ipi.ExecutePartialLine("def b(): return 1/0") ipi.ExecuteLine("") response = ipi.ExecuteLine("a()", True) response = response.replace("\r\r\n", "\n").strip() Assert(response.startswith('''Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in a File "<stdin>", line 1, in b ZeroDivisionError:'''), response) ipi.End() ############################################################################### # Test "ipy.exe -i script.py" def test_interactive_mode(): inputScript = testpath.test_inputs_dir + "\\simpleCommand.py" ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -i \"" + inputScript + "\"") AreEqual(ipi.Start(), True) ipi.EnsureInteractive() AreEqual("1", ipi.ExecuteLine("x")) ipi.End() inputScript = testpath.test_inputs_dir + "\\raise.py" ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -i \"" + inputScript + "\"") AreEqual(ipi.Start(), True) ipi.ReadError() ipi.EnsureInteractive() AreEqual("1", ipi.ExecuteLine("x")) ipi.End() inputScript = testpath.test_inputs_dir + "\\syntaxError.py" ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -i \"" + inputScript + "\"") AreEqual(ipi.Start(), True) # ipi.EnsureInteractive() AssertContains(ipi.ExecuteLine("x", True), "NameError") ipi.End() inputScript = testpath.test_inputs_dir + "\\exit.py" ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -i \"" + inputScript + "\"") (result, output, output2, exitCode) = ipi.StartAndRunToCompletion() AreEqual(exitCode, 0) ipi.End() # interactive + -c ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -i -c x=2") AreEqual(ipi.Start(), True) ipi.EnsureInteractive() Assert(ipi.ExecuteLine("x", True).find("2") != -1) ipi.End() ############################################################################### # Test sys.exitfunc def test_sys_exitfunc(): import clr inputScript = testpath.test_inputs_dir + "\\exitFuncRuns.py" ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " \"" + inputScript + "\"") (result, output, output2, exitCode) = ipi.StartAndRunToCompletion() AreEqual(exitCode, 0) AreEqual(output.find('hello world') > -1, True) ipi.End() args = extraArgs if clr.GetCurrentRuntime().Configuration.DebugMode: args = "-D " + args inputScript = testpath.test_inputs_dir + "\\exitFuncRaises.py" ipi = IronPythonInstance(executable, exec_prefix, args + " \"" + inputScript + "\"") (result, output, output2, exitCode) = ipi.StartAndRunToCompletion() AreEqual(exitCode, 0) AreEqual(output2.find('Error in sys.exitfunc:') > -1, True) AreEqual(output2.find('exitFuncRaises.py", line 19, in foo') > -1, True) ipi.End() # verify sys.exit(True) and sys.exit(False) return 1 and 0 ipi = IronPythonInstance(executable, exec_prefix, '-c "import sys; sys.exit(False)"') res = ipi.StartAndRunToCompletion() AreEqual(res[0], True) # should have started AreEqual(res[1], '') # no std out AreEqual(res[2], '') # no std err AreEqual(res[3], 0) # should return 0 ipi = IronPythonInstance(executable, exec_prefix, '-c "import sys; sys.exit(True)"') res = ipi.StartAndRunToCompletion() AreEqual(res[0], True) # should have started AreEqual(res[1], '') # no std out AreEqual(res[2], '') # no std err AreEqual(res[3], 1) # should return 0 # and verify it works at the interactive console as well ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) # parameterless exception ipi.ExecuteLine("import sys") AreEqual(ipi.ExecuteAndExit("sys.exit(False)"), 0) # and verify it works at the interactive console as well ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) # parameterless exception ipi.ExecuteLine("import sys") AreEqual(ipi.ExecuteAndExit("sys.exit(True)"), 1) ############################################################################# # verify we need to dedent to a previous valid indentation level def test_indentation(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) ipi.ExecutePartialLine("if False:") ipi.ExecutePartialLine(" print 'hello'") response = ipi.ExecuteLine(" print 'goodbye'", True) AreEqual(response.find('IndentationError') > 1, True) ipi.End() ############################################################################# # verify we dump exception details def test_dump_exception(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -X:ExceptionDetail") AreEqual(ipi.Start(), True) response = ipi.ExecuteLine("raise 'goodbye'", True) AreEqual(response.count("IronPython.Hosting") >= 1, True) ipi.End() ############################################################################# # make sure we can enter try/except blocks def test_try_except(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) ipi.ExecutePartialLine("try:") ipi.ExecutePartialLine(" raise Exception('foo')") ipi.ExecutePartialLine("except Exception, e:") ipi.ExecutePartialLine(" if e.message=='foo':") ipi.ExecutePartialLine(" print 'okay'") response = ipi.ExecuteLine("") Assert(response.find('okay') > -1) ipi.End() ########################################################### # Throw on "complete" incomplete syntax bug #864 def test_incomplate_syntax(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) ipi.ExecutePartialLine("class K:") response = ipi.ExecuteLine("", True) Assert("IndentationError:" in response) ipi.End() def test_incomplate_syntax_backslash(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) for i in xrange(4): for j in xrange(i): ipi.ExecutePartialLine("\\") ipi.ExecutePartialLine("1 + \\") for j in xrange(i): ipi.ExecutePartialLine("\\") response = ipi.ExecuteLine("2", True) Assert("3" in response) ipi.End() ########################################################### # if , while, try, for and then EOF. def test_missing_test(): for x in ['if', 'while', 'for', 'try']: ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) response = ipi.ExecuteLine(x, True) Assert("SyntaxError:" in response) ipi.End() ########################################################## # Support multiple-levels of indentation def test_indentation_levels(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) ipi.ExecutePartialLine("class K:") ipi.ExecutePartialLine(" def M(self):") ipi.ExecutePartialLine(" if 1:") ipi.ExecutePartialLine(" pass") response = ipi.ExecuteLine("") ipi.End() ########################################################## # Support partial lists def test_partial_lists(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) ipi.ExecutePartialLine("[1") ipi.ExecutePartialLine(" ,") ipi.ExecutePartialLine(" 2") response = ipi.ExecuteLine("]") Assert("[1, 2]" in response) ipi.ExecutePartialLine("[") ipi.ExecutePartialLine("") ipi.ExecutePartialLine("") response = ipi.ExecuteLine("]") Assert("[]" in response) ipi.End() def test_partial_lists_cp3530(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) try: ipi.ExecutePartialLine("[{'a':None},") response = ipi.ExecuteLine("]") Assert("[{'a': None}]" in response, response) ipi.ExecutePartialLine("[{'a'") response = ipi.ExecutePartialLine(":None},") response = ipi.ExecuteLine("]") Assert("[{'a': None}]" in response, response) ipi.ExecutePartialLine("[{'a':None},") ipi.ExecutePartialLine("1,") response = ipi.ExecuteLine("2]") Assert("[{'a': None}, 1, 2]" in response, response) finally: ipi.End() ########################################################## # Support partial tuples def test_partial_tuples(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) ipi.ExecutePartialLine("(2") ipi.ExecutePartialLine(" ,") ipi.ExecutePartialLine(" 3") response = ipi.ExecuteLine(")") Assert("(2, 3)" in response) ipi.ExecutePartialLine("(") response = ipi.ExecuteLine(")") Assert("()" in response) ipi.ExecutePartialLine("'abc %s %s %s %s %s' % (") ipi.ExecutePartialLine(" 'def'") ipi.ExecutePartialLine(" ,'qrt',") ipi.ExecutePartialLine(" 'jkl'") ipi.ExecutePartialLine(",'jkl'") ipi.ExecutePartialLine("") ipi.ExecutePartialLine(",") ipi.ExecutePartialLine("") ipi.ExecutePartialLine("") ipi.ExecutePartialLine("'123'") response = ipi.ExecuteLine(")") Assert("'abc def qrt jkl jkl 123'" in response) ipi.ExecutePartialLine("a = (") ipi.ExecutePartialLine(" 1") ipi.ExecutePartialLine(" , ") ipi.ExecuteLine(")") response = ipi.ExecuteLine("a") Assert("(1,)" in response) ipi.ExecutePartialLine("(") ipi.ExecutePartialLine("'joe'") ipi.ExecutePartialLine(" ") ipi.ExecutePartialLine(" #") ipi.ExecutePartialLine(",") ipi.ExecutePartialLine("2") response = ipi.ExecuteLine(")") Assert("('joe', 2)" in response) ipi.ExecutePartialLine("(") ipi.ExecutePartialLine("") ipi.ExecutePartialLine("") response = ipi.ExecuteLine(")") Assert("()" in response) ipi.End() ########################################################## # Support partial dicts def test_partial_dicts(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) ipi.ExecutePartialLine("{2:2") ipi.ExecutePartialLine(" ,") ipi.ExecutePartialLine(" 2:2") response = ipi.ExecuteLine("}") Assert("{2: 2}" in response) ipi.ExecutePartialLine("{") response = ipi.ExecuteLine("}") Assert("{}" in response) ipi.ExecutePartialLine("a = {") ipi.ExecutePartialLine(" None:2") ipi.ExecutePartialLine(" , ") ipi.ExecuteLine("}") response = ipi.ExecuteLine("a") Assert("{None: 2}" in response) ipi.ExecutePartialLine("{") ipi.ExecutePartialLine("'joe'") ipi.ExecutePartialLine(": ") ipi.ExecutePartialLine(" 42") ipi.ExecutePartialLine(",") ipi.ExecutePartialLine("3:45") response = ipi.ExecuteLine("}") Assert(repr({'joe':42, 3:45}) in response) ipi.ExecutePartialLine("{") ipi.ExecutePartialLine("") ipi.ExecutePartialLine("") response = ipi.ExecuteLine("}") Assert("{}" in response) ipi.End() ########################################################### # Some whitespace wackiness def test_whitespace(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) ipi.ExecuteLine(" ") response = ipi.ExecuteLine("") ipi.End() ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) ipi.ExecuteLine(" ") response = ipi.ExecuteLine("2") Assert("2" in response) ipi.End() ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) ipi.ExecuteLine(" ") response = ipi.ExecuteLine(" 2", True) Assert("SyntaxError:" in response) ipi.End() ########################################################### # test the indentation error in the interactive mode def test_indentation_interactive(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) ipi.ExecutePartialLine("class C:pass") response = ipi.ExecuteLine("") AreEqual(response, "") ipi.ExecutePartialLine("class D(C):") response = ipi.ExecuteLine("", True) Assert("IndentationError:" in response) ipi.End() ########################################################### # test /mta w/ no other args def test_mta(): ipi = IronPythonInstance(executable, exec_prefix, '-X:MTA') AreEqual(ipi.Start(), True) ipi.ExecutePartialLine("class C:pass") response = ipi.ExecuteLine("") AreEqual(response, "") ipi.ExecutePartialLine("class D(C):") response = ipi.ExecuteLine("", True) Assert("IndentationError:" in response) ipi.End() ########################################################### # test for comments in interactive input def test_comments(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) response = ipi.ExecuteLine("# this is some comment line") AreEqual(response, "") response = ipi.ExecuteLine(" # this is some comment line") AreEqual(response, "") response = ipi.ExecuteLine("# this is some more comment line") AreEqual(response, "") ipi.ExecutePartialLine("if 100:") ipi.ExecutePartialLine(" print 100") ipi.ExecutePartialLine("# this is some more comment line inside if") ipi.ExecutePartialLine("# this is some indented comment line inside if") ipi.ExecutePartialLine(" print 200") response = ipi.ExecuteLine("") AreEqual(response, "100" + newline + "200") ipi.End() def test_global_values(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) ipi.ExecuteLine("import clr") response = ipi.ExecuteLine("[x for x in globals().values()]") Assert(response.startswith('[')) d = eval(ipi.ExecuteLine("globals().fromkeys(['a', 'b'], 'c')")) AreEqual(d, {'a':'c', 'b':'c'}) def test_globals8961(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) response = ipi.ExecuteLine("print globals().keys()") res = set(eval(response)) AreEqual(res, set(['__builtins__', '__name__', '__doc__'])) ipi.ExecuteLine("a = None") response = ipi.ExecuteLine("print globals().keys()") res = set(eval(response)) AreEqual(res, set(['__builtins__', '__name__', '__doc__', 'a'])) response = ipi.ExecuteLine("print globals().values()") l = eval(response.replace("<module '__builtin__' (built-in)>", '"builtin"')) res = set(l) AreEqual(len(l), 4) AreEqual(res, set(['builtin', '__main__', None])) ipi.ExecuteLine("b = None") response = ipi.ExecuteLine("print globals().values()") l = eval(response.replace("<module '__builtin__' (built-in)>", '"builtin"')) res = set(l) AreEqual(len(l), 5) AreEqual(res, set(['builtin', '__main__', None])) def test_console_input_output(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) input_output = [ ("x=100",""), ("x=200\n",""), ("\nx=300",""), ("\nx=400\n",""), ("500","500"), ("600\n\n\n\n\n\n\n\n\n\n\n","600"), ("valid=3;more_valid=4;valid","3"), ("valid=5;more_valid=6;more_valid\n\n\n\n\n","6"), ("valid=7;more_valid=8;#valid",""), ("valid=9;valid;# more_valid\n","9"), ("valid=11;more_valid=12;more_valid# should be valid input\n\n\n\n","12"), ] for x in input_output: AreEqual(ipi.Start(), True) AreEqual(ipi.ExecuteLine(x[0]),x[1]) ipi.End() # expect a clean exception message/stack from thread def test_thrown_from_thread(): inputScript = path_combine(testpath.temporary_dir, "throwingfromthread.py") write_to_file(inputScript, ''' def f(): raise AssertionError, 'hello' import thread, time thread.start_new_thread(f, tuple()) time.sleep(2) ''') ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " " + inputScript) (result, output, output2, exitCode) = ipi.StartAndRunToCompletion() AreEqual(exitCode, 0) Assert("AssertionError: hello" in output2) Assert("IronPython." not in output2) # '.' is necessary here ipi.End() def test_aform_feeds(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) response = ipi.ExecuteLine("\fprint 'hello'") AreEqual(response, "hello") response = ipi.ExecuteLine(" \fprint 'hello'") AreEqual(response, "hello") ipi.ExecutePartialLine("def f():") ipi.ExecutePartialLine("\f print 'hello'") ipi.ExecuteLine('') response = ipi.ExecuteLine('f()') AreEqual(response, "hello") # \f resets indent to 0 ipi.ExecutePartialLine("def f():") ipi.ExecutePartialLine(" \f x = 'hello'") ipi.ExecutePartialLine("\f print x") ipi.ExecuteLine('') response = ipi.ExecuteLine('f()') AreEqual(response, "hello") # \f resets indent to 0 ipi.ExecutePartialLine("def f():") ipi.ExecutePartialLine(" \f x = 'hello'") ipi.ExecutePartialLine(" print x") ipi.ExecuteLine('') response = ipi.ExecuteLine('f()') AreEqual(response, "hello") def test_ipy_dash_S(): """ipy -S should still install Lib into sys.path""" ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -S") AreEqual(ipi.Start(), True) response = ipi.ExecuteLine("import sys") response = ipi.ExecuteLine("print sys.path") Assert(response.find('Lib') != -1) def test_startup_dir(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) response = ipi.ExecuteLine("print dir()") AreEqual(sorted(eval(response)), sorted(['__builtins__', '__doc__', '__name__'])) def test_ipy_dash_m(): import sys for path in sys.path: if path.find('Lib') != -1: filename = System.IO.Path.Combine(path, 'somemodule.py') break try: f = file(filename, 'w') f.write('print "hello"\n') f.write('import sys\n') f.write('print sys.argv') f.close() # need to run these tests where we have access to runpy.py path = System.IO.FileInfo(__file__).DirectoryName # simple case works ipi = IronPythonInstance(executable, path, extraArgs + " -m somemodule") res, output, err, exit = ipi.StartAndRunToCompletion() AreEqual(res, True) # run should have worked AreEqual(exit, 0) # should have returned 0 output = output.replace('\r\n', '\n') lines = output.split('\n') AreEqual(lines[0], 'hello') Assert(samefile(eval(lines[1])[0], filename)) # we receive any arguments in sys.argv ipi = IronPythonInstance(executable, path, extraArgs + " -m somemodule foo bar") res, output, err, exit = ipi.StartAndRunToCompletion() AreEqual(res, True) # run should have worked AreEqual(exit, 0) # should have returned 0 output = output.replace('\r\n', '\n') lines = output.split('\n') AreEqual(lines[0], 'hello') AreEqual(eval(lines[1]), [filename, 'foo', 'bar']) f = file(filename, 'w') f.write('print "hello"\n') f.write('import sys\n') f.write('sys.exit(1)') f.close() # sys.exit works ipi = IronPythonInstance(executable, path, extraArgs + " -m somemodule") res, output, err, exit = ipi.StartAndRunToCompletion() AreEqual(res, True) # run should have worked AreEqual(exit, 1) # should have returned 0 output = output.replace('\r\n', '\n') lines = output.split('\n') AreEqual(lines[0], 'hello') finally: nt.unlink(filename) @disabled("CodePlex Work Item 10925") def test_ipy_dash_m_negative(): # builtin modules should not work for modname in [ "sys", "datetime" ]: ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -m " + modname) res, output, err, exit = ipi.StartAndRunToCompletion() AreEqual(exit, -1) # Modules within packages should not work ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -m testpkg1.mod1") res, output, err, exit = ipi.StartAndRunToCompletion() AreEqual(res, True) # run should have worked AreEqual(exit, 1) # should have returned 0 Assert("SyntaxError: invalid syntax" in err, "stderr is:" + str(err)) def test_ipy_dash_m_pkgs(): # Python packages work import nt Assert("testpkg1" in [x.lower() for x in nt.listdir(nt.getcwd())], nt.getcwd()) old_ipy_path = get_environ_variable("IRONPYTHONPATH") try: nt.environ["IRONPYTHONPATH"] = nt.getcwd() ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -m testpkg1") res, output, err, exit = ipi.StartAndRunToCompletion() AreEqual(res, True) # run should have worked AreEqual(exit, 0) # should have returned 0 AreEqual(output, "") # Bad module names should not work ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -m libxyz") res, output, err, exit = ipi.StartAndRunToCompletion() AreEqual(res, True) # run should have worked AreEqual(exit, 1) # should have returned 0 Assert("ImportError: No module named libxyz" in err, "stderr is:" + str(err)) finally: nt.environ["IRONPYTHONPATH"] = old_ipy_path def test_ipy_dash_c(): """verify ipy -c cmd doesn't print expression statements""" ipi = IronPythonInstance(executable, exec_prefix, "-c True;False") res = ipi.StartAndRunToCompletion() AreEqual(res[0], True) # should have started AreEqual(res[1], '') # no std out AreEqual(res[2], '') # no std err AreEqual(res[3], 0) # should return 0 ############################################################################# # CP11924 - verify 'from __future__ import division' works def test_future_division(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) ipi.ExecuteLine("from __future__ import division") response = ipi.ExecuteLine("11/4") AreEqual(response, "2.75") ipi.End() ############################################################################# # CP2206 def test_future_with(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) ipi.ExecutePartialLine("class K(object):") ipi.ExecutePartialLine(" def __enter__(self): return 3.14") ipi.ExecutePartialLine(" def __exit__(self, type, value, tb): return False") ipi.ExecuteLine("") ipi.ExecutePartialLine("with K() as d:") ipi.ExecutePartialLine(" print d") response = ipi.ExecuteLine("") AreEqual(response, "3.14") ipi.End() ############################################################################# # Merlin 148481 def test_ipy_dash(): #Verify that typing a - in the arguments starts an interactive session ipi = IronPythonInstance(executable, exec_prefix, "-") AreEqual(ipi.Start(), True) response = ipi.ExecuteLine("42") AreEqual(response, "42") ipi.End() ############################################################################# def test_mta(): ipi = IronPythonInstance(executable, exec_prefix, '-X:MTA') AreEqual(ipi.Start(), True) ipi.ExecuteLine("import System") response = ipi.ExecuteLine("str(System.Threading.Thread.CurrentThread.ApartmentState)") AreEqual(response, "'MTA'") ipi.ExecutePartialLine("class C:pass") response = ipi.ExecuteLine("") AreEqual(response, "") response = ipi.ExecuteLine("str(System.Threading.Thread.CurrentThread.ApartmentState)") AreEqual(response, "'MTA'") ipi.End() def test_displayhook(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) # parameterless exception ipi.ExecuteLine("import sys") ipi.ExecutePartialLine("def f(x): print 'foo', x") ipi.ExecuteLine("") response = ipi.ExecuteLine("sys.displayhook = f") response = ipi.ExecuteLine("42") AreEqual(response, "foo 42") def test_excepthook(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) # parameterless exception ipi.ExecuteLine("import sys") ipi.ExecutePartialLine("def f(*args): print 'foo', args") ipi.ExecuteLine("") response = ipi.ExecuteLine("sys.excepthook = f") response = ipi.ExecuteLine("raise Exception", True) AssertContains(response, "foo (<type 'exceptions.Exception'>, Exception(), <traceback object at") def test_last_exception(): ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) # parameterless exception ipi.ExecuteLine("import sys") response = ipi.ExecuteLine("hasattr(sys, 'last_value')") AreEqual(response, 'False') AssertContains(ipi.ExecuteLine("x", True), "NameError") response = ipi.ExecuteLine("sys.last_value") AreEqual(response, "NameError(\"name 'x' is not defined\",)") response = ipi.ExecuteLine("sys.last_type") AreEqual(response, "<type 'exceptions.NameError'>") response = ipi.ExecuteLine("sys.last_traceback") AssertContains(response, "<traceback object at ") def test_sta_sleep_Warning(): ipi = IronPythonInstance(executable, exec_prefix, '-c "from System.Threading import Thread;Thread.Sleep(100)"') retval, stdouttext, stderrtext, exitcode = ipi.StartAndRunToCompletion() Assert(stderrtext.endswith("RuntimeWarning: Calling Thread.Sleep on an STA thread doesn't pump messages. Use Thread.CurrentThread.Join instead.\r\n")) def test_newline(): ipi = IronPythonInstance(executable, exec_prefix, "") ipi.proc.Start() ipi.reader = ipi.proc.StandardOutput output = ipi.EatToPrompt() Assert('\r\r\n' not in output) Assert('\r\n' in output) ############################################################################# # Remote console tests from System.Diagnostics import Process def get_process_ids(ipi): ipi.EnsureInteractiveRemote() ipi.proc.Refresh() consoleProcessId = ipi.proc.Id ipi.ExecuteLine("import System") remoteRuntimeProcessId = ipi.ExecuteLineRemote("System.Diagnostics.Process.GetCurrentProcess().Id") Assert(remoteRuntimeProcessId.isdigit(), "remoteRuntimeProcessId is '%s'" % remoteRuntimeProcessId) return consoleProcessId, int(remoteRuntimeProcessId) def start_remote_console(args = ""): inputScript = testpath.test_inputs_dir + "\\RemoteConsole.py" ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " \"" + inputScript + "\" -X:ExceptionDetail " + args) AreEqual(ipi.Start(), True) return ipi # Basic check that the remote console actually uses two processes def test_remote_console_processes(): # First check that a simple local console uses a single process ipi = IronPythonInstance(executable, exec_prefix, extraArgs) AreEqual(ipi.Start(), True) consoleProcessId, remoteRuntimeProcessId = get_process_ids(ipi) AreEqual(consoleProcessId, remoteRuntimeProcessId) ipi.End() # Now use the remote console ipi = start_remote_console() consoleProcessId, remoteRuntimeProcessId = get_process_ids(ipi) AreNotEqual(consoleProcessId, remoteRuntimeProcessId) ipi.End() # The remote runtime should terminate when the console terminates def test_remote_runtime_normal_exit(): ipi = start_remote_console() consoleProcessId, remoteRuntimeProcessId = get_process_ids(ipi) runtimeProcess = Process.GetProcessById(remoteRuntimeProcessId) Assert(not runtimeProcess.HasExited) ipi.End() runtimeProcess.WaitForExit() # The test is that this wait succeeds # Stress the input-output streams def test_remote_io(): ipi = start_remote_console() for i in xrange(100): AreEqual(ipi.ExecuteLineRemote("2+2"), "4") ipi.End() # Kill the remote runtime and ensure that another process starts up again def test_remote_server_restart(): ipi = start_remote_console() consoleProcessId, remoteRuntimeProcessId = get_process_ids(ipi) runtimeProcess = Process.GetProcessById(remoteRuntimeProcessId) AreNotEqual(runtimeProcess, consoleProcessId) runtimeProcess.Kill() runtimeProcess.WaitForExit() # The Process.Exited event is fired asynchronously, and might take sometime to fire. # Hence, we need to block for a known marker ipi.EatToMarker("Remote runtime terminated") # We need to press Enter to nudge the old console out of the ReadLine... restartMessage = ipi.ExecuteLine("", True) ipi.ReadError() consoleProcessId2, remoteRuntimeProcessId2 = get_process_ids(ipi) AreEqual(consoleProcessId, consoleProcessId2) # This is technically not a 100% correct as there is a small chance the the process id might get reused AreNotEqual(remoteRuntimeProcessId, remoteRuntimeProcessId2) ipi.End() # Check that an exception can be remoted back over the reverse channel # Note that exceptions are not written to stdout by the remote process def test_remote_console_exception(): ipi = start_remote_console() zeroDivisionErrorOutput = ipi.ExecuteLine("1/0", True) AssertContains(zeroDivisionErrorOutput, "ZeroDivisionError") ipi.End() def test_remote_startup_script(): ipi = start_remote_console("-i " + testpath.test_inputs_dir + "\\simpleCommand.py") AreEqual(ipi.ExecuteLine("x"), "1") ipi.End() def get_abort_command_output(): ipi = start_remote_console() ipi.ExecuteLine("import System") ipi.ExecutePartialLine ("def Hang():") ipi.ExecutePartialLine (" print 'ABORT ME!!!' # This string token should trigger an abort...") ipi.ExecutePartialLine (" infinite = System.Threading.Timeout.Infinite") ipi.ExecutePartialLine (" System.Threading.Thread.CurrentThread.Join(infinite)") ipi.ExecuteLine ("") result = ipi.ExecuteLine("Hang()", True) ipi.End() return result def test_remote_abort_command(): for i in xrange(10): output = get_abort_command_output() if "KeyboardInterrupt" in output: AssertDoesNotContain(output, "Thread was being aborted.") # ThreadAbortException return else: # Rarely, under stress conditions, ThreadAbortException leaks through. # Keep retrying until we actually get KeyboardInterrupt AssertContains(output, "Thread was being aborted.") # ThreadAbortException continue Assert(False, "KeyboardInterrupt not thrown. Only KeyboardInterrupt was thrown") def test_exception_slicing_warning(): ipi = IronPythonInstance(executable, exec_prefix, '-c "print Exception(*range(2))[1]"') res = ipi.StartAndRunToCompletion() AreEqual(res[0], True) # should have started AreEqual(res[1], '1\r\n') # some std out AreEqual(res[2], '') # no std err AreEqual(res[3], 0) # should return 0 ipi = IronPythonInstance(executable, exec_prefix, '-3 -c "import warnings;' 'warnings.filters.reverse();' 'warnings.filters.pop();' 'print Exception(*range(2))[1]"') res = ipi.StartAndRunToCompletion() AreEqual(res[0], True) # should have started AreEqual(res[1], '1\r\n') # std out Assert(res[2].endswith('DeprecationWarning: __getitem__ not supported for exception classes in 3.x; use args attribute\r\n')) #std err AreEqual(res[3], 0) # should return 0 #------------------------------------------------------------------------------ run_test(__name__)
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class AutoscaleSettingsOperations: """AutoscaleSettingsOperations async 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: ~$(python-base-namespace).v2021_05_01_preview.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) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list_by_resource_group( self, resource_group_name: str, **kwargs: Any ) -> AsyncIterable["_models.AutoscaleSettingResourceCollection"]: """Lists the autoscale settings for a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AutoscaleSettingResourceCollection or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~$(python-base-namespace).v2021_05_01_preview.models.AutoscaleSettingResourceCollection] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.AutoscaleSettingResourceCollection"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-05-01-preview" 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_resource_group.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', min_length=1), } 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 async def extract_data(pipeline_response): deserialized = self._deserialize('AutoscaleSettingResourceCollection', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await 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.AutoscaleErrorResponse, 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 AsyncItemPaged( get_next, extract_data ) list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings'} # type: ignore async def create_or_update( self, resource_group_name: str, autoscale_setting_name: str, parameters: "_models.AutoscaleSettingResource", **kwargs: Any ) -> "_models.AutoscaleSettingResource": """Creates or updates an autoscale setting. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param autoscale_setting_name: The autoscale setting name. :type autoscale_setting_name: str :param parameters: Parameters supplied to the operation. :type parameters: ~$(python-base-namespace).v2021_05_01_preview.models.AutoscaleSettingResource :keyword callable cls: A custom type or function that will be passed the direct response :return: AutoscaleSettingResource, or the result of cls(response) :rtype: ~$(python-base-namespace).v2021_05_01_preview.models.AutoscaleSettingResource :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.AutoscaleSettingResource"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-05-01-preview" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.create_or_update.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'autoscaleSettingName': self._serialize.url("autoscale_setting_name", autoscale_setting_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), } 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, 'AutoscaleSettingResource') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.AutoscaleErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('AutoscaleSettingResource', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('AutoscaleSettingResource', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}'} # type: ignore async def delete( self, resource_group_name: str, autoscale_setting_name: str, **kwargs: Any ) -> None: """Deletes and autoscale setting. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param autoscale_setting_name: The autoscale setting name. :type autoscale_setting_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ 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-preview" accept = "application/json" # Construct URL url = self.delete.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'autoscaleSettingName': self._serialize.url("autoscale_setting_name", autoscale_setting_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), } 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 = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.AutoscaleErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}'} # type: ignore async def get( self, resource_group_name: str, autoscale_setting_name: str, **kwargs: Any ) -> "_models.AutoscaleSettingResource": """Gets an autoscale setting. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param autoscale_setting_name: The autoscale setting name. :type autoscale_setting_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: AutoscaleSettingResource, or the result of cls(response) :rtype: ~$(python-base-namespace).v2021_05_01_preview.models.AutoscaleSettingResource :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.AutoscaleSettingResource"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-05-01-preview" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'autoscaleSettingName': self._serialize.url("autoscale_setting_name", autoscale_setting_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), } 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 = await 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.AutoscaleErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('AutoscaleSettingResource', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}'} # type: ignore async def update( self, resource_group_name: str, autoscale_setting_name: str, autoscale_setting_resource: "_models.AutoscaleSettingResourcePatch", **kwargs: Any ) -> "_models.AutoscaleSettingResource": """Updates an existing AutoscaleSettingsResource. To update other fields use the CreateOrUpdate method. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param autoscale_setting_name: The autoscale setting name. :type autoscale_setting_name: str :param autoscale_setting_resource: Parameters supplied to the operation. :type autoscale_setting_resource: ~$(python-base-namespace).v2021_05_01_preview.models.AutoscaleSettingResourcePatch :keyword callable cls: A custom type or function that will be passed the direct response :return: AutoscaleSettingResource, or the result of cls(response) :rtype: ~$(python-base-namespace).v2021_05_01_preview.models.AutoscaleSettingResource :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.AutoscaleSettingResource"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-05-01-preview" 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', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'autoscaleSettingName': self._serialize.url("autoscale_setting_name", autoscale_setting_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(autoscale_setting_resource, 'AutoscaleSettingResourcePatch') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await 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.AutoscaleErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('AutoscaleSettingResource', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}'} # type: ignore def list_by_subscription( self, **kwargs: Any ) -> AsyncIterable["_models.AutoscaleSettingResourceCollection"]: """Lists the autoscale settings for a subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AutoscaleSettingResourceCollection or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~$(python-base-namespace).v2021_05_01_preview.models.AutoscaleSettingResourceCollection] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.AutoscaleSettingResourceCollection"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-05-01-preview" 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_subscription.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), } 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 async def extract_data(pipeline_response): deserialized = self._deserialize('AutoscaleSettingResourceCollection', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await 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.AutoscaleErrorResponse, 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 AsyncItemPaged( get_next, extract_data ) list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Insights/autoscalesettings'} # type: ignore
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Defines the models. The base of the network is a vision model that embeds an RGB image to a flat vector which serves as a visual description. The head of the network turns the visual description into a pose. It must have a method to compute the loss and to predict a pose given a visual description vector. For the implicit function based approach, the random sampling is all contained within the class definition. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import re from absl import logging import numpy as np import tensorflow as tf import tensorflow_graphics.geometry.transformation as tfg tfkl = tf.keras.layers eps = 1e-9 def create_vision_model(image_dims=(224, 224, 3), weights='imagenet'): """Loads a pre-trained resnet for the vision model. Args: image_dims: The input shape. weights: Source of weights to be loaded. Returns: The vision model and the length of the visual description vector. """ base_model = tf.keras.applications.ResNet50V2( weights=weights, include_top=False, input_shape=image_dims) inp = tf.keras.layers.Input(shape=image_dims) x = base_model(inp) x = tfkl.GlobalAveragePooling2D()(x) len_visual_description = x.shape[-1] vision_model = tf.keras.Model(inp, x) return vision_model, len_visual_description class ImplicitSO3(tfkl.Layer): """Represents a distribution over SO(3) as an implicit function. Specifically, this is a fully connected network which takes as input a visual description vector and a query rotation, and outputs a single scalar which can be converted to a log likelihood via normalization. By querying many values we can build up a probability distribution over SO(3). The query format is a 3x3 rotation matrix, flattened and then positionally encoded in each component with multiple frequencies of sinusoids. Init args: len_visual_description: The length of the visual description vector, which is returned with the vision model at creation. number_fourier_components: The number of positional encoding frequencies for the rotation query. If zero, positional encoding is not used. mlp_layer_sizes: A list of the number of units in each layer of the MLP. so3_sampling_mode: 'random' or 'grid'. This is only efficacious during training, and determines how the normalization is computed. 'random' corresponds to sampling uniformly over the space of rotations, which is simple and less constrained but results in inexact normalization. 'grid' uses equivolumetric grids generated using healpix as a starting point. These grids are stored so each size only needs to be computed once per run. number_train_queries: The number of queries to use during training, which populate SO(3) to approximate the normalization of the likelihoods. If so3_sampling_mode is 'grid', the nearest grid size in log space is used. number_eval_queries: The number of queries to use during evaluation, which is always a grid sampling (for proper normalization). """ def __init__(self, len_visual_description, number_fourier_components, mlp_layer_sizes, so3_sampling_mode, number_train_queries, number_eval_queries, **kwargs): super().__init__(**kwargs) self.len_visual_description = len_visual_description # Rotations are represented as flattened 3x3 orthonormal matrices. self.len_rotation = 9 self.number_fourier_components = number_fourier_components self.frequencies = tf.range(number_fourier_components, dtype=tf.float32) self.frequencies = tf.math.pow(2., self.frequencies) self.so3_sampling_mode = so3_sampling_mode self.number_train_queries = number_train_queries self.number_eval_queries = number_eval_queries if number_fourier_components == 0: self.len_query = self.len_rotation else: self.len_query = self.len_rotation * number_fourier_components * 2 self.grids = {} # The grids will be populated on-demand. if self.so3_sampling_mode == 'grid': self.get_closest_available_grid(self.number_train_queries) self.get_closest_available_grid(self.number_eval_queries) input_visual = tfkl.Input(shape=(len_visual_description,)) visual_embedding = tfkl.Dense(mlp_layer_sizes[0])(input_visual) input_query = tfkl.Input(shape=(None, self.len_query,)) query_embedding = tfkl.Dense(mlp_layer_sizes[0])(input_query) # Broadcast sum to combine inputs. output = visual_embedding[:, tf.newaxis] + query_embedding output = tfkl.ReLU()(output) for num_units in mlp_layer_sizes[1:]: output = tfkl.Dense(num_units, 'relu')(output) output = tfkl.Dense(1)(output) self.implicit_model = tf.keras.models.Model( inputs=[input_visual, input_query], outputs=output) self.mlp_layer_sizes = mlp_layer_sizes def get_config(self): """For saving purposes.""" config = super().get_config().copy() config.update({ 'len_visual_description': self.len_visual_description, 'number_fourier_components': self.number_fourier_components, 'mlp_layer_sizes': self.mlp_layer_sizes, 'so3_sampling_mode': self.so3_sampling_mode, 'number_train_queries': self.number_train_queries, 'number_eval_queries': self.number_eval_queries, }) return config def call(self, inp): return self.implicit_model(inp) def predict_probability(self, vision_description, rotation_matrix, training=False): """Predict the probability of the rotation, given the vision description. Rotate the grids to make sure they contain the rotation matrix. It requires different queries per element in the batch, increasing the # of ops in the first MLP layer. Args: vision_description: The feature vectors of the batch of images. rotation_matrix: The query rotation matrices. training: True or False; determines how many queries to use for normalization and whether to use an equivolumetric grid. Returns: The probability density at the rotation given by rotation_matrix. """ if training: query_rotations = self.generate_queries( self.number_train_queries, mode=self.so3_sampling_mode) else: query_rotations = self.generate_queries( self.number_eval_queries, mode='grid') delta_rot = tf.transpose(query_rotations[-1]) @ rotation_matrix query_rotations = tf.einsum('aij,bjk->baik', query_rotations, delta_rot) shape = query_rotations.shape query_rotations = tf.reshape(query_rotations, [shape[0], shape[1], self.len_rotation]) query_rotations = self.positional_encoding(query_rotations) logits = self.implicit_model([vision_description, query_rotations], training=training)[Ellipsis, 0] probabilities = tf.nn.softmax(logits, axis=-1) # Scale by the volume per grid point. probabilities *= query_rotations.shape[1] / np.pi**2 # The final query rotation is the rotation we care about. return probabilities[:, -1] def predict_rotation(self, vision_descriptions, gradient_ascent=False): """Returns a predicted rotation given the vision description. The mode of the distribution is approximated, found either as the argmax over a set of samples, or by running gradient ascent on the probability with the sample argmax as the starting point. Args: vision_descriptions: The feature vectors for the images on which to run pose estimation. gradient_ascent: True or False; whether to perform gradient ascent after finding the argmax over the sample rotations, to squeeze out a little more performance. Returns: A tensor of rotations, shape [N, 3, 3] where N is the number of vision descriptions. """ query_rotations = self.generate_queries(self.number_eval_queries, mode='grid') query_rotations_inp = tf.reshape(query_rotations, [-1, self.len_rotation]) query_rotations_inp = self.positional_encoding(query_rotations_inp) logits = self.implicit_model([vision_descriptions, query_rotations_inp], training=False)[Ellipsis, 0] max_inds = tf.argmax(logits, axis=-1) max_rotations = tf.gather(query_rotations, max_inds) if not gradient_ascent: max_rotations = tf.reshape(max_rotations, [-1, 3, 3]) return max_rotations # Perform gradient ascent, using the argmax rotations as starting seeds. # These parameters were found to work well for the scenarios tested, but # other cases may benefit from tuning these. update_step_size = 1e-4 number_optimization_steps = 100 # Convert to quaternions to enforce normalization. query_quaternions = tfg.quaternion.from_rotation_matrix(max_rotations) query_quaternions = tf.Variable(query_quaternions, trainable=True) @tf.function def gradient_ascent_step(query_quaternions): with tf.GradientTape() as tape: query_rotations_inp = tfg.rotation_matrix_3d.from_quaternion( query_quaternions) query_rotations_inp = tf.reshape(query_rotations_inp, [-1, self.len_rotation]) query_rotations_inp = self.positional_encoding(query_rotations_inp) logits = self.implicit_model([vision_descriptions, query_rotations_inp], training=False) logits = tf.linalg.diag_part(logits[Ellipsis, 0]) # Maximize the network output without caring about normalization loss = -tf.reduce_mean(logits) grads = tape.gradient(loss, query_quaternions) query_quaternions.assign_add(-grads * update_step_size) query_quaternions.assign(tfg.quaternion.normalize(query_quaternions)) return for _ in range(number_optimization_steps): gradient_ascent_step(query_quaternions) max_rotations = tfg.rotation_matrix_3d.from_quaternion(query_quaternions) return max_rotations def compute_loss(self, vision_description, rotation_matrix_gt): """Return the negative log likelihood of the ground truth rotation matrix. Args: vision_description: The vector representations of a batch of images. rotation_matrix_gt: The ground truth rotation matrices associated with the batch of images. Returns: A scalar, the loss of the batch. """ probs = self.predict_probability( vision_description, rotation_matrix_gt, training=True) loss = -tf.reduce_mean(tf.math.log(probs)) return loss def get_closest_available_grid(self, number_queries=None): if not number_queries: number_queries = self.number_eval_queries # HEALPix-SO(3) is defined only on 72 * 8^N points; we find the closest # valid grid size (in log space) to the requested size. # The largest grid size we consider has 19M points. grid_sizes = 72*8**np.arange(7) size = grid_sizes[ np.argmin(np.abs(np.log(number_queries) - np.log(grid_sizes))) ] if self.grids.get(size) is not None: return self.grids[size] else: logging.info('Using grid of size %d. Requested was %d.', size, number_queries) grid_created = False if not grid_created: self.grids[size] = np.float32(generate_healpix_grid(size=size)) return self.grids[size] def generate_queries(self, number_queries, mode='random'): """Generate query rotations from SO(3). Args: number_queries: The number of queries. mode: 'random' or 'grid'; determines whether to generate rotations from the uniform distribution over SO(3), or use an equivolumetric grid. Returns: A tensor of rotation matrices, shape [num_queries, 3, 3]. """ if mode == 'random': return self.generate_queries_random(number_queries) elif mode == 'grid': return self.get_closest_available_grid(number_queries) def generate_queries_random(self, number_queries): """Generate rotation matrices from SO(3) uniformly at random. Args: number_queries: The number of queries. Returns: A tensor of shape [number_queries, 3, 3]. """ random_quaternions = tfg.quaternion.normalized_random_uniform( (number_queries,)) random_rotations = tfg.rotation_matrix_3d.from_quaternion( random_quaternions) random_rotations = tf.cast(random_rotations, tf.float32) return random_rotations def positional_encoding(self, query_rotations): """This handles the positional encoding. Args: query_rotations: tensor of shape [N, len_rotation] or [bs, N, len_rotation]. Returns: Tensor of shape [N, len_query] or [bs, N, len_query]. """ if self.frequencies.shape[0] == 0: return query_rotations def _enc(freq): return tf.concat( [tf.math.sin(query_rotations * freq), tf.math.cos(query_rotations * freq)], -1) query_rotations = tf.map_fn(_enc, self.frequencies) query_shape = tf.shape(query_rotations) if len(query_shape) == 4: query_rotations = tf.transpose(query_rotations, [1, 2, 0, 3]) shape = tf.concat([query_shape[1:3], [self.len_query]], axis=0) query_rotations = tf.reshape(query_rotations, shape) else: query_rotations = tf.transpose(query_rotations, [1, 0, 2]) query_rotations = tf.reshape(query_rotations, [-1, self.len_query]) return query_rotations def output_pdf(self, vision_description, num_queries=None, query_rotations=None): """Returns a normalized distribution over pose, given a vision description. Args: vision_description: A batch of feature vectors, representing the images on which to estimate the pose. num_queries: The number of queries to evaluate the probability for. query_rotations: If supplied, these rotations will be used to evaluate the distribution and normalize it, instead using the kwarg num_queries. Returns: Both the rotations and their corresponding probabilities. """ if num_queries is None: num_queries = self.number_eval_queries if query_rotations is None: query_rotations = self.get_closest_available_grid(num_queries) query_rotations_enc = tf.reshape(query_rotations, [-1, self.len_rotation]) query_rotations_enc = self.positional_encoding(query_rotations_enc) log_probabilities = self.implicit_model( [vision_description, query_rotations_enc], training=False)[Ellipsis, 0] probabilities = tf.nn.softmax(log_probabilities, axis=-1) return query_rotations, probabilities def generate_healpix_grid(recursion_level=None, size=None): """Generates an equivolumetric grid on SO(3) following Yershova et al. (2010). Uses a Healpix grid on the 2-sphere as a starting point and then tiles it along the 'tilt' direction 6*2**recursion_level times over 2pi. Args: recursion_level: An integer which determines the level of resolution of the grid. The final number of points will be 72*8**recursion_level. A recursion_level of 2 (4k points) was used for training and 5 (2.4M points) for evaluation. size: A number of rotations to be included in the grid. The nearest grid size in log space is returned. Returns: (N, 3, 3) array of rotation matrices, where N=72*8**recursion_level. """ import healpy as hp # pylint: disable=g-import-not-at-top assert not(recursion_level is None and size is None) if size: recursion_level = max(int(np.round(np.log(size/72.)/np.log(8.))), 0) number_per_side = 2**recursion_level number_pix = hp.nside2npix(number_per_side) s2_points = hp.pix2vec(number_per_side, np.arange(number_pix)) s2_points = np.stack([*s2_points], 1) # Take these points on the sphere and azimuths = np.arctan2(s2_points[:, 1], s2_points[:, 0]) tilts = np.linspace(0, 2*np.pi, 6*2**recursion_level, endpoint=False) polars = np.arccos(s2_points[:, 2]) grid_rots_mats = [] for tilt in tilts: # Build up the rotations from Euler angles, zyz format rot_mats = tfg.rotation_matrix_3d.from_euler( np.stack([azimuths, np.zeros(number_pix), np.zeros(number_pix)], 1)) rot_mats = rot_mats @ tfg.rotation_matrix_3d.from_euler( np.stack([np.zeros(number_pix), np.zeros(number_pix), polars], 1)) rot_mats = rot_mats @ tf.expand_dims( tfg.rotation_matrix_3d.from_euler([tilt, 0., 0.]), 0) grid_rots_mats.append(rot_mats) grid_rots_mats = np.concatenate(grid_rots_mats, 0) return grid_rots_mats
# Copyright 2014 PerfKitBenchmarker 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. """Runs plain netperf in a few modes. docs: http://www.netperf.org/svn/netperf2/tags/netperf-2.4.5/doc/netperf.html#TCP_005fRR manpage: http://manpages.ubuntu.com/manpages/maverick/man1/netperf.1.html Runs TCP_RR, TCP_CRR, and TCP_STREAM benchmarks from netperf across two machines. """ import os import csv import io import json import logging from collections import Counter from perfkitbenchmarker import configs from perfkitbenchmarker import data from perfkitbenchmarker import flag_util from perfkitbenchmarker import flags from perfkitbenchmarker import sample from perfkitbenchmarker import vm_util from perfkitbenchmarker.linux_packages import netperf flags.DEFINE_integer('netperf_max_iter', None, 'Maximum number of iterations to run during ' 'confidence interval estimation. If unset, ' 'a single iteration will be run.', lower_bound=3, upper_bound=30) flags.DEFINE_integer('netperf_test_length', 60, 'netperf test length, in seconds', lower_bound=1) flags.DEFINE_bool('netperf_enable_histograms', True, 'Determines whether latency histograms are ' 'collected/reported. Only for *RR benchmarks') flag_util.DEFINE_integerlist('netperf_num_streams', flag_util.IntegerList([1]), 'Number of netperf processes to run. Netperf ' 'will run once for each value in the list.') flags.DEFINE_integer('netperf_thinktime', 0, 'Time in nanoseconds to do work for each request.') flags.DEFINE_integer('netperf_thinktime_array_size', 0, 'The size of the array to traverse for thinktime.') flags.DEFINE_integer('netperf_thinktime_run_length', 0, 'The number of contiguous numbers to sum at a time in the ' 'thinktime array.') ALL_BENCHMARKS = ['TCP_RR', 'TCP_CRR', 'TCP_STREAM', 'UDP_RR'] flags.DEFINE_list('netperf_benchmarks', ALL_BENCHMARKS, 'The netperf benchmark(s) to run.') flags.RegisterValidator( 'netperf_benchmarks', lambda benchmarks: benchmarks and set(benchmarks).issubset(ALL_BENCHMARKS)) FLAGS = flags.FLAGS BENCHMARK_NAME = 'netperf' BENCHMARK_CONFIG = """ netperf: description: Run TCP_RR, TCP_CRR, UDP_RR and TCP_STREAM vm_groups: vm_1: vm_spec: *default_single_core vm_2: vm_spec: *default_single_core """ MBPS = 'Mbits/sec' TRANSACTIONS_PER_SECOND = 'transactions_per_second' # Command ports are even (id*2), data ports are odd (id*2 + 1) PORT_START = 20000 REMOTE_SCRIPTS_DIR = 'netperf_test_scripts' REMOTE_SCRIPT = 'netperf_test.py' PERCENTILES = [50, 90, 99] def GetConfig(user_config): return configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME) def PrepareNetperf(vm): """Installs netperf on a single vm.""" vm.Install('netperf') def Prepare(benchmark_spec): """Install netperf on the target vm. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. """ vms = benchmark_spec.vms vms = vms[:2] vm_util.RunThreaded(PrepareNetperf, vms) num_streams = max(FLAGS.netperf_num_streams) # Start the netserver processes if vm_util.ShouldRunOnExternalIpAddress(): # Open all of the command and data ports vms[1].AllowPort(PORT_START, PORT_START + num_streams * 2 - 1) netserver_cmd = ('for i in $(seq {port_start} 2 {port_end}); do ' '{netserver_path} -p $i & done').format( port_start=PORT_START, port_end=PORT_START + num_streams * 2 - 1, netserver_path=netperf.NETSERVER_PATH) vms[1].RemoteCommand(netserver_cmd) # Install some stuff on the client vm vms[0].Install('pip') vms[0].RemoteCommand('sudo pip install python-gflags==2.0') # Create a scratch directory for the remote test script vms[0].RemoteCommand('sudo mkdir -p /tmp/run/') vms[0].RemoteCommand('sudo chmod 777 /tmp/run/') # Copy remote test script to client path = data.ResourcePath(os.path.join(REMOTE_SCRIPTS_DIR, REMOTE_SCRIPT)) logging.info('Uploading %s to %s', path, vms[0]) vms[0].PushFile(path, '/tmp/run/') vms[0].RemoteCommand('sudo chmod 777 /tmp/run/%s' % REMOTE_SCRIPT) def _HistogramStatsCalculator(histogram, percentiles=PERCENTILES): """ Computes values at percentiles in a distribution as well as stddev. Args: histogram: A dict mapping values to the number of samples with that value. Returns: A dict mapping stat names to their values. """ stats = {} # Histogram data in list form sorted by key by_value = sorted([(value, count) for value, count in histogram.items()], key=lambda x: x[0]) total_count = sum(histogram.values()) cur_value_index = 0 # Current index in by_value cur_index = 0 # Number of values we've passed so far for p in percentiles: index = int(float(total_count) * float(p) / 100.0) index = min(index, total_count - 1) # Handle 100th percentile for value, count in by_value[cur_value_index:]: if cur_index + count > index: stats['p%s' % str(p)] = by_value[cur_value_index][0] break else: cur_index += count cur_value_index += 1 # Compute stddev value_sum = float(sum([value * count for value, count in histogram.items()])) average = value_sum / float(total_count) if total_count > 1: total_of_squares = sum([(value - average) ** 2 * count for value, count in histogram.items()]) stats['stddev'] = (total_of_squares / (total_count - 1)) ** 0.5 else: stats['stddev'] = 0 return stats def _ParseNetperfOutput(stdout, metadata, benchmark_name, enable_latency_histograms): """Parses the stdout of a single netperf process. Args: stdout: the stdout of the netperf process metadata: metadata for any sample.Sample objects we create Returns: A tuple containing (throughput_sample, latency_samples, latency_histogram) """ # Don't modify the metadata dict that was passed in metadata = metadata.copy() # Extract stats from stdout # Sample output: # # "MIGRATED TCP REQUEST/RESPONSE TEST from 0.0.0.0 (0.0.0.0) port 20001 # AF_INET to 104.154.50.86 () port 20001 AF_INET : +/-2.500% @ 99% conf. # : first burst 0",\n # Throughput,Throughput Units,Throughput Confidence Width (%), # Confidence Iterations Run,Stddev Latency Microseconds, # 50th Percentile Latency Microseconds,90th Percentile Latency Microseconds, # 99th Percentile Latency Microseconds,Minimum Latency Microseconds, # Maximum Latency Microseconds\n # 1405.50,Trans/s,2.522,4,783.80,683,735,841,600,900\n try: fp = io.StringIO(stdout) # "-o" flag above specifies CSV output, but there is one extra header line: banner = next(fp) assert banner.startswith('MIGRATED'), stdout r = csv.DictReader(fp) results = next(r) logging.info('Netperf Results: %s', results) assert 'Throughput' in results except: raise Exception('Netperf ERROR: Failed to parse stdout. STDOUT: %s' % stdout) # Update the metadata with some additional infos meta_keys = [('Confidence Iterations Run', 'confidence_iter'), ('Throughput Confidence Width (%)', 'confidence_width_percent')] metadata.update({meta_key: results[netperf_key] for netperf_key, meta_key in meta_keys}) # Create the throughput sample throughput = float(results['Throughput']) throughput_units = results['Throughput Units'] if throughput_units == '10^6bits/s': # TCP_STREAM benchmark unit = MBPS metric = '%s_Throughput' % benchmark_name elif throughput_units == 'Trans/s': # *RR benchmarks unit = TRANSACTIONS_PER_SECOND metric = '%s_Transaction_Rate' % benchmark_name else: raise ValueError('Netperf output specifies unrecognized throughput units %s' % throughput_units) throughput_sample = sample.Sample(metric, throughput, unit, metadata) latency_hist = None latency_samples = [] if enable_latency_histograms: # Parse the latency histogram. {latency: count} where "latency" is the # latency in microseconds with only 2 significant figures and "count" is the # number of response times that fell in that latency range. latency_hist = netperf.ParseHistogram(stdout) hist_metadata = {'histogram': json.dumps(latency_hist)} hist_metadata.update(metadata) latency_samples.append(sample.Sample( '%s_Latency_Histogram' % benchmark_name, 0, 'us', hist_metadata)) if unit != MBPS: for metric_key, metric_name in [ ('50th Percentile Latency Microseconds', 'p50'), ('90th Percentile Latency Microseconds', 'p90'), ('99th Percentile Latency Microseconds', 'p99'), ('Minimum Latency Microseconds', 'min'), ('Maximum Latency Microseconds', 'max'), ('Stddev Latency Microseconds', 'stddev')]: if metric_key in results: latency_samples.append( sample.Sample('%s_Latency_%s' % (benchmark_name, metric_name), float(results[metric_key]), 'us', metadata)) return (throughput_sample, latency_samples, latency_hist) def RunNetperf(vm, benchmark_name, server_ip, num_streams): """Spawns netperf on a remote VM, parses results. Args: vm: The VM that the netperf TCP_RR benchmark will be run upon. benchmark_name: The netperf benchmark to run, see the documentation. server_ip: A machine that is running netserver. num_streams: The number of netperf client threads to run. Returns: A sample.Sample object with the result. """ enable_latency_histograms = FLAGS.netperf_enable_histograms or num_streams > 1 # Throughput benchmarks don't have latency histograms enable_latency_histograms = enable_latency_histograms and \ benchmark_name != 'TCP_STREAM' # Flags: # -o specifies keys to include in CSV output. # -j keeps additional latency numbers # -v sets the verbosity level so that netperf will print out histograms # -I specifies the confidence % and width - here 99% confidence that the true # value is within +/- 2.5% of the reported value # -i specifies the maximum and minimum number of iterations. confidence = ('-I 99,5 -i {0},3'.format(FLAGS.netperf_max_iter) if FLAGS.netperf_max_iter else '') verbosity = '-v2 ' if enable_latency_histograms else '' netperf_cmd = ('{netperf_path} -p {{command_port}} -j {verbosity} ' '-t {benchmark_name} -H {server_ip} -l {length} {confidence}' ' -- ' '-P ,{{data_port}} ' '-o THROUGHPUT,THROUGHPUT_UNITS,P50_LATENCY,P90_LATENCY,' 'P99_LATENCY,STDDEV_LATENCY,' 'MIN_LATENCY,MAX_LATENCY,' 'CONFIDENCE_ITERATION,THROUGHPUT_CONFID').format( netperf_path=netperf.NETPERF_PATH, benchmark_name=benchmark_name, server_ip=server_ip, length=FLAGS.netperf_test_length, confidence=confidence, verbosity=verbosity) if FLAGS.netperf_thinktime != 0: netperf_cmd += (' -U {thinktime},{thinktime_array_size},' '{thinktime_run_length} ').format( thinktime=FLAGS.netperf_thinktime, thinktime_array_size=FLAGS.netperf_thinktime_array_size, thinktime_run_length=FLAGS.netperf_thinktime_run_length) # Run all of the netperf processes and collect their stdout # TODO: Record start times of netperf processes on the remote machine remote_script_path = '/tmp/run/%s' % REMOTE_SCRIPT remote_cmd = '%s --netperf_cmd="%s" --num_streams=%s --port_start=%s' % \ (remote_script_path, netperf_cmd, num_streams, PORT_START) remote_stdout, _ = vm.RemoteCommand(remote_cmd) # Decode stdouts, stderrs, and return codes from remote command's stdout stdouts, stderrs, return_codes = json.loads(remote_stdout) # Metadata to attach to samples metadata = {'netperf_test_length': FLAGS.netperf_test_length, 'max_iter': FLAGS.netperf_max_iter or 1, 'sending_thread_count': num_streams} parsed_output = [_ParseNetperfOutput(stdout, metadata, benchmark_name, enable_latency_histograms) for stdout in stdouts] if len(parsed_output) == 1: # Only 1 netperf thread throughput_sample, latency_samples, histogram = parsed_output[0] return [throughput_sample] + latency_samples else: # Multiple netperf threads samples = [] # Unzip parsed output # Note that latency_samples are invalid with multiple threads because stats # are computed per-thread by netperf, so we don't use them here. throughput_samples, _, latency_histograms = [list(t) for t in zip(*parsed_output)] # They should all have the same units throughput_unit = throughput_samples[0].unit # Extract the throughput values from the samples throughputs = [s.value for s in throughput_samples] # Compute some stats on the throughput values throughput_stats = sample.PercentileCalculator(throughputs, [50, 90, 99]) throughput_stats['min'] = min(throughputs) throughput_stats['max'] = max(throughputs) # Calculate aggregate throughput throughput_stats['total'] = throughput_stats['average'] * len(throughputs) # Create samples for throughput stats for stat, value in throughput_stats.items(): samples.append( sample.Sample('%s_Throughput_%s' % (benchmark_name, stat), float(value), throughput_unit, metadata)) if enable_latency_histograms: # Combine all of the latency histogram dictionaries latency_histogram = Counter() for histogram in latency_histograms: latency_histogram.update(histogram) # Create a sample for the aggregate latency histogram hist_metadata = {'histogram': json.dumps(latency_histogram)} hist_metadata.update(metadata) samples.append(sample.Sample( '%s_Latency_Histogram' % benchmark_name, 0, 'us', hist_metadata)) # Calculate stats on aggregate latency histogram latency_stats = _HistogramStatsCalculator(latency_histogram, [50, 90, 99]) # Create samples for the latency stats for stat, value in latency_stats.items(): samples.append( sample.Sample('%s_Latency_%s' % (benchmark_name, stat), float(value), 'us', metadata)) return samples def Run(benchmark_spec): """Run netperf TCP_RR on the target vm. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. Returns: A list of sample.Sample objects. """ vms = benchmark_spec.vms client_vm = vms[0] # Client aka "sending vm" server_vm = vms[1] # Server aka "receiving vm" logging.info('netperf running on %s', client_vm) results = [] metadata = { 'sending_zone': client_vm.zone, 'sending_machine_type': client_vm.machine_type, 'receiving_zone': server_vm.zone, 'receiving_machine_type': server_vm.machine_type } for num_streams in FLAGS.netperf_num_streams: assert(num_streams >= 1) for netperf_benchmark in FLAGS.netperf_benchmarks: if vm_util.ShouldRunOnExternalIpAddress(): external_ip_results = RunNetperf(client_vm, netperf_benchmark, server_vm.ip_address, num_streams) for external_ip_result in external_ip_results: external_ip_result.metadata['ip_type'] = 'external' external_ip_result.metadata.update(metadata) results.extend(external_ip_results) if vm_util.ShouldRunOnInternalIpAddress(client_vm, server_vm): internal_ip_results = RunNetperf(client_vm, netperf_benchmark, server_vm.internal_ip, num_streams) for internal_ip_result in internal_ip_results: internal_ip_result.metadata.update(metadata) internal_ip_result.metadata['ip_type'] = 'internal' results.extend(internal_ip_results) return results def Cleanup(benchmark_spec): """Cleanup netperf on the target vm (by uninstalling). Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. """ vms = benchmark_spec.vms vms[1].RemoteCommand('sudo killall netserver') vms[0].RemoteCommand('sudo rm -rf /tmp/run/')
#!/usr/bin/env python # native Python imports import os.path import sys import sqlite3 import numpy as np import shutil import uuid # third-party imports import cyvcf as vcf # gemini modules import version from ped import load_ped_file import gene_table import infotag import database import annotations import func_impact import severe_impact import popgen import structural_variants as svs from gemini_constants import * from compression import pack_blob from gemini.config import read_gemini_config def get_phred_lik(gt_phred_likelihoods, dtype=np.int32, empty_val=-1): """ Force each sample to have 3 GL's (0/0, 0/1, 1/1). If no samples have GL's, then we just return None to save space. """ m = np.iinfo(dtype).max - 1 out = [] all_empty = True empty_line = [empty_val] * 3 for row in gt_phred_likelihoods: # we only try to use the correct PL's if it already has size 3 if row is not None and isinstance(row, (list, tuple)) and len(row) == 3: out.append([min(m, int(v)) if v is not None else empty_val for v in row]) all_empty = False else: out.append(empty_line) if all_empty: return None return np.array(out, dtype=dtype) class GeminiLoader(object): """ Object for creating and populating a gemini database and auxillary data files. """ def __init__(self, args, buffer_size=10000): self.args = args self.seen_multi = False # create the gemini database self._create_db() # create a reader for the VCF file self.vcf_reader = self._get_vcf_reader() # load sample information if not self.args.no_genotypes and not self.args.no_load_genotypes: # load the sample info from the VCF file. self._prepare_samples() # initialize genotype counts for each sample self._init_sample_gt_counts() self.num_samples = len(self.samples) else: self.num_samples = 0 self.buffer_size = buffer_size self._get_anno_version() if not args.skip_gene_tables: self._get_gene_detailed() self._get_gene_summary() if self.args.anno_type == "VEP": self._effect_fields = self._get_vep_csq(self.vcf_reader) else: self._effect_fields = [] def store_vcf_header(self): """Store the raw VCF header. """ database.insert_vcf_header(self.c, self.vcf_reader.raw_header) def store_resources(self): """Create table of annotation resources used in this gemini database. """ database.insert_resources(self.c, annotations.get_resources(self.args)) def store_version(self): """Create table documenting which gemini version was used for this db. """ database.insert_version(self.c, version.__version__) def _get_vid(self): if hasattr(self.args, 'offset'): v_id = int(self.args.offset) else: v_id = 1 return v_id def _multiple_alts_message(self): self.seen_multi = 1 sys.stderr.write("\n") sys.stderr.write("warning: variant with multiple alternate alleles found.\n") sys.stderr.write(" in order to reduce the number of false negatives\n") sys.stderr.write(" we recommend to split multiple alts. see: \ http://gemini.readthedocs.org/en/latest/content/preprocessing.html#preprocess\n") def populate_from_vcf(self): """ """ import gemini_annotate as ga extra_vcf_fields = set() self.v_id = self._get_vid() self.counter = 0 self.var_buffer = [] self.var_impacts_buffer = [] self.skipped = 0 # we save the vcf in this chunk for extra annotations. self.extra_vcf_writer = ga.get_extra_vcf(self.args.db, self.vcf_reader) # process and load each variant in the VCF file for var in self.vcf_reader: if len(var.ALT) > 1 and not self.seen_multi: self._multiple_alts_message() if self.args.passonly and (var.FILTER is not None and var.FILTER != "."): self.skipped += 1 continue (variant, variant_impacts, extra_fields) = self._prepare_variation(var) if extra_fields: var.INFO.update(extra_fields) self.extra_vcf_writer.write_record(var) extra_vcf_fields.update(extra_fields.keys()) # add the core variant info to the variant buffer self.var_buffer.append(variant) # add each of the impact for this variant (1 per gene/transcript) for var_impact in variant_impacts: self.var_impacts_buffer.append(var_impact) # buffer full - time to insert into DB if len(self.var_buffer) >= self.buffer_size: sys.stderr.write("pid " + str(os.getpid()) + ": " + str(self.counter) + " variants processed.\n") database.insert_variation(self.c, self.var_buffer) database.insert_variation_impacts(self.c, self.var_impacts_buffer) # binary.genotypes.append(var_buffer) # reset for the next batch self.var_buffer = [] self.var_impacts_buffer = [] self.v_id += 1 self.counter += 1 # final load to the database self.v_id -= 1 database.insert_variation(self.c, self.var_buffer) database.insert_variation_impacts(self.c, self.var_impacts_buffer) sys.stderr.write("pid " + str(os.getpid()) + ": " + str(self.counter) + " variants processed.\n") if self.args.passonly: sys.stderr.write("pid " + str(os.getpid()) + ": " + str(self.skipped) + " skipped due to having the " "FILTER field set.\n") self.extra_vcf_writer.stream.close() if len(extra_vcf_fields) == 0: os.unlink(self.extra_vcf_writer.stream.name) else: with open(self.extra_vcf_writer.stream.name + ".fields", "w") as o: o.write("\n".join(list(extra_vcf_fields))) def _update_extra_headers(self, headers, cur_fields): """Update header information for extra fields. """ for field, val in cur_fields.items(): headers[field] = self._get_field_type(val, headers.get(field, "integer")) return headers def _get_field_type(self, val, cur_type): start_checking = False for name, check_fn in [("integer", int), ("float", float), ("text", str)]: if name == cur_type: start_checking = True if start_checking: try: check_fn(val) break except: continue return name def build_indices_and_disconnect(self): """ Create the db table indices and close up db connection """ # index our tables for speed database.create_indices(self.c) # commit data and close up database.close_and_commit(self.c, self.conn) def _get_vcf_reader(self): # the VCF is a proper file if self.args.vcf != "-": if self.args.vcf.endswith(".gz"): return vcf.VCFReader(open(self.args.vcf), 'rb', compressed=True) else: return vcf.VCFReader(open(self.args.vcf), 'rb') # the VCF is being passed in via STDIN else: return vcf.VCFReader(sys.stdin, 'rb') def _get_anno_version(self): """ Extract the snpEff or VEP version used to annotate the VCF """ # default to unknown version self.args.version = None if self.args.anno_type == "snpEff": try: version_string = self.vcf_reader.metadata['SnpEffVersion'] except KeyError: error = ("\nWARNING: VCF is not annotated with snpEff, check documentation at:\n"\ "http://gemini.readthedocs.org/en/latest/content/functional_annotation.html#stepwise-installation-and-usage-of-snpeff\n") sys.exit(error) # e.g., "SnpEff 3.0a (build 2012-07-08), by Pablo Cingolani" # or "3.3c (build XXXX), by Pablo Cingolani" version_string = version_string.replace('"', '') # No quotes toks = version_string.split() if "SnpEff" in toks[0]: self.args.raw_version = toks[1] # SnpEff *version*, etc else: self.args.raw_version = toks[0] # *version*, etc # e.g., 3.0a -> 3 self.args.maj_version = int(self.args.raw_version.split('.')[0]) elif self.args.anno_type == "VEP": pass def _get_vep_csq(self, reader): """ Test whether the VCF header meets expectations for proper execution of VEP for use with Gemini. """ required = ["Consequence"] expected = "Consequence|Codons|Amino_acids|Gene|SYMBOL|Feature|EXON|PolyPhen|SIFT|Protein_position|BIOTYPE".upper() if 'CSQ' in reader.infos: parts = str(reader.infos["CSQ"].desc).split("Format: ")[-1].split("|") all_found = True for check in required: if check not in parts: all_found = False break if all_found: return parts # Did not find expected fields error = "\nERROR: Check gemini docs for the recommended VCF annotation with VEP"\ "\nhttp://gemini.readthedocs.org/en/latest/content/functional_annotation.html#stepwise-installation-and-usage-of-vep" sys.exit(error) def _create_db(self): """ private method to open a new DB and create the gemini schema. """ # open up a new database db_path = self.args.db if not hasattr(self.args, 'tmp_db') else self.args.tmp_db if os.path.exists(db_path): os.remove(db_path) self.conn = sqlite3.connect(db_path) self.conn.isolation_level = None self.c = self.conn.cursor() self.c.execute('PRAGMA synchronous = OFF') self.c.execute('PRAGMA journal_mode=MEMORY') # create the gemini database tables for the new DB database.create_tables(self.c) database.create_sample_table(self.c, self.args) def _prepare_variation(self, var): """private method to collect metrics for a single variant (var) in a VCF file. Extracts variant information, variant impacts and extra fields for annotation. """ extra_fields = {} # these metric require that genotypes are present in the file call_rate = None hwe_p_value = None pi_hat = None inbreeding_coeff = None hom_ref = het = hom_alt = unknown = None # only compute certain metrics if genoypes are available if not self.args.no_genotypes and not self.args.no_load_genotypes: hom_ref = var.num_hom_ref hom_alt = var.num_hom_alt het = var.num_het unknown = var.num_unknown call_rate = var.call_rate aaf = var.aaf hwe_p_value, inbreeding_coeff = \ popgen.get_hwe_likelihood(hom_ref, het, hom_alt, aaf) pi_hat = var.nucl_diversity else: aaf = infotag.extract_aaf(var) ############################################################ # collect annotations from gemini's custom annotation files # but only if the size of the variant is <= 50kb ############################################################ if var.end - var.POS < 50000: pfam_domain = annotations.get_pfamA_domains(var) cyto_band = annotations.get_cyto_info(var) rs_ids = annotations.get_dbsnp_info(var) clinvar_info = annotations.get_clinvar_info(var) in_dbsnp = 0 if rs_ids is None else 1 rmsk_hits = annotations.get_rmsk_info(var) in_cpg = annotations.get_cpg_island_info(var) in_segdup = annotations.get_segdup_info(var) is_conserved = annotations.get_conservation_info(var) esp = annotations.get_esp_info(var) thousandG = annotations.get_1000G_info(var) recomb_rate = annotations.get_recomb_info(var) gms = annotations.get_gms(var) grc = annotations.get_grc(var) in_cse = annotations.get_cse(var) encode_tfbs = annotations.get_encode_tfbs(var) encode_dnaseI = annotations.get_encode_dnase_clusters(var) encode_cons_seg = annotations.get_encode_consensus_segs(var) gerp_el = annotations.get_gerp_elements(var) vista_enhancers = annotations.get_vista_enhancers(var) cosmic_ids = annotations.get_cosmic_info(var) fitcons = annotations.get_fitcons(var) Exac = annotations.get_exac_info(var) #load CADD scores by default if self.args.skip_cadd is False: (cadd_raw, cadd_scaled) = annotations.get_cadd_scores(var) else: (cadd_raw, cadd_scaled) = (None, None) # load the GERP score for this variant by default. gerp_bp = None if self.args.skip_gerp_bp is False: gerp_bp = annotations.get_gerp_bp(var) # the variant is too big to annotate else: pfam_domain = None cyto_band = None rs_ids = None clinvar_info = annotations.ClinVarInfo() in_dbsnp = None rmsk_hits = None in_cpg = None in_segdup = None is_conserved = None esp = annotations.ESPInfo(None, None, None, None, None) thousandG = annotations.ThousandGInfo(None, None, None, None, None, None, None) Exac = annotations.ExacInfo(None, None, None, None, None, None, None, None, None, None) recomb_rate = None gms = annotations.GmsTechs(None, None, None) grc = None in_cse = None encode_tfbs = None encode_dnaseI = annotations.ENCODEDnaseIClusters(None, None) encode_cons_seg = annotations.ENCODESegInfo(None, None, None, None, None, None) gerp_el = None vista_enhancers = None cosmic_ids = None fitcons = None cadd_raw = None cadd_scaled = None gerp_bp = None # impact is a list of impacts for this variant impacts = None severe_impacts = None # impact terms initialized to None for handling unannotated vcf's # anno_id in variants is for the trans. with the most severe impact term gene = transcript = exon = codon_change = aa_change = aa_length = \ biotype = consequence = consequence_so = effect_severity = None is_coding = is_exonic = is_lof = None polyphen_pred = polyphen_score = sift_pred = sift_score = anno_id = None if self.args.anno_type is not None: impacts = func_impact.interpret_impact(self.args, var, self._effect_fields) severe_impacts = \ severe_impact.interpret_severe_impact(self.args, var, self._effect_fields) if severe_impacts: extra_fields.update(severe_impacts.extra_fields) gene = severe_impacts.gene transcript = severe_impacts.transcript exon = severe_impacts.exon codon_change = severe_impacts.codon_change aa_change = severe_impacts.aa_change aa_length = severe_impacts.aa_length biotype = severe_impacts.biotype consequence = severe_impacts.consequence effect_severity = severe_impacts.effect_severity polyphen_pred = severe_impacts.polyphen_pred polyphen_score = severe_impacts.polyphen_score sift_pred = severe_impacts.sift_pred sift_score = severe_impacts.sift_score anno_id = severe_impacts.anno_id is_exonic = severe_impacts.is_exonic is_coding = severe_impacts.is_coding is_lof = severe_impacts.is_lof consequence_so = severe_impacts.so # construct the filter string filter = None if var.FILTER is not None and var.FILTER != ".": if isinstance(var.FILTER, list): filter = ";".join(var.FILTER) else: filter = var.FILTER vcf_id = None if var.ID is not None and var.ID != ".": vcf_id = var.ID # build up numpy arrays for the genotype information. # these arrays will be pickled-to-binary, compressed, # and loaded as SqlLite BLOB values (see compression.pack_blob) gt_phred_ll_homref = gt_phred_ll_het = gt_phred_ll_homalt = None if not self.args.no_genotypes and not self.args.no_load_genotypes: gt_bases = np.array(var.gt_bases, np.str) # 'A/G', './.' gt_types = np.array(var.gt_types, np.int8) # -1, 0, 1, 2 gt_phases = np.array(var.gt_phases, np.bool) # T F F gt_depths = np.array(var.gt_depths, np.int32) # 10 37 0 gt_ref_depths = np.array(var.gt_ref_depths, np.int32) # 2 21 0 -1 gt_alt_depths = np.array(var.gt_alt_depths, np.int32) # 8 16 0 -1 gt_quals = np.array(var.gt_quals, np.float32) # 10.78 22 99 -1 gt_copy_numbers = np.array(var.gt_copy_numbers, np.float32) # 1.0 2.0 2.1 -1 gt_phred_likelihoods = get_phred_lik(var.gt_phred_likelihoods) if gt_phred_likelihoods is not None: gt_phred_ll_homref = gt_phred_likelihoods[:, 0] gt_phred_ll_het = gt_phred_likelihoods[:, 1] gt_phred_ll_homalt = gt_phred_likelihoods[:, 2] # tally the genotypes self._update_sample_gt_counts(gt_types) else: gt_bases = gt_types = gt_phases = gt_depths = gt_ref_depths = None gt_alt_depths = gt_quals = gt_copy_numbers = None if self.args.skip_info_string: info = None else: info = var.INFO # were functional impacts predicted by SnpEFF or VEP? # if so, build up a row for each of the impacts / transcript variant_impacts = [] for idx, impact in enumerate(impacts or [], start=1): var_impact = [self.v_id, idx, impact.gene, impact.transcript, impact.is_exonic, impact.is_coding, impact.is_lof, impact.exon, impact.codon_change, impact.aa_change, impact.aa_length, impact.biotype, impact.consequence, impact.so, impact.effect_severity, impact.polyphen_pred, impact.polyphen_score, impact.sift_pred, impact.sift_score] variant_impacts.append(var_impact) # extract structural variants sv = svs.StructuralVariant(var) ci_left = sv.get_ci_left() ci_right = sv.get_ci_right() # construct the core variant record. # 1 row per variant to VARIANTS table chrom = var.CHROM if var.CHROM.startswith("chr") else "chr" + var.CHROM variant = [chrom, var.start, var.end, vcf_id, self.v_id, anno_id, var.REF, ','.join([x or "" for x in var.ALT]), var.QUAL, filter, var.var_type, var.var_subtype, pack_blob(gt_bases), pack_blob(gt_types), pack_blob(gt_phases), pack_blob(gt_depths), pack_blob(gt_ref_depths), pack_blob(gt_alt_depths), pack_blob(gt_quals), pack_blob(gt_copy_numbers), pack_blob(gt_phred_ll_homref), pack_blob(gt_phred_ll_het), pack_blob(gt_phred_ll_homalt), call_rate, in_dbsnp, rs_ids, ci_left[0], ci_left[1], ci_right[0], ci_right[1], sv.get_length(), sv.is_precise(), sv.get_sv_tool(), sv.get_evidence_type(), sv.get_event_id(), sv.get_mate_id(), sv.get_strand(), clinvar_info.clinvar_in_omim, clinvar_info.clinvar_sig, clinvar_info.clinvar_disease_name, clinvar_info.clinvar_dbsource, clinvar_info.clinvar_dbsource_id, clinvar_info.clinvar_origin, clinvar_info.clinvar_dsdb, clinvar_info.clinvar_dsdbid, clinvar_info.clinvar_disease_acc, clinvar_info.clinvar_in_locus_spec_db, clinvar_info.clinvar_on_diag_assay, clinvar_info.clinvar_causal_allele, pfam_domain, cyto_band, rmsk_hits, in_cpg, in_segdup, is_conserved, gerp_bp, gerp_el, hom_ref, het, hom_alt, unknown, aaf, hwe_p_value, inbreeding_coeff, pi_hat, recomb_rate, gene, transcript, is_exonic, is_coding, is_lof, exon, codon_change, aa_change, aa_length, biotype, consequence, consequence_so, effect_severity, polyphen_pred, polyphen_score, sift_pred, sift_score, infotag.get_ancestral_allele(var), infotag.get_rms_bq(var), infotag.get_cigar(var), infotag.get_depth(var), infotag.get_strand_bias(var), infotag.get_rms_map_qual(var), infotag.get_homopol_run(var), infotag.get_map_qual_zero(var), infotag.get_num_of_alleles(var), infotag.get_frac_dels(var), infotag.get_haplotype_score(var), infotag.get_quality_by_depth(var), infotag.get_allele_count(var), infotag.get_allele_bal(var), infotag.in_hm2(var), infotag.in_hm3(var), infotag.is_somatic(var), infotag.get_somatic_score(var), esp.found, esp.aaf_EA, esp.aaf_AA, esp.aaf_ALL, esp.exome_chip, thousandG.found, thousandG.aaf_AMR, thousandG.aaf_EAS, thousandG.aaf_SAS, thousandG.aaf_AFR, thousandG.aaf_EUR, thousandG.aaf_ALL, grc, gms.illumina, gms.solid, gms.iontorrent, in_cse, encode_tfbs, encode_dnaseI.cell_count, encode_dnaseI.cell_list, encode_cons_seg.gm12878, encode_cons_seg.h1hesc, encode_cons_seg.helas3, encode_cons_seg.hepg2, encode_cons_seg.huvec, encode_cons_seg.k562, vista_enhancers, cosmic_ids, pack_blob(info), cadd_raw, cadd_scaled, fitcons, Exac.found, Exac.aaf_ALL, Exac.adj_aaf_ALL, Exac.aaf_AFR, Exac.aaf_AMR, Exac.aaf_EAS, Exac.aaf_FIN, Exac.aaf_NFE, Exac.aaf_OTH, Exac.aaf_SAS] return variant, variant_impacts, extra_fields def _prepare_samples(self): """ private method to load sample information """ if not self.args.no_genotypes: self.samples = self.vcf_reader.samples self.sample_to_id = {} for idx, sample in enumerate(self.samples): self.sample_to_id[sample] = idx + 1 self.ped_hash = {} if self.args.ped_file is not None: self.ped_hash = load_ped_file(self.args.ped_file) sample_list = [] for sample in self.samples: i = self.sample_to_id[sample] if sample in self.ped_hash: fields = self.ped_hash[sample] sample_list = [i] + fields elif len(self.ped_hash) > 0: sys.exit("EXITING: sample %s found in the VCF but " "not in the PED file.\n" % (sample)) else: # if there is no ped file given, just fill in the name and # sample_id and set the other required fields to None sample_list = [i, 0, sample, 0, 0, -9, -9] database.insert_sample(self.c, sample_list) def _get_gene_detailed(self): """ define a gene detailed table """ #unique identifier for each entry i = 0 table_contents = detailed_list = [] config = read_gemini_config(args=self.args) path_dirname = config["annotation_dir"] file_handle = os.path.join(path_dirname, 'detailed_gene_table_v75') for line in open(file_handle, 'r'): field = line.strip().split("\t") if not field[0].startswith("Chromosome"): i += 1 table = gene_table.gene_detailed(field) detailed_list = [str(i),table.chrom,table.gene,table.is_hgnc, table.ensembl_gene_id,table.ensembl_trans_id, table.biotype,table.trans_status,table.ccds_id, table.hgnc_id,table.entrez,table.cds_length,table.protein_length, table.transcript_start,table.transcript_end, table.strand,table.synonym,table.rvis,table.mam_phenotype] table_contents.append(detailed_list) database.insert_gene_detailed(self.c, table_contents) def _get_gene_summary(self): """ define a gene summary table """ #unique identifier for each entry i = 0 contents = summary_list = [] config = read_gemini_config(args=self.args) path_dirname = config["annotation_dir"] file = os.path.join(path_dirname, 'summary_gene_table_v75') for line in open(file, 'r'): col = line.strip().split("\t") if not col[0].startswith("Chromosome"): i += 1 table = gene_table.gene_summary(col) # defaul cosmic census to False cosmic_census = 0 summary_list = [str(i),table.chrom,table.gene,table.is_hgnc, table.ensembl_gene_id,table.hgnc_id, table.transcript_min_start, table.transcript_max_end,table.strand, table.synonym,table.rvis,table.mam_phenotype, cosmic_census] contents.append(summary_list) database.insert_gene_summary(self.c, contents) def update_gene_table(self): """ """ gene_table.update_cosmic_census_genes(self.c, self.args) def _init_sample_gt_counts(self): """ Initialize a 2D array of counts for tabulating the count of each genotype type for eaxh sample. The first dimension is one bucket for each sample. The second dimension (size=4) is a count for each gt type. Index 0 == # of hom_ref genotypes for the sample Index 1 == # of het genotypes for the sample Index 2 == # of missing genotypes for the sample Index 3 == # of hom_alt genotypes for the sample """ self.sample_gt_counts = np.array(np.zeros((len(self.samples), 4)), dtype='uint32') def _update_sample_gt_counts(self, gt_types): """ Update the count of each gt type for each sample """ for idx, gt_type in enumerate(gt_types): self.sample_gt_counts[idx][gt_type] += 1 def store_sample_gt_counts(self): """ Update the count of each gt type for each sample """ self.c.execute("BEGIN TRANSACTION") for idx, gt_counts in enumerate(self.sample_gt_counts): self.c.execute("""insert into sample_genotype_counts values \ (?,?,?,?,?)""", [idx, int(gt_counts[HOM_REF]), # hom_ref int(gt_counts[HET]), # het int(gt_counts[HOM_ALT]), # hom_alt int(gt_counts[UNKNOWN])]) # missing self.c.execute("END") def load(parser, args): if (args.db is None or args.vcf is None): parser.print_help() exit("ERROR: load needs both a VCF file and a database file\n") if args.anno_type not in ['snpEff', 'VEP', None]: parser.print_help() exit("\nERROR: Unsupported selection for -t\n") # collect of the the add'l annotation files annotations.load_annos(args) # create a new gemini loader and populate # the gemini db and files from the VCF for try_count in range(2): try: if try_count > 0: args.tmp_db = os.path.join(args.tempdir, "%s.db" % uuid.uuid4()) gemini_loader = GeminiLoader(args) gemini_loader.store_resources() gemini_loader.store_version() gemini_loader.store_vcf_header() extra_fields = gemini_loader.populate_from_vcf() gemini_loader.update_gene_table() # gemini_loader.build_indices_and_disconnect() if not args.no_genotypes and not args.no_load_genotypes: gemini_loader.store_sample_gt_counts() if try_count > 0: shutil.move(args.tmp_db, args.db) break except sqlite3.OperationalError, e: sys.stderr.write("sqlite3.OperationalError: %s\n" % e) else: raise Exception(("Attempted workaround for SQLite locking issue on NFS " "drives has failed. One possible reason is that the temp directory " "%s is also on an NFS drive.") % args.tempdir)
# -*- coding: utf-8 -*- """ Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import print_function, unicode_literals import os from atomic_reactor.constants import YUM_REPOS_DIR, DEFAULT_YUM_REPOFILE_NAME, RELATIVE_REPOS_PATH try: from collections import OrderedDict except ImportError: # Python 2.6 from ordereddict import OrderedDict from dockerfile_parse import DockerfileParser from atomic_reactor.core import DockerTasker from atomic_reactor.inner import DockerBuildWorkflow from atomic_reactor.plugin import PreBuildPluginsRunner from atomic_reactor.plugins.pre_inject_yum_repo import InjectYumRepoPlugin, alter_yum_commands from atomic_reactor.util import ImageName, render_yum_repo import os.path from collections import namedtuple import requests from flexmock import flexmock from tests.fixtures import docker_tasker from tests.constants import SOURCE, MOCK if MOCK: from tests.docker_mock import mock_docker class X(object): pass def prepare(df_path, inherited_user=''): if MOCK: mock_docker() tasker = DockerTasker() workflow = DockerBuildWorkflow(SOURCE, "test-image") setattr(workflow, 'builder', X()) setattr(workflow.builder, 'image_id', "asd123") setattr(workflow.builder, 'df_path', str(df_path)) setattr(workflow.builder, 'df_dir', os.path.dirname(str(df_path))) setattr(workflow.builder, 'base_image', ImageName(repo='Fedora', tag='21')) setattr(workflow.builder, 'git_dockerfile_path', None) setattr(workflow.builder, 'git_path', None) setattr(workflow.builder, 'source', X()) setattr(workflow.builder.source, 'dockerfile_path', None) setattr(workflow.builder.source, 'path', '') inspection_data = {'Config': {'User': inherited_user}} workflow.builder.inspect_base_image = lambda: inspection_data (flexmock(requests.Response, content=repocontent) .should_receive('raise_for_status') .and_return(None)) (flexmock(requests, get=lambda *_: requests.Response())) return tasker, workflow def test_yuminject_plugin_notwrapped(tmpdir): df_content = """\ FROM fedora RUN yum install -y python-django CMD blabla""" df = DockerfileParser(str(tmpdir)) df.content = df_content tasker, workflow = prepare(df.dockerfile_path) metalink = 'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.files[os.path.join(YUM_REPOS_DIR, DEFAULT_YUM_REPOFILE_NAME)] = render_yum_repo(OrderedDict( (('name', 'my-repo'), ('metalink', metalink), ('enabled', 1), ('gpgcheck', 0)), )) runner = PreBuildPluginsRunner(tasker, workflow, [{ 'name': InjectYumRepoPlugin.key, 'args': { "wrap_commands": False } }]) runner.run() assert InjectYumRepoPlugin.key is not None expected_output = r"""FROM fedora ADD atomic-reactor-repos/* '/etc/yum.repos.d/' RUN yum install -y python-django CMD blabla RUN rm -f '/etc/yum.repos.d/atomic-reactor-injected.repo' """ assert expected_output == df.content def test_yuminject_plugin_wrapped(tmpdir, docker_tasker): df_content = """\ FROM fedora RUN yum install -y python-django CMD blabla""" df = DockerfileParser(str(tmpdir)) df.content = df_content workflow = DockerBuildWorkflow(SOURCE, "test-image") setattr(workflow, 'builder', X()) workflow.builder.source = workflow.source metalink = 'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.files[os.path.join(YUM_REPOS_DIR, DEFAULT_YUM_REPOFILE_NAME)] = render_yum_repo(OrderedDict( (('name', 'my-repo'), ('metalink', metalink), ('enabled', '1'), ('gpgcheck', '0')), )) setattr(workflow.builder, 'image_id', "asd123") setattr(workflow.builder, 'df_path', df.dockerfile_path) setattr(workflow.builder, 'df_dir', str(tmpdir)) setattr(workflow.builder, 'base_image', ImageName(repo='Fedora', tag='21')) setattr(workflow.builder, 'git_dockerfile_path', None) setattr(workflow.builder, 'git_path', None) runner = PreBuildPluginsRunner(docker_tasker, workflow, [{ 'name': InjectYumRepoPlugin.key, 'args': { "wrap_commands": True } }]) runner.run() assert InjectYumRepoPlugin.key is not None expected_output = """FROM fedora RUN printf "[my-repo]\nname=my-repo\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\nenabled=1\ngpgcheck=0\n" >/etc/yum.repos.d/atomic-reactor-injected.repo && yum install -y python-django && yum clean all && rm -f /etc/yum.repos.d/atomic-reactor-injected.repo CMD blabla""" assert df.content == expected_output def test_yuminject_multiline_wrapped(tmpdir, docker_tasker): df_content = """\ FROM fedora RUN yum install -y httpd \ uwsgi CMD blabla""" df = DockerfileParser(str(tmpdir)) df.content = df_content workflow = DockerBuildWorkflow(SOURCE, "test-image") setattr(workflow, 'builder', X()) metalink = 'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.files[os.path.join(YUM_REPOS_DIR, DEFAULT_YUM_REPOFILE_NAME)] = render_yum_repo(OrderedDict( (('name', 'my-repo'), ('metalink', metalink), ('enabled', '1'), ('gpgcheck', '0')), )) setattr(workflow.builder, 'image_id', "asd123") setattr(workflow.builder, 'df_path', df.dockerfile_path) setattr(workflow.builder, 'df_dir', str(tmpdir)) setattr(workflow.builder, 'base_image', ImageName(repo='Fedora', tag='21')) setattr(workflow.builder, 'source', X()) setattr(workflow.builder.source, 'dockerfile_path', None) setattr(workflow.builder.source, 'path', None) runner = PreBuildPluginsRunner(docker_tasker, workflow, [{'name': InjectYumRepoPlugin.key, 'args': { "wrap_commands": True }}]) runner.run() assert InjectYumRepoPlugin.key is not None expected_output = """FROM fedora RUN printf "[my-repo]\nname=my-repo\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\nenabled=1\ngpgcheck=0\n" >/etc/yum.repos.d/atomic-reactor-injected.repo && yum install -y httpd uwsgi && yum clean all && rm -f /etc/yum.repos.d/atomic-reactor-injected.repo CMD blabla""" assert df.content == expected_output def test_yuminject_multiline_notwrapped(tmpdir): df_content = """\ FROM fedora RUN yum install -y httpd \ uwsgi CMD blabla""" df = DockerfileParser(str(tmpdir)) df.content = df_content tasker, workflow = prepare(df.dockerfile_path) metalink = r'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.files[os.path.join(YUM_REPOS_DIR, DEFAULT_YUM_REPOFILE_NAME)] = render_yum_repo(OrderedDict( (('name', 'my-repo'), ('metalink', metalink), ('enabled', "1"), ('gpgcheck', "0")), )) runner = PreBuildPluginsRunner(tasker, workflow, [{'name': InjectYumRepoPlugin.key, 'args': { "wrap_commands": False }}]) runner.run() assert InjectYumRepoPlugin.key is not None expected_output = r"""FROM fedora ADD atomic-reactor-repos/* '/etc/yum.repos.d/' RUN yum install -y httpd uwsgi CMD blabla RUN rm -f '/etc/yum.repos.d/atomic-reactor-injected.repo' """ assert df.content == expected_output def test_yuminject_multiline_wrapped_with_chown(tmpdir, docker_tasker): df_content = """\ FROM fedora RUN yum install -y --setopt=tsflags=nodocs bind-utils gettext iproute v8314 mongodb24-mongodb mongodb24 && \ yum clean all && \ mkdir -p /var/lib/mongodb/data && chown -R mongodb:mongodb /var/lib/mongodb/ && \ test "$(id mongodb)" = "uid=184(mongodb) gid=998(mongodb) groups=998(mongodb)" && \ chmod o+w -R /var/lib/mongodb && chmod o+w -R /opt/rh/mongodb24/root/var/lib/mongodb CMD blabla""" df = DockerfileParser(str(tmpdir)) df.content = df_content workflow = DockerBuildWorkflow(SOURCE, "test-image") setattr(workflow, 'builder', X()) metalink = r'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.files[os.path.join(YUM_REPOS_DIR, DEFAULT_YUM_REPOFILE_NAME)] = render_yum_repo(OrderedDict( (('name', 'my-repo'), ('metalink', metalink), ('enabled', 1), ('gpgcheck', 0)), )) setattr(workflow.builder, 'image_id', "asd123") setattr(workflow.builder, 'df_path', df.dockerfile_path) setattr(workflow.builder, 'df_dir', str(tmpdir)) setattr(workflow.builder, 'base_image', ImageName(repo='Fedora', tag='21')) setattr(workflow.builder, 'git_dockerfile_path', None) setattr(workflow.builder, 'git_path', None) setattr(workflow.builder, 'source', X()) setattr(workflow.builder.source, 'dockerfile_path', None) setattr(workflow.builder.source, 'path', '') runner = PreBuildPluginsRunner(docker_tasker, workflow, [{'name': InjectYumRepoPlugin.key, 'args': { "wrap_commands": True }}]) runner.run() assert InjectYumRepoPlugin.key is not None expected_output = """FROM fedora RUN printf "[my-repo]\nname=my-repo\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\ \\$basearch\nenabled=1\ngpgcheck=0\n" >/etc/yum.repos.d/atomic-reactor-injected.repo && \ yum install -y --setopt=tsflags=nodocs bind-utils gettext iproute v8314 mongodb24-mongodb mongodb24 && \ yum clean all && mkdir -p /var/lib/mongodb/data && chown -R mongodb:mongodb /var/lib/mongodb/ && \ test "$(id mongodb)" = "uid=184(mongodb) gid=998(mongodb) groups=998(mongodb)" && \ chmod o+w -R /var/lib/mongodb && chmod o+w -R /opt/rh/mongodb24/root/var/lib/mongodb && \ yum clean all && rm -f /etc/yum.repos.d/atomic-reactor-injected.repo CMD blabla""" assert df.content == expected_output def test_complex_df(): df = """\ FROM fedora RUN asd RUN yum install x ENV x=y RUN yum install \ x \ y \ && something else CMD asd""" wrap_cmd = "RUN test && %(yum_command)s && asd" out = alter_yum_commands(df, wrap_cmd) expected_output = """\ FROM fedora RUN asd RUN test && yum install x && asd ENV x=y RUN test && yum install x y && something else && asd CMD asd""" assert out == expected_output repocontent = '''\ [repo] name=asd ''' Dockerfile = namedtuple('Dockerfile', ['inherited_user', 'lines_before_add', 'lines_before_remove', 'remove_lines']) DOCKERFILES = { "no maintainer": Dockerfile('', ["# Simple example with no MAINTAINER line\n", "FROM base\n"], # add goes here [" RUN yum -y update\n"], ["RUN rm ...\n"]), "no yum": Dockerfile('', ["FROM base\n", "# This time there is a MAINTAINER line\n", "# but it's the last last there is\n", "MAINTAINER Example <example@example.com>\n"], # add goes here [], ["RUN rm ...\n"]), "user": Dockerfile('', [" From base\n", " Maintainer Example <example@example.com\n"], # add goes here [" Run yum update -y\n", " Env asd qwe\n", " User foo\n", " Run uname\n", " Label x y\n", " Cmd ['/bin/ls']\n"], ["USER root\n", "RUN rm ...\n", " User foo\n"]), "root": Dockerfile('', ["FROM nonroot-base\n", "MAINTAINER example@example.com\n"], # add goes here ["USER root\n", "RUN yum -y update\n", "USER user\n", "CMD ['id']\n"], ["USER root\n", "RUN rm ...\n", "USER user\n"]), "inherit": Dockerfile('inherited', ["FROM inherit-user\n"], # add goes here ["RUN /bin/ls\n"], ["USER root\n", "RUN rm ...\n", "USER inherited\n"]), "inherit-root": Dockerfile('inherited', ["FROM inherit-root\n"], # add goes here ["USER root\n", "RUN yum -y update\n", "USER user\n"], ["USER root\n", "RUN rm ...\n", "USER user\n"]), } def test_no_repourls(tmpdir): for df_content in DOCKERFILES.values(): df = DockerfileParser(str(tmpdir)) df.lines = df_content.lines_before_add + \ df_content.lines_before_remove tasker, workflow = prepare(df.dockerfile_path, df_content.inherited_user) runner = PreBuildPluginsRunner(tasker, workflow, [{ 'name': InjectYumRepoPlugin.key, }]) runner.run() assert InjectYumRepoPlugin.key is not None # Should be unchanged. assert df.lines == df_content.lines_before_add + \ df_content.lines_before_remove def remove_lines_match(actual, expected, repos): if len(actual) != len(expected): return False for aline, eline in zip(actual, expected): if eline.startswith("RUN rm"): if not aline.startswith("RUN rm -f "): assert aline == eline assert set(aline.rstrip()[10:].split(' ')) == set(["'/etc/yum.repos.d/%s'" % repo for repo in repos]) else: assert aline == eline return True def test_single_repourl(tmpdir): for df_content in DOCKERFILES.values(): df = DockerfileParser(str(tmpdir)) df.lines = df_content.lines_before_add + \ df_content.lines_before_remove tasker, workflow = prepare(df.dockerfile_path, df_content.inherited_user) filename = 'test.repo' repo_path = os.path.join(YUM_REPOS_DIR, filename) workflow.files[repo_path] = repocontent runner = PreBuildPluginsRunner(tasker, workflow, [{ 'name': InjectYumRepoPlugin.key, 'args': {'wrap_commands': False}}]) runner.run() # Was it written correctly? repos_dir = os.path.join(str(tmpdir), RELATIVE_REPOS_PATH) repofile = os.path.join(repos_dir, filename) with open(repofile, "r") as fp: assert fp.read() == repocontent # Remove the repos/ directory. os.remove(repofile) os.rmdir(repos_dir) # Examine the Dockerfile. newdf = df.lines before_add = len(df_content.lines_before_add) before_remove = len(df_content.lines_before_remove) # Start of file should be unchanged. assert newdf[:before_add] == df_content.lines_before_add # Should see a single add line. after_add = before_add + 1 assert (newdf[before_add:after_add] == ["ADD %s* '/etc/yum.repos.d/'\n" % RELATIVE_REPOS_PATH]) # Lines from there up to the remove line should be unchanged. before_remove = after_add + len(df_content.lines_before_remove) assert (newdf[after_add:before_remove] == df_content.lines_before_remove) # The 'rm' lines should match # There should be a final 'rm' remove = newdf[before_remove:] assert remove_lines_match(remove, df_content.remove_lines, [filename]) def test_multiple_repourls(tmpdir): for df_content in DOCKERFILES.values(): df = DockerfileParser(str(tmpdir)) df.lines = df_content.lines_before_add + \ df_content.lines_before_remove tasker, workflow = prepare(df.dockerfile_path, df_content.inherited_user) filename1 = 'myrepo.repo' filename2 = 'repo-2.repo' repo_path1 = os.path.join(YUM_REPOS_DIR, filename1) repo_path2 = os.path.join(YUM_REPOS_DIR, filename2) workflow.files[repo_path1] = repocontent workflow.files[repo_path2] = repocontent runner = PreBuildPluginsRunner(tasker, workflow, [{ 'name': InjectYumRepoPlugin.key, 'args': {'wrap_commands': False}}]) runner.run() # Remove the repos/ directory. repos_dir = os.path.join(str(tmpdir), RELATIVE_REPOS_PATH) for repofile in [filename1, filename2]: os.remove(os.path.join(repos_dir, repofile)) os.rmdir(repos_dir) # Examine the Dockerfile. newdf = df.lines before_add = len(df_content.lines_before_add) before_remove = len(df_content.lines_before_remove) # Start of file should be unchanged. assert newdf[:before_add] == df_content.lines_before_add # Should see a single add line. after_add = before_add + 1 assert (newdf[before_add:after_add] == ["ADD %s* '/etc/yum.repos.d/'\n" % RELATIVE_REPOS_PATH]) # Lines from there up to the remove line should be unchanged. before_remove = after_add + len(df_content.lines_before_remove) assert (newdf[after_add:before_remove] == df_content.lines_before_remove) # For the 'rm' line, they could be in either order remove = newdf[before_remove:] assert remove_lines_match(remove, df_content.remove_lines, [filename1, filename2])
#!/usr/bin/env ambari-python-wrap """ 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. """ import imp import os import re import socket import traceback class StackAdvisor(object): """ Abstract class implemented by all stack advisors. Stack advisors advise on stack specific questions. Currently stack advisors provide following abilities: - Recommend where services should be installed in cluster - Recommend configurations based on host hardware - Validate user selection of where services are installed on cluster - Validate user configuration values Each of the above methods is passed in parameters about services and hosts involved as described below. @type services: dictionary @param services: Dictionary containing all information about services selected by the user. Example: { "services": [ { "StackServices": { "service_name" : "HDFS", "service_version" : "2.6.0.2.2", }, "components" : [ { "StackServiceComponents" : { "cardinality" : "1+", "component_category" : "SLAVE", "component_name" : "DATANODE", "display_name" : "DataNode", "service_name" : "HDFS", "hostnames" : [] }, "dependencies" : [] }, { "StackServiceComponents" : { "cardinality" : "1-2", "component_category" : "MASTER", "component_name" : "NAMENODE", "display_name" : "NameNode", "service_name" : "HDFS", "hostnames" : [] }, "dependencies" : [] }, ... ] }, ... ] } @type hosts: dictionary @param hosts: Dictionary containing all information about hosts in this cluster Example: { "items": [ { Hosts: { "host_name": "c6401.ambari.apache.org", "public_host_name" : "c6401.ambari.apache.org", "ip": "192.168.1.101", "cpu_count" : 1, "disk_info" : [ { "available" : "4564632", "used" : "5230344", "percent" : "54%", "size" : "10319160", "type" : "ext4", "mountpoint" : "/" }, { "available" : "1832436", "used" : "0", "percent" : "0%", "size" : "1832436", "type" : "tmpfs", "mountpoint" : "/dev/shm" } ], "host_state" : "HEALTHY", "os_arch" : "x86_64", "os_type" : "centos6", "total_mem" : 3664872 } }, ... ] } Each of the methods can either return recommendations or validations. Recommendations are made in a Ambari Blueprints friendly format. Validations are an array of validation objects. """ def recommendComponentLayout(self, services, hosts): """ Returns recommendation of which hosts various service components should be installed on. This function takes as input all details about services being installed, and hosts they are being installed into, to generate hostname assignments to various components of each service. @type services: dictionary @param services: Dictionary containing all information about services selected by the user. @type hosts: dictionary @param hosts: Dictionary containing all information about hosts in this cluster @rtype: dictionary @return: Layout recommendation of service components on cluster hosts in Ambari Blueprints friendly format. Example: { "resources" : [ { "hosts" : [ "c6402.ambari.apache.org", "c6401.ambari.apache.org" ], "services" : [ "HDFS" ], "recommendations" : { "blueprint" : { "host_groups" : [ { "name" : "host-group-2", "components" : [ { "name" : "JOURNALNODE" }, { "name" : "ZKFC" }, { "name" : "DATANODE" }, { "name" : "SECONDARY_NAMENODE" } ] }, { "name" : "host-group-1", "components" : [ { "name" : "HDFS_CLIENT" }, { "name" : "NAMENODE" }, { "name" : "JOURNALNODE" }, { "name" : "ZKFC" }, { "name" : "DATANODE" } ] } ] }, "blueprint_cluster_binding" : { "host_groups" : [ { "name" : "host-group-1", "hosts" : [ { "fqdn" : "c6401.ambari.apache.org" } ] }, { "name" : "host-group-2", "hosts" : [ { "fqdn" : "c6402.ambari.apache.org" } ] } ] } } } ] } """ pass def validateComponentLayout(self, services, hosts): """ Returns array of Validation issues with service component layout on hosts This function takes as input all details about services being installed along with hosts the components are being installed on (hostnames property is populated for each component). @type services: dictionary @param services: Dictionary containing information about services and host layout selected by the user. @type hosts: dictionary @param hosts: Dictionary containing all information about hosts in this cluster @rtype: dictionary @return: Dictionary containing array of validation items Example: { "items": [ { "type" : "host-group", "level" : "ERROR", "message" : "NameNode and Secondary NameNode should not be hosted on the same machine", "component-name" : "NAMENODE", "host" : "c6401.ambari.apache.org" }, ... ] } """ pass def recommendConfigurations(self, services, hosts): """ Returns recommendation of service configurations based on host-specific layout of components. This function takes as input all details about services being installed, and hosts they are being installed into, to recommend host-specific configurations. @type services: dictionary @param services: Dictionary containing all information about services and component layout selected by the user. @type hosts: dictionary @param hosts: Dictionary containing all information about hosts in this cluster @rtype: dictionary @return: Layout recommendation of service components on cluster hosts in Ambari Blueprints friendly format. Example: { "services": [ "HIVE", "TEZ", "YARN" ], "recommendations": { "blueprint": { "host_groups": [], "configurations": { "yarn-site": { "properties": { "yarn.scheduler.minimum-allocation-mb": "682", "yarn.scheduler.maximum-allocation-mb": "2048", "yarn.nodemanager.resource.memory-mb": "2048" } }, "tez-site": { "properties": { "tez.am.java.opts": "-server -Xmx546m -Djava.net.preferIPv4Stack=true -XX:+UseNUMA -XX:+UseParallelGC", "tez.am.resource.memory.mb": "682" } }, "hive-site": { "properties": { "hive.tez.container.size": "682", "hive.tez.java.opts": "-server -Xmx546m -Djava.net.preferIPv4Stack=true -XX:NewRatio=8 -XX:+UseNUMA -XX:+UseParallelGC", "hive.auto.convert.join.noconditionaltask.size": "238026752" } } } }, "blueprint_cluster_binding": { "host_groups": [] } }, "hosts": [ "c6401.ambari.apache.org", "c6402.ambari.apache.org", "c6403.ambari.apache.org" ] } """ pass def validateConfigurations(self, services, hosts): """" Returns array of Validation issues with configurations provided by user This function takes as input all details about services being installed along with configuration values entered by the user. These configurations can be validated against service requirements, or host hardware to generate validation issues. @type services: dictionary @param services: Dictionary containing information about services and user configurations. @type hosts: dictionary @param hosts: Dictionary containing all information about hosts in this cluster @rtype: dictionary @return: Dictionary containing array of validation items Example: { "items": [ { "config-type": "yarn-site", "message": "Value is less than the recommended default of 682", "type": "configuration", "config-name": "yarn.scheduler.minimum-allocation-mb", "level": "WARN" } ] } """ pass class DefaultStackAdvisor(StackAdvisor): CLUSTER_CREATE_OPERATION = "ClusterCreate" ADD_SERVICE_OPERATION = "AddService" EDIT_CONFIG_OPERATION = "EditConfig" RECOMMEND_ATTRIBUTE_OPERATION = "RecommendAttribute" OPERATION = "operation" OPERATION_DETAILS = "operation_details" ADVISOR_CONTEXT = "advisor_context" CALL_TYPE = "call_type" """ Default stack advisor implementation. This implementation is used when a stack-version, or its hierarchy does not have an advisor. Stack-versions can extend this class to provide their own implement """ def __init__(self): self.services = None # Dictionary that maps serviceName or componentName to serviceAdvisor self.serviceAdvisorsDict = {} # Contains requested properties during 'recommend-configuration-dependencies' request. # It's empty during other requests. self.allRequestedProperties = None def getActiveHosts(self, hosts): """ Filters the list of specified hosts object and returns a list of hosts which are not in maintenance mode. """ hostsList = [] if hosts is not None: hostsList = [host['host_name'] for host in hosts if host.get('maintenance_state') is None or host.get('maintenance_state') == "OFF"] return hostsList def getServiceAdvisor(self, key): if len(self.serviceAdvisorsDict) == 0: self.loadServiceAdvisors() return self.serviceAdvisorsDict[key] def loadServiceAdvisors(self): for service in self.services["services"]: serviceName = service["StackServices"]["service_name"] self.serviceAdvisorsDict[serviceName] = self.instantiateServiceAdvisor(service) for component in service["components"]: componentName = self.getComponentName(component) self.serviceAdvisorsDict[componentName] = self.serviceAdvisorsDict[serviceName] def instantiateServiceAdvisor(self, service): serviceName = service["StackServices"]["service_name"] className = service["StackServices"]["advisor_name"] if "advisor_name" in service["StackServices"] else None path = service["StackServices"]["advisor_path"] if "advisor_path" in service["StackServices"] else None if path is not None and os.path.exists(path) and className is not None: try: with open(path, 'rb') as fp: serviceAdvisor = imp.load_module('service_advisor_impl', fp, path, ('.py', 'rb', imp.PY_SOURCE)) if hasattr(serviceAdvisor, className): print "ServiceAdvisor implementation for service {0} was loaded".format(serviceName) return getattr(serviceAdvisor, className)() else: print "Failed to load or create ServiceAdvisor implementation for service {0}: " \ "Expecting class name {1} but it was not found.".format(serviceName, className) except Exception as e: traceback.print_exc() print "Failed to load or create ServiceAdvisor implementation for service {0}".format(serviceName) return None def recommendComponentLayout(self, services, hosts): """Returns Services object with hostnames array populated for components""" stackName = services["Versions"]["stack_name"] stackVersion = services["Versions"]["stack_version"] hostsList = self.getActiveHosts([host["Hosts"] for host in hosts["items"]]) servicesList = self.getServiceNames(services) layoutRecommendations = self.createComponentLayoutRecommendations(services, hosts) recommendations = { "Versions": {"stack_name": stackName, "stack_version": stackVersion}, "hosts": hostsList, "services": servicesList, "recommendations": layoutRecommendations } return recommendations def createComponentLayoutRecommendations(self, services, hosts): self.services = services recommendations = { "blueprint": { "host_groups": [ ] }, "blueprint_cluster_binding": { "host_groups": [ ] } } hostsList = self.getActiveHosts([host["Hosts"] for host in hosts["items"]]) # for fast lookup hostsSet = set(hostsList) hostsComponentsMap = {} for hostName in hostsList: if hostName not in hostsComponentsMap: hostsComponentsMap[hostName] = [] #extend hostsComponentsMap' with MASTER components for service in services["services"]: masterComponents = [component for component in service["components"] if self.isMasterComponent(component)] serviceName = service["StackServices"]["service_name"] serviceAdvisor = self.getServiceAdvisor(serviceName) for component in masterComponents: componentName = component["StackServiceComponents"]["component_name"] advisor = serviceAdvisor if serviceAdvisor is not None else self hostsForComponent = advisor.getHostsForMasterComponent(services, hosts, component, hostsList) #extend 'hostsComponentsMap' with 'hostsForComponent' for hostName in hostsForComponent: if hostName in hostsSet: hostsComponentsMap[hostName].append( { "name":componentName } ) #extend 'hostsComponentsMap' with Slave and Client Components componentsListList = [service["components"] for service in services["services"]] componentsList = [item for sublist in componentsListList for item in sublist] usedHostsListList = [component["StackServiceComponents"]["hostnames"] for component in componentsList if not self.isComponentNotValuable(component)] utilizedHosts = [item for sublist in usedHostsListList for item in sublist] freeHosts = [hostName for hostName in hostsList if hostName not in utilizedHosts] for service in services["services"]: slaveClientComponents = [component for component in service["components"] if self.isSlaveComponent(component) or self.isClientComponent(component)] serviceName = service["StackServices"]["service_name"] serviceAdvisor = self.getServiceAdvisor(serviceName) for component in slaveClientComponents: componentName = component["StackServiceComponents"]["component_name"] advisor = serviceAdvisor if serviceAdvisor is not None else self hostsForComponent = advisor.getHostsForSlaveComponent(services, hosts, component, hostsList, freeHosts) #extend 'hostsComponentsMap' with 'hostsForComponent' for hostName in hostsForComponent: if hostName not in hostsComponentsMap and hostName in hostsSet: hostsComponentsMap[hostName] = [] if hostName in hostsSet: hostsComponentsMap[hostName].append( { "name": componentName } ) #colocate custom services for service in services["services"]: serviceName = service["StackServices"]["service_name"] serviceAdvisor = self.getServiceAdvisor(serviceName) if serviceAdvisor is not None: serviceComponents = [component for component in service["components"]] serviceAdvisor.colocateService(hostsComponentsMap, serviceComponents) #prepare 'host-group's from 'hostsComponentsMap' host_groups = recommendations["blueprint"]["host_groups"] bindings = recommendations["blueprint_cluster_binding"]["host_groups"] index = 0 for key in hostsComponentsMap.keys(): index += 1 host_group_name = "host-group-{0}".format(index) host_groups.append( { "name": host_group_name, "components": hostsComponentsMap[key] } ) bindings.append( { "name": host_group_name, "hosts": [{ "fqdn": key }] } ) return recommendations def getHostsForMasterComponent(self, services, hosts, component, hostsList): if self.isComponentHostsPopulated(component): return component["StackServiceComponents"]["hostnames"] if len(hostsList) > 1 and self.isMasterComponentWithMultipleInstances(component): hostsCount = self.getMinComponentCount(component, hosts) if hostsCount > 1: # get first 'hostsCount' available hosts hostsForComponent = [] hostIndex = 0 while hostsCount > len(hostsForComponent) and hostIndex < len(hostsList): currentHost = hostsList[hostIndex] if self.isHostSuitableForComponent(currentHost, component): hostsForComponent.append(currentHost) hostIndex += 1 return hostsForComponent return [self.getHostForComponent(component, hostsList)] def getHostsForSlaveComponent(self, services, hosts, component, hostsList, freeHosts): if component["StackServiceComponents"]["cardinality"] == "ALL": return hostsList if self.isComponentHostsPopulated(component): return component["StackServiceComponents"]["hostnames"] hostsForComponent = [] componentName = component["StackServiceComponents"]["component_name"] if self.isSlaveComponent(component): cardinality = str(component["StackServiceComponents"]["cardinality"]) hostsMin, hostsMax = self.parseCardinality(cardinality, len(hostsList)) hostsMin, hostsMax = (0 if hostsMin is None else hostsMin, len(hostsList) if hostsMax is None else hostsMax) if self.isComponentUsingCardinalityForLayout(componentName) and cardinality: if hostsMin > len(hostsForComponent): hostsForComponent.extend(freeHosts[0:hostsMin-len(hostsForComponent)]) else: hostsForComponent.extend(freeHosts) if not hostsForComponent: # hostsForComponent is empty hostsForComponent = hostsList[-1:] hostsForComponent = list(set(hostsForComponent)) # removing duplicates if len(hostsForComponent) < hostsMin: hostsForComponent = list(set(hostsList))[0:hostsMin] elif len(hostsForComponent) > hostsMax: hostsForComponent = list(set(hostsList))[0:hostsMax] elif self.isClientComponent(component): hostsForComponent = freeHosts[0:1] if not hostsForComponent: # hostsForComponent is empty hostsForComponent = hostsList[-1:] return hostsForComponent def isComponentUsingCardinalityForLayout(self, componentName): return False def createValidationResponse(self, services, validationItems): """Returns array of Validation objects about issues with hostnames components assigned to""" stackName = services["Versions"]["stack_name"] stackVersion = services["Versions"]["stack_version"] validations = { "Versions": {"stack_name": stackName, "stack_version": stackVersion}, "items": validationItems } return validations def validateComponentLayout(self, services, hosts): """Returns array of Validation objects about issues with hostnames components assigned to""" validationItems = self.getComponentLayoutValidations(services, hosts) return self.createValidationResponse(services, validationItems) def validateConfigurations(self, services, hosts): """Returns array of Validation objects about issues with hostnames components assigned to""" self.services = services validationItems = self.getConfigurationsValidationItems(services, hosts) return self.createValidationResponse(services, validationItems) def getComponentLayoutValidations(self, services, hosts): self.services = services items = [] if services is None: return items for service in services["services"]: serviceName = service["StackServices"]["service_name"] serviceAdvisor = self.getServiceAdvisor(serviceName) if serviceAdvisor is not None: items.extend(serviceAdvisor.getServiceComponentLayoutValidations(services, hosts)) return items def getConfigurationClusterSummary(self, servicesList, hosts, components, services): return {} def validateClusterConfigurations(self, configurations, services, hosts): validationItems = [] return self.toConfigurationValidationProblems(validationItems, "") def toConfigurationValidationProblems(self, validationProblems, siteName): result = [] for validationProblem in validationProblems: validationItem = validationProblem.get("item", None) if validationItem is not None: problem = {"type": 'configuration', "level": validationItem["level"], "message": validationItem["message"], "config-type": siteName, "config-name": validationProblem["config-name"] } result.append(problem) return result def validateServiceConfigurations(self, serviceName): return self.getServiceConfigurationValidators().get(serviceName, None) def getServiceConfigurationValidators(self): return {} def validateMinMax(self, items, recommendedDefaults, configurations): # required for casting to the proper numeric type before comparison def convertToNumber(number): try: return int(number) except ValueError: return float(number) for configName in configurations: validationItems = [] if configName in recommendedDefaults and "property_attributes" in recommendedDefaults[configName]: for propertyName in recommendedDefaults[configName]["property_attributes"]: if propertyName in configurations[configName]["properties"]: if "maximum" in recommendedDefaults[configName]["property_attributes"][propertyName] and \ propertyName in recommendedDefaults[configName]["properties"]: userValue = convertToNumber(configurations[configName]["properties"][propertyName]) maxValue = convertToNumber(recommendedDefaults[configName]["property_attributes"][propertyName]["maximum"]) if userValue > maxValue: validationItems.extend([{"config-name": propertyName, "item": self.getWarnItem("Value is greater than the recommended maximum of {0} ".format(maxValue))}]) if "minimum" in recommendedDefaults[configName]["property_attributes"][propertyName] and \ propertyName in recommendedDefaults[configName]["properties"]: userValue = convertToNumber(configurations[configName]["properties"][propertyName]) minValue = convertToNumber(recommendedDefaults[configName]["property_attributes"][propertyName]["minimum"]) if userValue < minValue: validationItems.extend([{"config-name": propertyName, "item": self.getWarnItem("Value is less than the recommended minimum of {0} ".format(minValue))}]) items.extend(self.toConfigurationValidationProblems(validationItems, configName)) pass def getConfigurationsValidationItems(self, services, hosts): """Returns array of Validation objects about issues with configuration values provided in services""" items = [] recommendations = self.recommendConfigurations(services, hosts) recommendedDefaults = recommendations["recommendations"]["blueprint"]["configurations"] configurations = services["configurations"] for service in services["services"]: items.extend(self.getConfigurationsValidationItemsForService(configurations, recommendedDefaults, service, services, hosts)) clusterWideItems = self.validateClusterConfigurations(configurations, services, hosts) items.extend(clusterWideItems) self.validateMinMax(items, recommendedDefaults, configurations) return items def validateConfigurationsForSite(self, configurations, recommendedDefaults, services, hosts, siteName, method): if siteName in recommendedDefaults: siteProperties = self.getSiteProperties(configurations, siteName) if siteProperties is not None: siteRecommendations = recommendedDefaults[siteName]["properties"] print("SiteName: %s, method: %s" % (siteName, method.__name__)) print("Site properties: %s" % str(siteProperties)) print("Recommendations: %s" % str(siteRecommendations)) return method(siteProperties, siteRecommendations, configurations, services, hosts) return [] def getConfigurationsValidationItemsForService(self, configurations, recommendedDefaults, service, services, hosts): items = [] serviceName = service["StackServices"]["service_name"] validator = self.validateServiceConfigurations(serviceName) if validator is not None: for siteName, method in validator.items(): resultItems = self.validateConfigurationsForSite(configurations, recommendedDefaults, services, hosts, siteName, method) items.extend(resultItems) serviceAdvisor = self.getServiceAdvisor(serviceName) if serviceAdvisor is not None: items.extend(serviceAdvisor.getServiceConfigurationsValidationItems(configurations, recommendedDefaults, services, hosts)) return items def recommendConfigGroupsConfigurations(self, recommendations, services, components, hosts, servicesList): recommendations["recommendations"]["config-groups"] = [] for configGroup in services["config-groups"]: # Override configuration with the config group values cgServices = services.copy() for configName in configGroup["configurations"].keys(): if configName in cgServices["configurations"]: cgServices["configurations"][configName]["properties"].update( configGroup["configurations"][configName]['properties']) else: cgServices["configurations"][configName] = \ configGroup["configurations"][configName] # Override hosts with the config group hosts cgHosts = {"items": [host for host in hosts["items"] if host["Hosts"]["host_name"] in configGroup["hosts"]]} # Override clusterSummary cgClusterSummary = self.getConfigurationClusterSummary(servicesList, cgHosts, components, cgServices) configurations = {} # there can be dependencies between service recommendations which require special ordering # for now, make sure custom services (that have service advisors) run after standard ones serviceAdvisors = [] for service in services["services"]: serviceName = service["StackServices"]["service_name"] calculation = self.getServiceConfigurationRecommender(serviceName) if calculation is not None: calculation(configurations, cgClusterSummary, cgServices, cgHosts) else: serviceAdvisor = self.getServiceAdvisor(serviceName) if serviceAdvisor is not None: serviceAdvisors.append(serviceAdvisor) for serviceAdvisor in serviceAdvisors: serviceAdvisor.getServiceConfigurationRecommendations(configurations, cgClusterSummary, cgServices, cgHosts) cgRecommendation = { "configurations": {}, "dependent_configurations": {}, "hosts": configGroup["hosts"] } recommendations["recommendations"]["config-groups"].append( cgRecommendation) # Parse results. for config in configurations.keys(): cgRecommendation["configurations"][config] = {} cgRecommendation["dependent_configurations"][config] = {} # property + property_attributes for configElement in configurations[config].keys(): cgRecommendation["configurations"][config][configElement] = {} cgRecommendation["dependent_configurations"][config][ configElement] = {} for property, value in configurations[config][configElement].items(): if config in configGroup["configurations"]: cgRecommendation["configurations"][config][configElement][ property] = value else: cgRecommendation["dependent_configurations"][config][ configElement][property] = value def recommendConfigurations(self, services, hosts): self.services = services stackName = services["Versions"]["stack_name"] stackVersion = services["Versions"]["stack_version"] hostsList = [host["Hosts"]["host_name"] for host in hosts["items"]] servicesList = [service["StackServices"]["service_name"] for service in services["services"]] components = [component["StackServiceComponents"]["component_name"] for service in services["services"] for component in service["components"]] clusterSummary = self.getConfigurationClusterSummary(servicesList, hosts, components, services) recommendations = { "Versions": {"stack_name": stackName, "stack_version": stackVersion}, "hosts": hostsList, "services": servicesList, "recommendations": { "blueprint": { "configurations": {}, "host_groups": [] }, "blueprint_cluster_binding": { "host_groups": [] } } } # If recommendation for config groups if "config-groups" in services: self.recommendConfigGroupsConfigurations(recommendations, services, components, hosts, servicesList) else: configurations = recommendations["recommendations"]["blueprint"]["configurations"] # there can be dependencies between service recommendations which require special ordering # for now, make sure custom services (that have service advisors) run after standard ones serviceAdvisors = [] for service in services["services"]: serviceName = service["StackServices"]["service_name"] calculation = self.getServiceConfigurationRecommender(serviceName) if calculation is not None: calculation(configurations, clusterSummary, services, hosts) else: serviceAdvisor = self.getServiceAdvisor(serviceName) if serviceAdvisor is not None: serviceAdvisors.append(serviceAdvisor) for serviceAdvisor in serviceAdvisors: serviceAdvisor.getServiceConfigurationRecommendations(configurations, clusterSummary, services, hosts) return recommendations def getServiceConfigurationRecommender(self, service): return self.getServiceConfigurationRecommenderDict().get(service, None) def getServiceConfigurationRecommenderDict(self): return {} # Recommendation helper methods def isComponentHostsPopulated(self, component): hostnames = self.getComponentAttribute(component, "hostnames") if hostnames is not None: return len(hostnames) > 0 return False def isClientComponent(self, component): return self.getComponentAttribute(component, "component_category") == 'CLIENT' def isSlaveComponent(self, component): return self.getComponentAttribute(component, "component_category") == 'SLAVE' def isMasterComponent(self, component): return self.getComponentAttribute(component, "is_master") def getComponentAttribute(self, component, attribute): serviceComponent = component.get("StackServiceComponents", None) if serviceComponent is None: return None return serviceComponent.get(attribute, None) def isLocalHost(self, hostName): return socket.getfqdn(hostName) == socket.getfqdn() def isMasterComponentWithMultipleInstances(self, component): componentName = self.getComponentName(component) masters = self.getMastersWithMultipleInstances() return componentName in masters def isComponentNotValuable(self, component): componentName = self.getComponentName(component) service = self.getNotValuableComponents() return componentName in service def getMinComponentCount(self, component, hosts): componentName = self.getComponentName(component) return self.getComponentCardinality(componentName, hosts)["min"] # Helper dictionaries def getComponentCardinality(self, componentName, hosts): return self.getCardinalitiesDict(hosts).get(componentName, {"min": 1, "max": 1}) def getHostForComponent(self, component, hostsList): if len(hostsList) == 0: return None componentName = self.getComponentName(component) if len(hostsList) != 1: scheme = self.getComponentLayoutSchemes().get(componentName, None) if scheme is not None: hostIndex = next((index for key, index in scheme.iteritems() if isinstance(key, (int, long)) and len(hostsList) < key), scheme['else']) else: hostIndex = 0 for host in hostsList[hostIndex:]: if self.isHostSuitableForComponent(host, component): return host return hostsList[0] def getComponentName(self, component): return self.getComponentAttribute(component, "component_name") def isHostSuitableForComponent(self, host, component): return not (self.getComponentName(component) in self.getNotPreferableOnServerComponents() and self.isLocalHost(host)) def getMastersWithMultipleInstances(self): return [] def getNotValuableComponents(self): return [] def getNotPreferableOnServerComponents(self): return [] def getCardinalitiesDict(self, hosts): return {} def getComponentLayoutSchemes(self): """ Provides layout scheme dictionaries for components. The scheme dictionary basically maps the number of hosts to host index where component should exist. """ return {} def getWarnItem(self, message): """ Utility method used for validation warnings. """ return {"level": "WARN", "message": message} def getErrorItem(self, message): """ Utility method used for validation errors. """ return {"level": "ERROR", "message": message} def getComponentHostNames(self, servicesDict, serviceName, componentName): for service in servicesDict["services"]: if service["StackServices"]["service_name"] == serviceName: for component in service['components']: if component["StackServiceComponents"]["component_name"] == componentName: return component["StackServiceComponents"]["hostnames"] def recommendConfigurationDependencies(self, services, hosts): self.allRequestedProperties = self.getAllRequestedProperties(services) result = self.recommendConfigurations(services, hosts) return self.filterResult(result, services) # returns recommendations only for changed and depended properties def filterResult(self, result, services): allRequestedProperties = self.getAllRequestedProperties(services) self.filterConfigs(result['recommendations']['blueprint']['configurations'], allRequestedProperties) if "config-groups" in services: for configGroup in result['recommendations']["config-groups"]: self.filterConfigs(configGroup["configurations"], allRequestedProperties) self.filterConfigs(configGroup["dependent_configurations"], allRequestedProperties) return result def filterConfigs(self, configs, requestedProperties): filteredConfigs = {} for type, names in configs.items(): if 'properties' in names.keys(): for name in names['properties']: if type in requestedProperties.keys() and \ name in requestedProperties[type]: if type not in filteredConfigs.keys(): filteredConfigs[type] = {'properties': {}} filteredConfigs[type]['properties'][name] = \ configs[type]['properties'][name] if 'property_attributes' in names.keys(): for name in names['property_attributes']: if type in requestedProperties.keys() and \ name in requestedProperties[type]: if type not in filteredConfigs.keys(): filteredConfigs[type] = {'property_attributes': {}} elif 'property_attributes' not in filteredConfigs[type].keys(): filteredConfigs[type]['property_attributes'] = {} filteredConfigs[type]['property_attributes'][name] = \ configs[type]['property_attributes'][name] configs.clear() configs.update(filteredConfigs) def getAllRequestedProperties(self, services): affectedConfigs = self.getAffectedConfigs(services) allRequestedProperties = {} for config in affectedConfigs: if config['type'] in allRequestedProperties: allRequestedProperties[config['type']].append(config['name']) else: allRequestedProperties[config['type']] = [config['name']] return allRequestedProperties def getAffectedConfigs(self, services): """returns properties dict including changed-configurations and depended-by configs""" changedConfigs = services['changed-configurations'] changedConfigs = [{"type": entry["type"], "name": entry["name"]} for entry in changedConfigs] allDependencies = [] for item in services['services']: allDependencies.extend(item['configurations']) dependencies = [] size = -1 while size != len(dependencies): size = len(dependencies) for config in allDependencies: property = { "type": re.sub('\.xml$', '', config['StackConfigurations']['type']), "name": config['StackConfigurations']['property_name'] } if property in dependencies or property in changedConfigs: for dependedConfig in config['dependencies']: dependency = { "name": dependedConfig["StackConfigurationDependency"]["dependency_name"], "type": dependedConfig["StackConfigurationDependency"]["dependency_type"] } if dependency not in dependencies: dependencies.append(dependency) if "forced-configurations" in services and services["forced-configurations"] is not None: dependencies.extend(services["forced-configurations"]) return dependencies def versionCompare(self, version1, version2): def normalize(v): return [int(x) for x in re.sub(r'(\.0+)*$','', v).split(".")] return cmp(normalize(version1), normalize(version2)) pass def getSiteProperties(self, configurations, siteName): siteConfig = configurations.get(siteName) if siteConfig is None: return None return siteConfig.get("properties") def getServicesSiteProperties(self, services, siteName): if not services: return None configurations = services.get("configurations") if not configurations: return None siteConfig = configurations.get(siteName) if siteConfig is None: return None return siteConfig.get("properties") def putProperty(self, config, configType, services=None): userConfigs = {} changedConfigs = [] # if services parameter, prefer values, set by user if services: if 'configurations' in services.keys(): userConfigs = services['configurations'] if 'changed-configurations' in services.keys(): changedConfigs = services["changed-configurations"] if configType not in config: config[configType] = {} if"properties" not in config[configType]: config[configType]["properties"] = {} def appendProperty(key, value): # If property exists in changedConfigs, do not override, use user defined property if not self.isPropertyRequested(configType, key, changedConfigs) \ and configType in userConfigs and key in userConfigs[configType]['properties']: config[configType]["properties"][key] = userConfigs[configType]['properties'][key] else: config[configType]["properties"][key] = str(value) return appendProperty def __isPropertyInChangedConfigs(self, configType, propertyName, changedConfigs): for changedConfig in changedConfigs: if changedConfig['type']==configType and changedConfig['name']==propertyName: return True return False def isPropertyRequested(self, configType, propertyName, changedConfigs): # When the property depends on more than one property, we need to recalculate it based on the actual values # of all related properties. But "changed-configurations" usually contains only one on the dependent on properties. # So allRequestedProperties is used to avoid recommendations of other properties that are not requested. # Calculations should use user provided values for all properties that we depend on, not only the one that # came in the "changed-configurations". if self.allRequestedProperties: return configType in self.allRequestedProperties and propertyName in self.allRequestedProperties[configType] else: return not self.__isPropertyInChangedConfigs(configType, propertyName, changedConfigs) def updateProperty(self, config, configType, services=None): userConfigs = {} changedConfigs = [] # if services parameter, prefer values, set by user if services: if 'configurations' in services.keys(): userConfigs = services['configurations'] if 'changed-configurations' in services.keys(): changedConfigs = services["changed-configurations"] if configType not in config: config[configType] = {} if "properties" not in config[configType]: config[configType]["properties"] = {} def updatePropertyWithCallback(key, value, callback): # If property exists in changedConfigs, do not override, use user defined property if self.__isPropertyInChangedConfigs(configType, key, changedConfigs): config[configType]["properties"][key] = userConfigs[configType]['properties'][key] else: # Give the callback an empty string if the mapping doesn't exist current_value = "" if key in config[configType]["properties"]: current_value = config[configType]["properties"][key] config[configType]["properties"][key] = callback(current_value, value) return updatePropertyWithCallback def putPropertyAttribute(self, config, configType): if configType not in config: config[configType] = {} def appendPropertyAttribute(key, attribute, attributeValue): if "property_attributes" not in config[configType]: config[configType]["property_attributes"] = {} if key not in config[configType]["property_attributes"]: config[configType]["property_attributes"][key] = {} config[configType]["property_attributes"][key][attribute] = attributeValue if isinstance(attributeValue, list) else str(attributeValue) return appendPropertyAttribute def getHosts(self, componentsList, componentName): """ Returns the hosts which are running the given component. """ hostNamesList = [component["hostnames"] for component in componentsList if component["component_name"] == componentName] return hostNamesList[0] if len(hostNamesList) > 0 else [] def getServiceComponents(self, services, serviceName): """ Return list of components for serviceName service :type services dict :type serviceName str :rtype list """ components = [] if not services or not serviceName: return components for service in services["services"]: if service["StackServices"]["service_name"] == serviceName: components.extend(service["components"]) break return components def getHostsForComponent(self, services, serviceName, componentName): """ Returns the host(s) on which a requested service's component is hosted. :argument services Configuration information for the cluster :argument serviceName Passed-in service in consideration :argument componentName Passed-in component in consideration :type services dict :type serviceName str :type componentName str :rtype list """ hosts_for_component = [] components = self.getServiceComponents(services, serviceName) for component in components: if component["StackServiceComponents"]["component_name"] == componentName: hosts_for_component.extend(component["StackServiceComponents"]["hostnames"]) break return hosts_for_component def getMountPoints(self, hosts): """ Return list of mounts available on the hosts :type hosts dict """ mount_points = [] for item in hosts["items"]: if "disk_info" in item["Hosts"]: mount_points.append(item["Hosts"]["disk_info"]) return mount_points def isSecurityEnabled(self, services): """ Determines if security is enabled by testing the value of cluster-env/security enabled. If the property exists and is equal to "true", then is it enabled; otherwise is it assumed to be disabled. :param services: the services structure containing the current configurations :return: true if security is enabled; otherwise false """ return "cluster-env" in services["configurations"] \ and "security_enabled" in services["configurations"]["cluster-env"]["properties"] \ and services["configurations"]["cluster-env"]["properties"]["security_enabled"].lower() == "true" def parseCardinality(self, cardinality, hostsCount): """ Cardinality types: 1+, 1-2, 1, ALL @return: a tuple: (minHosts, maxHosts) or (None, None) if cardinality string is invalid """ if not cardinality: return (None, None) if "+" in cardinality: return (int(cardinality[:-1]), int(hostsCount)) elif "-" in cardinality: nums = cardinality.split("-") return (int(nums[0]), int(nums[1])) elif "ALL" == cardinality: return (int(hostsCount), int(hostsCount)) elif cardinality.isdigit(): return (int(cardinality),int(cardinality)) return (None, None) def getServiceNames(self, services): return [service["StackServices"]["service_name"] for service in services["services"]] def filterHostMounts(self, hosts, services): """ Filter mounts on the host using agent_mounts_ignore_list, by excluding and record with mount-point mentioned in agent_mounts_ignore_list. This function updates hosts dictionary Example: agent_mounts_ignore_list : "/run/secrets" Hosts record : "disk_info" : [ { ... "mountpoint" : "/" }, { ... "mountpoint" : "/run/secrets" } ] Result would be : "disk_info" : [ { ... "mountpoint" : "/" } ] :type hosts dict :type services dict """ if not services or "items" not in hosts: return hosts banned_filesystems = ["devtmpfs", "tmpfs", "vboxsf", "cdfs"] banned_mount_points = ["/etc/resolv.conf", "/etc/hostname", "/boot", "/mnt", "/tmp", "/run/secrets"] cluster_env = self.getServicesSiteProperties(services, "cluster-env") ignore_list = [] if cluster_env and "agent_mounts_ignore_list" in cluster_env and cluster_env["agent_mounts_ignore_list"].strip(): ignore_list = [x.strip() for x in cluster_env["agent_mounts_ignore_list"].strip().split(",")] ignore_list.extend(banned_mount_points) for host in hosts["items"]: if "Hosts" not in host and "disk_info" not in host["Hosts"]: continue host = host["Hosts"] disk_info = [] for disk in host["disk_info"]: if disk["mountpoint"] not in ignore_list\ and disk["type"].lower() not in banned_filesystems: disk_info.append(disk) host["disk_info"] = disk_info return hosts def __getSameHostMounts(self, hosts): """ Return list of the mounts which are same and present on all hosts :type hosts dict :rtype list """ if not hosts: return None hostMounts = self.getMountPoints(hosts) mounts = [] for m in hostMounts: host_mounts = set([item["mountpoint"] for item in m]) mounts = host_mounts if not mounts else mounts & host_mounts return sorted(mounts) def getMountPathVariations(self, initial_value, component_name, services, hosts): """ Recommends best fitted mount by prefixing path with it. :return return list of paths with properly selected paths. If no recommendation possible, would be returned empty list :type initial_value str :type component_name str :type services dict :type hosts dict :rtype list """ available_mounts = [] if not initial_value: return available_mounts mounts = self.__getSameHostMounts(hosts) sep = "/" if not mounts: return available_mounts for mount in mounts: new_mount = initial_value if mount == "/" else os.path.join(mount + sep, initial_value.lstrip(sep)) if new_mount not in available_mounts: available_mounts.append(new_mount) # no list transformations after filling the list, because this will cause item order change return available_mounts def getMountPathVariation(self, initial_value, component_name, services, hosts): """ Recommends best fitted mount by prefixing path with it. :return return list of paths with properly selected paths. If no recommendation possible, would be returned empty list :type initial_value str :type component_name str :type services dict :type hosts dict :rtype str """ try: return [self.getMountPathVariations(initial_value, component_name, services, hosts)[0]] except IndexError: return [] def updateMountProperties(self, siteConfig, propertyDefinitions, configurations, services, hosts): """ Update properties according to recommendations for available mount-points propertyDefinitions is an array of set : property name, component name, initial value, recommendation type Where, property name - name of the property component name, name of the component to which belongs this property initial value - initial path recommendation type - could be "multi" or "single". This describes recommendation strategy, to use only one disk or use all available space on the host :type propertyDefinitions list :type siteConfig str :type configurations dict :type services dict :type hosts dict """ props = self.getServicesSiteProperties(services, siteConfig) put_f = self.putProperty(configurations, siteConfig, services) for prop_item in propertyDefinitions: name, component, default_value, rc_type = prop_item recommendation = None if props is None or name not in props: if rc_type == "multi": recommendation = self.getMountPathVariations(default_value, component, services, hosts) else: recommendation = self.getMountPathVariation(default_value, component, services, hosts) elif props and name in props and props[name] == default_value: if rc_type == "multi": recommendation = self.getMountPathVariations(default_value, component, services, hosts) else: recommendation = self.getMountPathVariation(default_value, component, services, hosts) if recommendation: put_f(name, ",".join(recommendation))
""" unit tests for restframework_gis """ import json import pickle import sys from unittest import skipIf import django from django.contrib.gis.geos import GEOSGeometry, Point from django.test import TestCase try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse import rest_framework from django.core.exceptions import ImproperlyConfigured from rest_framework_gis import serializers as gis_serializers from rest_framework_gis.fields import GeoJsonDict from .models import LocatedFile, Location, Nullable from .serializers import LocationGeoSerializer is_pre_drf_39 = not rest_framework.VERSION.startswith('3.9') class TestRestFrameworkGis(TestCase): def setUp(self): self.location_list_url = reverse('api_location_list') self.geojson_location_list_url = reverse('api_geojson_location_list') self.geos_error_message = ( 'Invalid format: string or unicode input unrecognized as GeoJSON,' ' WKT EWKT or HEXEWKB.' ) self.gdal_error_message = ( 'Unable to convert to python object:' ' Invalid geometry pointer returned from "OGR_G_CreateGeometryFromJson".' ) if django.VERSION >= (2, 0, 0): self.value_error_message = ( "Unable to convert to python object:" " String input unrecognized as WKT EWKT, and HEXEWKB." ) else: self.value_error_message = ( "Unable to convert to python object:" " String or unicode input unrecognized as WKT EWKT, and HEXEWKB." ) self.type_error_message = ( "Unable to convert to python object: Improper geometry input type:" ) def _create_locations(self): self.l1 = Location.objects.create( id=1, name='l1', slug='l1', geometry='POINT (13.0078125000020002 42.4234565179379999)', ) self.l2 = Location.objects.create( id=2, name='l2', slug='l2', geometry='POINT (12.0078125000020002 43.4234565179379999)', ) def test_get_location_list(self): response = self.client.get(self.location_list_url) self.assertEqual(response.status_code, 200) def test_post_location_list_geojson(self): self.assertEqual(Location.objects.count(), 0) data = { "name": "geojson input test", "geometry": { "type": "GeometryCollection", "geometries": [ {"type": "Point", "coordinates": [12.492324113849, 41.890307434153]} ], }, } response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) data = { "name": "geojson input test2", "geometry": { "type": "Point", "coordinates": [12.492324113849, 41.890307434153], }, } response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 2) def test_post_location_list_geojson_as_multipartformdata(self): """ emulate sending geojson string in webform """ self.assertEqual(Location.objects.count(), 0) data = { "name": "geojson input test", "geometry": json.dumps( { "type": "GeometryCollection", "geometries": [ { "type": "Point", "coordinates": [12.492324113849, 41.890307434153], } ], } ), } response = self.client.post(self.location_list_url, data) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) def test_post_HTML_browsable_api(self): self.assertEqual(Location.objects.count(), 0) data = { "name": "geojson input test2", "slug": "prova", "geometry": json.dumps( { "type": "GeometryCollection", "geometries": [ { "type": "Point", "coordinates": [12.492324113849, 41.890307434153], } ], } ), } response = self.client.post( self.location_list_url, data, HTTP_ACCEPT='text/html' ) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) location = Location.objects.all()[0] self.assertEqual(location.name, 'geojson input test2') self.assertEqual(location.slug, 'prova') def test_post_location_list_WKT(self): self.assertEqual(Location.objects.count(), 0) data = { 'name': 'WKT input test', 'geometry': 'POINT (12.492324113849 41.890307434153)', } response = self.client.post(self.location_list_url, data) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) def test_post_location_list_EWKT(self): self.assertEqual(Location.objects.count(), 0) data = { 'name': 'EWKT input test', 'geometry': 'SRID=28992;POINT(221160 600204)', } response = self.client.post(self.location_list_url, data) expected_coords = (6.381495826183805, 53.384066927384985) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) for lat, lon in zip( Location.objects.get(name='EWKT input test').geometry.coords, expected_coords, ): self.assertAlmostEqual(lat, lon, places=5) def test_post_location_list_WKT_as_json(self): self.assertEqual(Location.objects.count(), 0) data = { 'name': 'WKT input test', 'geometry': 'POINT (12.492324113849 41.890307434153)', } response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) def test_post_location_list_empty_geometry(self): data = {'name': 'empty input test'} response = self.client.post(self.location_list_url, data) self.assertEqual(response.data['geometry'][0], 'This field is required.') data = {'name': 'empty input test', 'geometry': ''} response = self.client.post(self.location_list_url, data) self.assertEqual(response.data['geometry'][0], 'This field is required.') data = {'name': 'empty input test'} response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.data['geometry'][0], 'This field is required.') data = {'name': 'empty input test', 'geometry': ''} response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.data['geometry'][0], 'This field is required.') def test_post_location_list_invalid_WKT(self): data = {'name': 'WKT wrong input test', 'geometry': 'I AM OBVIOUSLY WRONG'} response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 400) self.assertEqual(Location.objects.count(), 0) self.assertEqual(response.data['geometry'][0], self.value_error_message) # repeat as multipart form data response = self.client.post(self.location_list_url, data) self.assertEqual(response.data['geometry'][0], self.value_error_message) data = { 'name': 'I AM MODERATELY WRONG', 'geometry': 'POINT (12.492324113849, 41.890307434153)', } response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.data['geometry'][0], self.geos_error_message) # repeat as multipart form data response = self.client.post(self.location_list_url, data) self.assertEqual(response.data['geometry'][0], self.geos_error_message) def test_post_location_list_invalid_geojson(self): data = { "name": "quite wrong", "geometry": { "type": "ARRRR", "dasdas": [{"STtype": "PTUAMAoint", "NNAare": "rgon"}], }, } response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.data['geometry'][0], self.gdal_error_message) data = {"name": "very wrong", "geometry": ['a', 'b', 'c']} response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.data['geometry'][0][0:65], self.type_error_message) data = {"name": "very wrong", "geometry": False} response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.data['geometry'][0][0:65], self.type_error_message) data = {"name": "very wrong", "geometry": {"value": {"nested": ["yo"]}}} response = self.client.post( self.location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.data['geometry'][0], self.gdal_error_message) def test_geojson_format(self): """ test geojson format """ location = Location.objects.create( name='geojson test', geometry='POINT (135.0 45.0)' ) url = reverse('api_geojson_location_details', args=[location.id]) expected = { 'id': location.id, 'type': 'Feature', 'properties': { 'details': "http://testserver/geojson/%s/" % location.id, 'name': 'geojson test', 'fancy_name': 'Kool geojson test', 'timestamp': None, 'slug': 'geojson-test', }, 'geometry': {'type': 'Point', 'coordinates': [135.0, 45.0]}, } response = self.client.get(url) if sys.version_info > (3, 0, 0): self.assertCountEqual(json.dumps(response.data), json.dumps(expected)) else: self.assertItemsEqual(json.dumps(response.data), json.dumps(expected)) response = self.client.get(url, HTTP_ACCEPT='text/html') self.assertContains(response, "Kool geojson test") def test_geojson_id_attribute(self): location = Location.objects.create( name='geojson test', geometry='POINT (10.1 10.1)' ) url = reverse('api_geojson_location_details', args=[location.id]) response = self.client.get(url) self.assertEqual(response.data['id'], location.id) def test_geojson_id_attribute_slug(self): location = Location.objects.create( name='geojson test', geometry='POINT (10.1 10.1)' ) url = reverse('api_geojson_location_slug_details', args=[location.slug]) response = self.client.get(url) self.assertEqual(response.data['id'], location.slug) def test_geojson_false_id_attribute_slug(self): location = Location.objects.create( name='falseid test', geometry='POINT (10.1 10.1)' ) url = reverse('api_geojson_location_falseid_details', args=[location.id]) response = self.client.get(url) self.assertEqual(response.data['properties']['name'], 'falseid test') with self.assertRaises(KeyError): response.data['id'] def test_geojson_no_id_attribute_slug(self): location = Location.objects.create( name='noid test', geometry='POINT (10.1 10.1)' ) url = reverse('api_geojson_location_noid_details', args=[location.id]) response = self.client.get(url) self.assertEqual(response.data['properties']['name'], 'noid test') with self.assertRaises(KeyError): response.data['id'] def test_geojson_filefield_attribute(self): located_file = LocatedFile.objects.create( name='geojson filefield test', geometry='POINT (10.1 10.1)' ) url = reverse('api_geojson_located_file_details', args=[located_file.id]) response = self.client.get(url) self.assertEqual(response.data['properties']['file'], None) def test_post_geojson_location_list(self): self.assertEqual(Location.objects.count(), 0) data = { "type": "Feature", "properties": {"name": "point?", "details": "ignore this"}, "geometry": {"type": "Point", "coordinates": [10.1, 10.1]}, } response = self.client.post( self.geojson_location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) url = reverse( 'api_geojson_location_details', args=[Location.objects.order_by('-id')[0].id], ) response = self.client.get(url) self.assertEqual(response.data['properties']['name'], "point?") self.assertEqual(response.data['geometry']['type'], "Point") self.assertEqual( json.dumps(response.data['geometry']['coordinates']), "[10.1, 10.1]" ) self.assertNotEqual(response.data['properties']['details'], "ignore this") def test_post_geojson_location_list_HTML(self): self.assertEqual(Location.objects.count(), 0) data = { "type": "Feature", "properties": {"name": "point?", "details": "ignore this"}, "geometry": {"type": "Point", "coordinates": [10.1, 10.1]}, } response = self.client.post( self.geojson_location_list_url, data=json.dumps(data), content_type='application/json', HTTP_ACCEPT='text/html', ) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) url = reverse( 'api_geojson_location_details', args=[Location.objects.order_by('-id')[0].id], ) response = self.client.get(url) self.assertEqual(response.data['properties']['name'], "point?") self.assertEqual(response.data['geometry']['type'], "Point") self.assertEqual( json.dumps(response.data['geometry']['coordinates']), "[10.1, 10.1]" ) self.assertNotEqual(response.data['properties']['details'], "ignore this") def test_post_invalid_geojson_location_list(self): data = { "type": "Feature", "properties": {"details": "ignore this"}, "geometry": {"type": "Point", "coordinates": [10.1, 10.1]}, } response = self.client.post( self.geojson_location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 400) self.assertEqual(Location.objects.count(), 0) self.assertEqual(response.data['name'][0], "This field is required.") data = { "type": "Feature", "properties": {"name": "point?"}, "geometry": {"type": "Point", "WRONG": {}}, } response = self.client.post( self.geojson_location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 400) self.assertEqual(Location.objects.count(), 0) self.assertEqual(response.data['geometry'][0], self.gdal_error_message) def test_post_geojson_location_list_WKT(self): self.assertEqual(Location.objects.count(), 0) data = { "type": "Feature", "properties": {"name": "point?"}, "geometry": "POINT (10.1 10.1)", } response = self.client.post( self.geojson_location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) url = reverse( 'api_geojson_location_details', args=[Location.objects.order_by('-id')[0].id], ) response = self.client.get(url) self.assertEqual(response.data['properties']['name'], "point?") self.assertEqual(response.data['geometry']['type'], "Point") self.assertEqual( json.dumps(response.data['geometry']['coordinates']), "[10.1, 10.1]" ) def test_geofeatured_model_serializer_compatible_with_geomodel_serializer(self): self.assertEqual(Location.objects.count(), 0) data = { "name": "geojson input test", "geometry": { "type": "GeometryCollection", "geometries": [ {"type": "Point", "coordinates": [12.492324113849, 41.890307434153]} ], }, } response = self.client.post( self.geojson_location_list_url, data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) def test_geofeatured_model_post_as_multipartformdata(self): """ emulate sending geojson string in webform """ self.assertEqual(Location.objects.count(), 0) data = { "name": "geojson input test", "geometry": json.dumps( {"type": "Point", "coordinates": [12.492324113849, 41.890307434153]} ), } response = self.client.post(self.location_list_url, data) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) self.assertEqual(response.data['geometry']['type'], "Point") def test_HTML_browsable_geojson_location_list(self): response = self.client.get( self.geojson_location_list_url, HTTP_ACCEPT='text/html' ) self.assertEqual(response.status_code, 200) self._create_locations() response = self.client.get( self.geojson_location_list_url, HTTP_ACCEPT='text/html' ) self.assertContains(response, 'l1') self.assertContains(response, 'l2') def test_post_geojson_location_list_HTML_web_form(self): self.assertEqual(Location.objects.count(), 0) data = { "name": "HTML test", "geometry": json.dumps({"type": "Point", "coordinates": [10.1, 10.1]}), } response = self.client.post( self.geojson_location_list_url, data, HTTP_ACCEPT='text/html' ) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) location = Location.objects.all()[0] self.assertEqual(location.name, "HTML test") self.assertEqual(location.geometry.geom_type, "Point") def test_post_geojson_location_list_HTML_web_form_WKT(self): self.assertEqual(Location.objects.count(), 0) data = {"name": "HTML test WKT", "geometry": "POINT (10.1 10.1)"} response = self.client.post( self.geojson_location_list_url, data, HTTP_ACCEPT='text/html' ) self.assertEqual(response.status_code, 201) self.assertEqual(Location.objects.count(), 1) location = Location.objects.all()[0] self.assertEqual(location.name, "HTML test WKT") @skipIf(is_pre_drf_39, 'Skip this test if DRF < 3.9') def test_geojson_HTML_widget_value(self): self._create_locations() response = self.client.get( self.geojson_location_list_url, HTTP_ACCEPT='text/html' ) self.assertContains(response, '<textarea name="geometry"') self.assertContains(response, '"type": "Point"') self.assertContains(response, '"coordinates": [') @skipIf(not is_pre_drf_39, 'Skip this test if DRF >= 3.9') def test_geojson_HTML_widget_value_pre_drf_39(self): self._create_locations() response = self.client.get( self.geojson_location_list_url, HTTP_ACCEPT='text/html' ) self.assertContains(response, '<textarea name="geometry"') self.assertContains(response, '&quot;type&quot;: &quot;Point&quot;') self.assertContains(response, '&quot;coordinates&quot;: [') # TODO: remove this when python 2 will be deprecated self.assertNotContains( response, 'u&#39;type&#39;: u&#39;Point&#39;, u&#39;coordinates&#39;:' ) def test_patch_geojson_location(self): location = Location.objects.create( name='geojson patch test', geometry='POINT (135.0 45.0)' ) url = reverse('api_geojson_location_details', args=[location.id]) data = { "properties": {"name": "geojson successful patch test"}, "geometry": {"type": "Point", "coordinates": [10.1, 10.1]}, } response = self.client.generic( 'PATCH', url, json.dumps(data), content_type='application/json' ) self.assertEqual(response.status_code, 200) location_reloaded = Location.objects.get(pk=location.id) self.assertEquals(location_reloaded.name, 'geojson successful patch test') self.assertEquals( location_reloaded.geometry, Point(10.1, 10.1, srid=location.geometry.srid) ) def test_patch_geojson_location_wo_changing_geometry(self): location = Location.objects.create( name='geojson patch test', geometry='POINT (135.0 45.0)' ) url = reverse('api_geojson_location_details', args=[location.id]) data = {"properties": {"name": "geojson successful patch test"}} response = self.client.generic( 'PATCH', url, json.dumps(data), content_type='application/json' ) self.assertEqual(response.status_code, 200) location_reloaded = Location.objects.get(pk=location.id) self.assertEquals(location_reloaded.name, 'geojson successful patch test') self.assertEquals( location_reloaded.geometry, Point(135.0, 45.0, srid=location.geometry.srid) ) def test_geometry_serializer_method_field(self): location = Location.objects.create( name='geometry serializer method test', geometry='POINT (135.0 45.0)' ) location_loaded = Location.objects.get(pk=location.id) self.assertEqual(location_loaded.name, 'geometry serializer method test') self.assertEqual( location_loaded.geometry, Point(135.0, 45.0, srid=location.geometry.srid) ) url = reverse('api_geojson_location_details_hidden', args=[location.id]) data = {"properties": {"name": "hidden geometry"}} response = self.client.generic( 'PATCH', url, json.dumps(data), content_type='application/json' ) self.assertEqual(response.status_code, 200) self.assertEqual(response.data['properties']['name'], 'hidden geometry') self.assertEqual(response.data['geometry']['type'], 'Point') self.assertEqual(response.data['geometry']['coordinates'], [0.0, 0.0]) def test_geometry_serializer_method_field_none(self): location = Location.objects.create( name='None value', geometry='POINT (135.0 45.0)' ) location_loaded = Location.objects.get(pk=location.id) self.assertEqual( location_loaded.geometry, Point(135.0, 45.0, srid=location.geometry.srid) ) url = reverse('api_geojson_location_details_none', args=[location.id]) response = self.client.generic('GET', url, content_type='application/json') self.assertEqual(response.status_code, 200) self.assertEqual(response.data['properties']['name'], 'None value') self.assertEqual(response.data['geometry'], None) def test_nullable_empty_geometry(self): empty = Nullable(name='empty', geometry='POINT EMPTY') empty.full_clean() empty.save() url = reverse('api_geojson_nullable_details', args=[empty.id]) response = self.client.generic('GET', url, content_type='application/json') self.assertIsNotNone(response.data['geometry']) self.assertEqual(response.data['geometry']['coordinates'], []) def test_nullable_null_geometry(self): empty = Nullable(name='empty', geometry=None) empty.full_clean() empty.save() url = reverse('api_geojson_nullable_details', args=[empty.id]) response = self.client.generic('GET', url, content_type='application/json') self.assertIsNone(response.data['geometry']) def test_geometry_field_to_representation_none(self): self._create_locations() f = LocationGeoSerializer(instance=self.l1).fields['geometry'] self.assertIsNone(f.to_representation(None)) def test_geometry_empty_representation(self): self._create_locations() f = LocationGeoSerializer(instance=self.l1).fields['geometry'] geom_types = ( 'POINT', 'LINESTRING', 'LINEARRING', 'POLYGON', 'MULTIPOINT', 'MULTILINESTRING', 'MULTIPOLYGON', ) for geom_type in geom_types: with self.subTest(geom_type=geom_type): value = f.to_representation(GEOSGeometry('{} EMPTY'.format(geom_type))) self.assertIsNotNone(value) if geom_type == 'LINEARRING': geom_type = 'LINESTRING' self.assertEqual(value['type'].upper(), geom_type) self.assertEqual(value['coordinates'], []) # GEOMETRYCOLLECTION needs different handling value = f.to_representation(GEOSGeometry('GEOMETRYCOLLECTION EMPTY')) self.assertIsNotNone(value) self.assertEqual(value['type'].upper(), 'GEOMETRYCOLLECTION') self.assertEqual(value['geometries'], []) def test_no_geo_field_improperly_configured(self): class LocationGeoFeatureSerializer(gis_serializers.GeoFeatureModelSerializer): class Meta: model = Location with self.assertRaises(ImproperlyConfigured): LocationGeoFeatureSerializer() def test_exclude_geo_field_improperly_configured(self): self._create_locations() class LocationGeoFeatureSerializer(gis_serializers.GeoFeatureModelSerializer): class Meta: model = Location geo_field = 'geometry' exclude = ('geometry',) with self.assertRaises(ImproperlyConfigured): LocationGeoFeatureSerializer(instance=self.l1) def test_geojson_pagination(self): self._create_locations() response = self.client.get(self.geojson_location_list_url) self.assertEqual(response.data['type'], 'FeatureCollection') self.assertEqual(len(response.data['features']), 2) response = self.client.get( '{0}?page_size=1'.format(self.geojson_location_list_url) ) self.assertEqual(response.data['type'], 'FeatureCollection') self.assertEqual(len(response.data['features']), 1) self.assertIn('next', response.data) self.assertIn('previous', response.data) def test_pickle(self): geometry = GEOSGeometry('POINT (30 10)') geojsondict = GeoJsonDict( (('type', geometry.geom_type), ('coordinates', geometry.coords),) ) pickled = pickle.dumps(geojsondict) restored = pickle.loads(pickled) self.assertEqual(restored, geojsondict) def test_geometrycollection_geojson(self): """ test geometry collection geojson behaviour """ location = Location.objects.create( name='geometry collection geojson test', geometry='GEOMETRYCOLLECTION (' 'POINT (135.0 45.0),' 'LINESTRING (135.0 45.0,140.0 50.0,145.0 55.0),' 'POLYGON ((135.0 45.0,140.0 50.0,145.0 55.0,135.0 45.0)))', ) url = reverse('api_geojson_location_details', args=[location.id]) expected = { 'id': location.id, 'type': 'Feature', 'properties': { 'details': "http://testserver/geojson/%s/" % location.id, 'name': 'geometry collection geojson test', 'fancy_name': 'Kool geometry collection geojson test', 'timestamp': None, 'slug': 'geometry-collection-geojson-test', }, 'geometry': { 'type': 'GeometryCollection', 'geometries': [ {'type': 'Point', 'coordinates': [135.0, 45.0]}, { 'type': 'LineString', 'coordinates': [[135.0, 45.0], [140.0, 50.0], [145.0, 55.0]], }, { 'type': 'Polygon', 'coordinates': [ [ [135.0, 45.0], [140.0, 50.0], [145.0, 55.0], [135.0, 45.0], ] ], }, ], }, } response = self.client.get(url) if sys.version_info > (3, 0, 0): self.assertCountEqual(json.dumps(response.data), json.dumps(expected)) else: self.assertItemsEqual(json.dumps(response.data), json.dumps(expected)) self.assertContains(response, "Kool geometry collection geojson test")
"""Native Home Assistant iOS app component.""" import datetime import logging import voluptuous as vol from homeassistant import config_entries from homeassistant.components.http import HomeAssistantView from homeassistant.const import HTTP_BAD_REQUEST, HTTP_INTERNAL_SERVER_ERROR from homeassistant.core import callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import ( config_entry_flow, config_validation as cv, discovery) from homeassistant.util.json import load_json, save_json _LOGGER = logging.getLogger(__name__) DOMAIN = 'ios' DEPENDENCIES = ['device_tracker', 'http', 'zeroconf'] CONF_PUSH = 'push' CONF_PUSH_CATEGORIES = 'categories' CONF_PUSH_CATEGORIES_NAME = 'name' CONF_PUSH_CATEGORIES_IDENTIFIER = 'identifier' CONF_PUSH_CATEGORIES_ACTIONS = 'actions' CONF_PUSH_ACTIONS_IDENTIFIER = 'identifier' CONF_PUSH_ACTIONS_TITLE = 'title' CONF_PUSH_ACTIONS_ACTIVATION_MODE = 'activationMode' CONF_PUSH_ACTIONS_AUTHENTICATION_REQUIRED = 'authenticationRequired' CONF_PUSH_ACTIONS_DESTRUCTIVE = 'destructive' CONF_PUSH_ACTIONS_BEHAVIOR = 'behavior' CONF_PUSH_ACTIONS_CONTEXT = 'context' CONF_PUSH_ACTIONS_TEXT_INPUT_BUTTON_TITLE = 'textInputButtonTitle' CONF_PUSH_ACTIONS_TEXT_INPUT_PLACEHOLDER = 'textInputPlaceholder' ATTR_FOREGROUND = 'foreground' ATTR_BACKGROUND = 'background' ACTIVATION_MODES = [ATTR_FOREGROUND, ATTR_BACKGROUND] ATTR_DEFAULT_BEHAVIOR = 'default' ATTR_TEXT_INPUT_BEHAVIOR = 'textInput' BEHAVIORS = [ATTR_DEFAULT_BEHAVIOR, ATTR_TEXT_INPUT_BEHAVIOR] ATTR_LAST_SEEN_AT = 'lastSeenAt' ATTR_DEVICE = 'device' ATTR_PUSH_TOKEN = 'pushToken' ATTR_APP = 'app' ATTR_PERMISSIONS = 'permissions' ATTR_PUSH_ID = 'pushId' ATTR_DEVICE_ID = 'deviceId' ATTR_PUSH_SOUNDS = 'pushSounds' ATTR_BATTERY = 'battery' ATTR_DEVICE_NAME = 'name' ATTR_DEVICE_LOCALIZED_MODEL = 'localizedModel' ATTR_DEVICE_MODEL = 'model' ATTR_DEVICE_PERMANENT_ID = 'permanentID' ATTR_DEVICE_SYSTEM_VERSION = 'systemVersion' ATTR_DEVICE_TYPE = 'type' ATTR_DEVICE_SYSTEM_NAME = 'systemName' ATTR_APP_BUNDLE_IDENTIFIER = 'bundleIdentifier' ATTR_APP_BUILD_NUMBER = 'buildNumber' ATTR_APP_VERSION_NUMBER = 'versionNumber' ATTR_LOCATION_PERMISSION = 'location' ATTR_NOTIFICATIONS_PERMISSION = 'notifications' PERMISSIONS = [ATTR_LOCATION_PERMISSION, ATTR_NOTIFICATIONS_PERMISSION] ATTR_BATTERY_STATE = 'state' ATTR_BATTERY_LEVEL = 'level' ATTR_BATTERY_STATE_UNPLUGGED = 'Not Charging' ATTR_BATTERY_STATE_CHARGING = 'Charging' ATTR_BATTERY_STATE_FULL = 'Full' ATTR_BATTERY_STATE_UNKNOWN = 'Unknown' BATTERY_STATES = [ATTR_BATTERY_STATE_UNPLUGGED, ATTR_BATTERY_STATE_CHARGING, ATTR_BATTERY_STATE_FULL, ATTR_BATTERY_STATE_UNKNOWN] ATTR_DEVICES = 'devices' ACTION_SCHEMA = vol.Schema({ vol.Required(CONF_PUSH_ACTIONS_IDENTIFIER): vol.Upper, vol.Required(CONF_PUSH_ACTIONS_TITLE): cv.string, vol.Optional(CONF_PUSH_ACTIONS_ACTIVATION_MODE, default=ATTR_BACKGROUND): vol.In(ACTIVATION_MODES), vol.Optional(CONF_PUSH_ACTIONS_AUTHENTICATION_REQUIRED, default=False): cv.boolean, vol.Optional(CONF_PUSH_ACTIONS_DESTRUCTIVE, default=False): cv.boolean, vol.Optional(CONF_PUSH_ACTIONS_BEHAVIOR, default=ATTR_DEFAULT_BEHAVIOR): vol.In(BEHAVIORS), vol.Optional(CONF_PUSH_ACTIONS_TEXT_INPUT_BUTTON_TITLE): cv.string, vol.Optional(CONF_PUSH_ACTIONS_TEXT_INPUT_PLACEHOLDER): cv.string, }, extra=vol.ALLOW_EXTRA) ACTION_SCHEMA_LIST = vol.All(cv.ensure_list, [ACTION_SCHEMA]) CONFIG_SCHEMA = vol.Schema({ DOMAIN: { CONF_PUSH: { CONF_PUSH_CATEGORIES: vol.All(cv.ensure_list, [{ vol.Required(CONF_PUSH_CATEGORIES_NAME): cv.string, vol.Required(CONF_PUSH_CATEGORIES_IDENTIFIER): vol.Lower, vol.Required(CONF_PUSH_CATEGORIES_ACTIONS): ACTION_SCHEMA_LIST }]) } } }, extra=vol.ALLOW_EXTRA) IDENTIFY_DEVICE_SCHEMA = vol.Schema({ vol.Required(ATTR_DEVICE_NAME): cv.string, vol.Required(ATTR_DEVICE_LOCALIZED_MODEL): cv.string, vol.Required(ATTR_DEVICE_MODEL): cv.string, vol.Required(ATTR_DEVICE_PERMANENT_ID): cv.string, vol.Required(ATTR_DEVICE_SYSTEM_VERSION): cv.string, vol.Required(ATTR_DEVICE_TYPE): cv.string, vol.Required(ATTR_DEVICE_SYSTEM_NAME): cv.string, }, extra=vol.ALLOW_EXTRA) IDENTIFY_DEVICE_SCHEMA_CONTAINER = vol.All(dict, IDENTIFY_DEVICE_SCHEMA) IDENTIFY_APP_SCHEMA = vol.Schema({ vol.Required(ATTR_APP_BUNDLE_IDENTIFIER): cv.string, vol.Required(ATTR_APP_BUILD_NUMBER): cv.positive_int, vol.Optional(ATTR_APP_VERSION_NUMBER): cv.string }, extra=vol.ALLOW_EXTRA) IDENTIFY_APP_SCHEMA_CONTAINER = vol.All(dict, IDENTIFY_APP_SCHEMA) IDENTIFY_BATTERY_SCHEMA = vol.Schema({ vol.Required(ATTR_BATTERY_LEVEL): cv.positive_int, vol.Required(ATTR_BATTERY_STATE): vol.In(BATTERY_STATES) }, extra=vol.ALLOW_EXTRA) IDENTIFY_BATTERY_SCHEMA_CONTAINER = vol.All(dict, IDENTIFY_BATTERY_SCHEMA) IDENTIFY_SCHEMA = vol.Schema({ vol.Required(ATTR_DEVICE): IDENTIFY_DEVICE_SCHEMA_CONTAINER, vol.Required(ATTR_BATTERY): IDENTIFY_BATTERY_SCHEMA_CONTAINER, vol.Required(ATTR_PUSH_TOKEN): cv.string, vol.Required(ATTR_APP): IDENTIFY_APP_SCHEMA_CONTAINER, vol.Required(ATTR_PERMISSIONS): vol.All(cv.ensure_list, [vol.In(PERMISSIONS)]), vol.Required(ATTR_PUSH_ID): cv.string, vol.Required(ATTR_DEVICE_ID): cv.string, vol.Optional(ATTR_PUSH_SOUNDS): list }, extra=vol.ALLOW_EXTRA) CONFIGURATION_FILE = '.ios.conf' def devices_with_push(hass): """Return a dictionary of push enabled targets.""" targets = {} for device_name, device in hass.data[DOMAIN][ATTR_DEVICES].items(): if device.get(ATTR_PUSH_ID) is not None: targets[device_name] = device.get(ATTR_PUSH_ID) return targets def enabled_push_ids(hass): """Return a list of push enabled target push IDs.""" push_ids = list() for device in hass.data[DOMAIN][ATTR_DEVICES].values(): if device.get(ATTR_PUSH_ID) is not None: push_ids.append(device.get(ATTR_PUSH_ID)) return push_ids def devices(hass): """Return a dictionary of all identified devices.""" return hass.data[DOMAIN][ATTR_DEVICES] def device_name_for_push_id(hass, push_id): """Return the device name for the push ID.""" for device_name, device in hass.data[DOMAIN][ATTR_DEVICES].items(): if device.get(ATTR_PUSH_ID) is push_id: return device_name return None async def async_setup(hass, config): """Set up the iOS component.""" conf = config.get(DOMAIN) ios_config = await hass.async_add_executor_job( load_json, hass.config.path(CONFIGURATION_FILE)) if ios_config == {}: ios_config[ATTR_DEVICES] = {} ios_config[CONF_PUSH] = (conf or {}).get(CONF_PUSH, {}) hass.data[DOMAIN] = ios_config # No entry support for notify component yet discovery.load_platform(hass, 'notify', DOMAIN, {}, config) if conf is not None: hass.async_create_task(hass.config_entries.flow.async_init( DOMAIN, context={'source': config_entries.SOURCE_IMPORT})) return True async def async_setup_entry(hass, entry): """Set up an iOS entry.""" hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, 'sensor')) hass.http.register_view( iOSIdentifyDeviceView(hass.config.path(CONFIGURATION_FILE))) hass.http.register_view(iOSPushConfigView(hass.data[DOMAIN][CONF_PUSH])) return True # pylint: disable=invalid-name class iOSPushConfigView(HomeAssistantView): """A view that provides the push categories configuration.""" url = '/api/ios/push' name = 'api:ios:push' def __init__(self, push_config): """Init the view.""" self.push_config = push_config @callback def get(self, request): """Handle the GET request for the push configuration.""" return self.json(self.push_config) class iOSIdentifyDeviceView(HomeAssistantView): """A view that accepts device identification requests.""" url = '/api/ios/identify' name = 'api:ios:identify' def __init__(self, config_path): """Initiliaze the view.""" self._config_path = config_path async def post(self, request): """Handle the POST request for device identification.""" try: data = await request.json() except ValueError: return self.json_message("Invalid JSON", HTTP_BAD_REQUEST) hass = request.app['hass'] # Commented for now while iOS app is getting frequent updates # try: # data = IDENTIFY_SCHEMA(req_data) # except vol.Invalid as ex: # return self.json_message( # vol.humanize.humanize_error(request.json, ex), # HTTP_BAD_REQUEST) data[ATTR_LAST_SEEN_AT] = datetime.datetime.now().isoformat() name = data.get(ATTR_DEVICE_ID) hass.data[DOMAIN][ATTR_DEVICES][name] = data try: save_json(self._config_path, hass.data[DOMAIN]) except HomeAssistantError: return self.json_message("Error saving device.", HTTP_INTERNAL_SERVER_ERROR) return self.json({"status": "registered"}) config_entry_flow.register_discovery_flow( DOMAIN, 'Home Assistant iOS', lambda *_: True, config_entries.CONN_CLASS_CLOUD_PUSH)
""" Includes BaseModel, which can be used as an ndb mixin that's fully searchable. """ import string from google.appengine.ext import ndb from google.appengine.api import search from google.appengine.ext.ndb.polymodel import PolyModel SEARCHABLE_PROPERTY_TYPES = { ndb.TextProperty: search.TextField, ndb.IntegerProperty: search.NumberField, ndb.FloatProperty: search.NumberField, ndb.DateProperty: search.DateField, ndb.KeyProperty: search.AtomField } alphabet = string.digits + string.letters class SearchableModel(object): """ Mix this class into your ndb models to make them searchable. """ searching_enabled = True searchable_fields = None # defaults to all fields search_index = 'general-index' @classmethod def search_get_index(cls): """ Returns index to be used. You may override this. :return: instance of search.Index """ return search.Index(name=cls.search_index) @staticmethod def search_get_document_id(key): """ Returns an index document id from a key. Defaults to just using the key's urlsafe string. :param key: ndb.Key instance :return: String for document index """ return key.urlsafe() @classmethod def search(cls, query_string, options=None, enable_facet_discovery=False, return_facets=None, facet_options=None, facet_refinements=None, deadline=None, **kwargs): """ Searches the index. Conveniently searches only for documents that belong to instances of this class. :param query_string: The query to match against documents in the index. See search.Query() for details. :param options: A QueryOptions describing post-processing of search results. :param enable_facet_discovery: discovery top relevent facets to this search query and return them. :param return_facets: An iterable of FacetRequest or basestring as facet name to return specific facet with the result. :param facet_options: A FacetOption describing processing of facets. :param facet_refinements: An iterable of FacetRefinement objects or refinement token strings used to filter out search results based on a facet value. refinements for different facets will be conjunction and refinements for the same facet will be disjunction. :param deadline: Deadline for RPC call in seconds; if None use the default. :param kwargs: A SearchResults containing a list of documents matched, number returned and number matched by the query. :return: A SearchResults containing a list of documents matched, number returned and number matched by the query. :raises: QueryError: If the query string is not parseable. TypeError: If any of the parameters have invalid types, or an unknown attribute is passed. ValueError: If any of the parameters have invalid values (e.g., a negative deadline). """ search_class = cls.search_get_class_names()[-1] query_string += ' ' + 'class_name:%s' % (search_class,) q = search.Query( query_string=query_string, options=options, enable_facet_discovery=enable_facet_discovery, return_facets=return_facets, facet_options=facet_options, facet_refinements=facet_refinements ) index = cls.search_get_index() return index.search(q, deadline=deadline, **kwargs) def search_update_index(self): """ Updates the search index for this instance. This happens automatically on put. """ doc_id = self.search_get_document_id(self.key) fields = [search.AtomField('class_name', name) for name in self.search_get_class_names()] index = self.search_get_index() if self.searchable_fields is None: searchable_fields = [] for field, prop in self._properties.items(): if field == 'class': continue for class_, field_type in SEARCHABLE_PROPERTY_TYPES.items(): if isinstance(prop, class_): searchable_fields.append(field) else: searchable_fields = self.searchable_fields for f in set(searchable_fields): prop = self._properties[f] value = getattr(self, f) field = None field_found = False for class_, field_type in SEARCHABLE_PROPERTY_TYPES.items(): if isinstance(prop, class_): field_found = True if value is not None: if isinstance(value, list) or isinstance(value, tuple) or isinstance(value, set): for v in value: field = field_type(name=f, value=v) elif isinstance(value, ndb.Key): field = field_type(name=f, value=value.urlsafe()) else: field = field_type(name=f, value=value) if not field_found: raise ValueError('Cannot find field type for %r on %r' % (prop, self.__class__)) if field is not None: fields.append(field) document = search.Document(doc_id, fields=fields) index.put(document) @classmethod def search_get_class_names(cls): """ Returns class names for use in document indexing. """ if hasattr(cls, '_class_key'): class_names = [] for n in cls._class_key(): class_names.append(n) return class_names else: return [cls.__name__] @classmethod def from_urlsafe(cls, urlsafe): """ Returns an instance of the model from a urlsafe string. :param urlsafe: urlsafe key :return: Instance of cls """ try: key = ndb.Key(urlsafe=urlsafe) except: return None obj = key.get() if obj and isinstance(obj, cls): return obj @classmethod def get_from_search_doc(cls, doc_id): """ Returns an instance of the model from a search document id. :param doc_id: Search document id :return: Instance of cls """ # If the document was passed instead of the doc_id, get the document. if hasattr(doc_id, 'doc_id'): doc_id = doc_id.doc_id return cls.from_urlsafe(doc_id) @classmethod def _pre_delete_hook(cls, key): """ Removes instance from index. """ if cls.searching_enabled: doc_id = cls.search_get_document_id(key) index = cls.search_get_index() index.delete(doc_id) def _post_put_hook(self, future): """ Updates or creates instance in index. """ if self.searching_enabled: self.search_update_index()
try: from itertools import zip_longest except ImportError: from itertools import izip_longest as zip_longest from django.utils.six.moves import zip from django.db.backends.util import truncate_name, typecast_timestamp from django.db.models.sql import compiler from django.db.models.sql.constants import MULTI from django.utils import six SQLCompiler = compiler.SQLCompiler class GeoSQLCompiler(compiler.SQLCompiler): def get_columns(self, with_aliases=False): """ Return the list of columns to use in the select statement. If no columns have been specified, returns all columns relating to fields in the model. If 'with_aliases' is true, any column names that are duplicated (without the table names) are given unique aliases. This is needed in some cases to avoid ambiguitity with nested queries. This routine is overridden from Query to handle customized selection of geometry columns. """ qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name result = ['(%s) AS %s' % (self.get_extra_select_format(alias) % col[0], qn2(alias)) for alias, col in six.iteritems(self.query.extra_select)] aliases = set(self.query.extra_select.keys()) if with_aliases: col_aliases = aliases.copy() else: col_aliases = set() if self.query.select: only_load = self.deferred_to_columns() # This loop customized for GeoQuery. for col, field in self.query.select: if isinstance(col, (list, tuple)): alias, column = col table = self.query.alias_map[alias].table_name if table in only_load and column not in only_load[table]: continue r = self.get_field_select(field, alias, column) if with_aliases: if col[1] in col_aliases: c_alias = 'Col%d' % len(col_aliases) result.append('%s AS %s' % (r, c_alias)) aliases.add(c_alias) col_aliases.add(c_alias) else: result.append('%s AS %s' % (r, qn2(col[1]))) aliases.add(r) col_aliases.add(col[1]) else: result.append(r) aliases.add(r) col_aliases.add(col[1]) else: result.append(col.as_sql(qn, self.connection)) if hasattr(col, 'alias'): aliases.add(col.alias) col_aliases.add(col.alias) elif self.query.default_cols: cols, new_aliases = self.get_default_columns(with_aliases, col_aliases) result.extend(cols) aliases.update(new_aliases) max_name_length = self.connection.ops.max_name_length() result.extend([ '%s%s' % ( self.get_extra_select_format(alias) % aggregate.as_sql(qn, self.connection), alias is not None and ' AS %s' % qn(truncate_name(alias, max_name_length)) or '' ) for alias, aggregate in self.query.aggregate_select.items() ]) # This loop customized for GeoQuery. for (table, col), field in self.query.related_select_cols: r = self.get_field_select(field, table, col) if with_aliases and col in col_aliases: c_alias = 'Col%d' % len(col_aliases) result.append('%s AS %s' % (r, c_alias)) aliases.add(c_alias) col_aliases.add(c_alias) else: result.append(r) aliases.add(r) col_aliases.add(col) self._select_aliases = aliases return result def get_default_columns(self, with_aliases=False, col_aliases=None, start_alias=None, opts=None, as_pairs=False, from_parent=None): """ Computes the default columns for selecting every field in the base model. Will sometimes be called to pull in related models (e.g. via select_related), in which case "opts" and "start_alias" will be given to provide a starting point for the traversal. Returns a list of strings, quoted appropriately for use in SQL directly, as well as a set of aliases used in the select statement (if 'as_pairs' is True, returns a list of (alias, col_name) pairs instead of strings as the first component and None as the second component). This routine is overridden from Query to handle customized selection of geometry columns. """ result = [] if opts is None: opts = self.query.model._meta aliases = set() only_load = self.deferred_to_columns() seen = self.query.included_inherited_models.copy() if start_alias: seen[None] = start_alias for field, model in opts.get_fields_with_model(): if from_parent and model is not None and issubclass(from_parent, model): # Avoid loading data for already loaded parents. continue alias = self.query.join_parent_model(opts, model, start_alias, seen) table = self.query.alias_map[alias].table_name if table in only_load and field.column not in only_load[table]: continue if as_pairs: result.append((alias, field.column)) aliases.add(alias) continue # This part of the function is customized for GeoQuery. We # see if there was any custom selection specified in the # dictionary, and set up the selection format appropriately. field_sel = self.get_field_select(field, alias) if with_aliases and field.column in col_aliases: c_alias = 'Col%d' % len(col_aliases) result.append('%s AS %s' % (field_sel, c_alias)) col_aliases.add(c_alias) aliases.add(c_alias) else: r = field_sel result.append(r) aliases.add(r) if with_aliases: col_aliases.add(field.column) return result, aliases def resolve_columns(self, row, fields=()): """ This routine is necessary so that distances and geometries returned from extra selection SQL get resolved appropriately into Python objects. """ values = [] aliases = list(self.query.extra_select) # Have to set a starting row number offset that is used for # determining the correct starting row index -- needed for # doing pagination with Oracle. rn_offset = 0 if self.connection.ops.oracle: if self.query.high_mark is not None or self.query.low_mark: rn_offset = 1 index_start = rn_offset + len(aliases) # Converting any extra selection values (e.g., geometries and # distance objects added by GeoQuerySet methods). values = [self.query.convert_values(v, self.query.extra_select_fields.get(a, None), self.connection) for v, a in zip(row[rn_offset:index_start], aliases)] if self.connection.ops.oracle or getattr(self.query, 'geo_values', False): # We resolve the rest of the columns if we're on Oracle or if # the `geo_values` attribute is defined. for value, field in zip_longest(row[index_start:], fields): values.append(self.query.convert_values(value, field, self.connection)) else: values.extend(row[index_start:]) return tuple(values) #### Routines unique to GeoQuery #### def get_extra_select_format(self, alias): sel_fmt = '%s' if hasattr(self.query, 'custom_select') and alias in self.query.custom_select: sel_fmt = sel_fmt % self.query.custom_select[alias] return sel_fmt def get_field_select(self, field, alias=None, column=None): """ Returns the SELECT SQL string for the given field. Figures out if any custom selection SQL is needed for the column The `alias` keyword may be used to manually specify the database table where the column exists, if not in the model associated with this `GeoQuery`. Similarly, `column` may be used to specify the exact column name, rather than using the `column` attribute on `field`. """ sel_fmt = self.get_select_format(field) if field in self.query.custom_select: field_sel = sel_fmt % self.query.custom_select[field] else: field_sel = sel_fmt % self._field_column(field, alias, column) return field_sel def get_select_format(self, fld): """ Returns the selection format string, depending on the requirements of the spatial backend. For example, Oracle and MySQL require custom selection formats in order to retrieve geometries in OGC WKT. For all other fields a simple '%s' format string is returned. """ if self.connection.ops.select and hasattr(fld, 'geom_type'): # This allows operations to be done on fields in the SELECT, # overriding their values -- used by the Oracle and MySQL # spatial backends to get database values as WKT, and by the # `transform` method. sel_fmt = self.connection.ops.select # Because WKT doesn't contain spatial reference information, # the SRID is prefixed to the returned WKT to ensure that the # transformed geometries have an SRID different than that of the # field -- this is only used by `transform` for Oracle and # SpatiaLite backends. if self.query.transformed_srid and ( self.connection.ops.oracle or self.connection.ops.spatialite ): sel_fmt = "'SRID=%d;'||%s" % (self.query.transformed_srid, sel_fmt) else: sel_fmt = '%s' return sel_fmt # Private API utilities, subject to change. def _field_column(self, field, table_alias=None, column=None): """ Helper function that returns the database column for the given field. The table and column are returned (quoted) in the proper format, e.g., `"geoapp_city"."point"`. If `table_alias` is not specified, the database table associated with the model of this `GeoQuery` will be used. If `column` is specified, it will be used instead of the value in `field.column`. """ if table_alias is None: table_alias = self.query.model._meta.db_table return "%s.%s" % (self.quote_name_unless_alias(table_alias), self.connection.ops.quote_name(column or field.column)) class SQLInsertCompiler(compiler.SQLInsertCompiler, GeoSQLCompiler): pass class SQLDeleteCompiler(compiler.SQLDeleteCompiler, GeoSQLCompiler): pass class SQLUpdateCompiler(compiler.SQLUpdateCompiler, GeoSQLCompiler): pass class SQLAggregateCompiler(compiler.SQLAggregateCompiler, GeoSQLCompiler): pass class SQLDateCompiler(compiler.SQLDateCompiler, GeoSQLCompiler): """ This is overridden for GeoDjango to properly cast date columns, since `GeoQuery.resolve_columns` is used for spatial values. See #14648, #16757. """ def results_iter(self): if self.connection.ops.oracle: from django.db.models.fields import DateTimeField fields = [DateTimeField()] else: needs_string_cast = self.connection.features.needs_datetime_string_cast offset = len(self.query.extra_select) for rows in self.execute_sql(MULTI): for row in rows: date = row[offset] if self.connection.ops.oracle: date = self.resolve_columns(row, fields)[offset] elif needs_string_cast: date = typecast_timestamp(str(date)) yield date
"""This module implements functions that have to do with number theory.""" import random from operator import mul _stock_primes = [2, 3, 5, 7, 11, 13, 17, 19] def int_pow(x, n): """Raise x to the power n (if n is negative a ValueError is raised). intPow(0, 0) is defined to be 0. """ if n < 0: raise ValueError("n must be non-negative") elif n == 0: return 1 else: if n % 2 == 0: tmp = int_pow(x, n // 2) return tmp * tmp else: return x * int_pow(x, n - 1) def mod_exp(b, e, m): """Calculate b to the e modulo m.""" if e < 0: raise ValueError("e must be non-negative") elif e == 0: return 1 else: if e % 2 == 0: tmp = mod_exp(b, e // 2, m) return tmp * tmp % m else: return b * mod_exp(b, e - 1, m) % m def discrete_log(alpha, beta, n, totient_n): """ Calculate x such that alpha^x = beta in group G of order n. If no such x exists, then None is returned. """ lookup = dict() m = int(ceil(sqrt(n))) for j in range(0, m): lookup[mod_exp(alpha, j, n)] = j alpha_to_minus_m = mod_exp(alpha, m, n) alpha_to_minus_m = mod_exp(alpha_to_minus_m, totient_n - 1, n) gamma = beta for i in range(m): if gamma in lookup: return i * m + lookup[gamma] gamma = (gamma * alpha_to_minus_m) % n def miller_rabin(n, k): """Declare n probably prime with probability at most 1/4^k (if returns true) otherwise declare n composite (if returns false). """ if n <= 4: if n in (2, 3): return True else: return False d = n - 1 s = 0 while d % 2 == 0: d = d // 2 s += 1 for _ in range(k): a = random.randint(2, n - 2) x = mod_exp(a, d, n) if x in (1, n - 1): continue next_loop = False for r in range(1, s): x = x * x % n if x == 1: return False #composite if x == n - 1: next_loop = True break if not next_loop: return False #composite return True #probably prime def prime_sieve(n): """Calculate all primes up to and including n, and return the list of those primes. If n is negative, a ValueError is raised. """ if n < 0: raise ValueError("n must be non-negative") candidates = list(range(n+1)) finish = int(n**0.5) for i in range(2, finish+1): if candidates[i]: candidates[i*i::i] = [None] * len(candidates[i*i::i]) return [i for i in candidates[2:] if i] def prime(n, primes=_stock_primes): """Checks if an integer n is a prime number. If primes is provided, these can be used to speed up the test.""" if n < 2: return False for p in primes: if p * p > n: return True if n % p == 0: return False p = primes[-1] + 2 while p * p <= n: if n % p == 0: return False p = p + 2 return True def isqrt(n): """Calculate the integer part of the square root of a natural number n. Uses a binary search to find the integer square root, and so runs logarithmically. If n negative, a ValueError is raised. """ if n < 0: raise ValueError("n must be non-negative") a, b = 0, n+1 while b - a != 1: mid = (a + b) // 2 if mid*mid <= n: a = mid else: b = mid return a def perfect_square(n): """Calculate if an integer is a perfect square. Constant time complexity for most numbers due to modulo tests. Worst case time complexity is logn when the square of the isqrt is checked against n. """ #negative values cannot be perfect squares if n < 0: return False #checks modulo 256 if (n & 7 != 1) and (n & 31 != 4) and (n & 127 != 16) and (n & 191 != 0): return False #checks the modulus of n is a quadratic residue mod 9, 5, 7, 13, and 17. if n % 9 not in (0, 1, 4, 7): return False if n % 5 not in (0, 1, 4): return False if n % 7 not in (0, 1, 2, 4): return False if n % 13 not in (0, 1, 3, 4, 9, 10, 12): return False if n % 17 not in (0, 1, 2, 4, 8, 9, 13, 15, 16): return False #check using isqrt i = isqrt(n) return i*i == n def decomp_sieve(n): """Calculate the prime decomposition for each number up and including n, and return the prime decompositions in a list indexed by that number. """ result = [dict() for i in range(n+1)] p = 2 while p <= n: for pk in range(p, n+1, p): result[pk][p] = 1 palpha = p*p while palpha <= n: for palphak in range(palpha, n+1, palpha): result[palphak][p] += 1 palpha *= p while p <= n and result[p]: p += 1 return result def decomp(n, primes=_stock_primes): """Find the prime decomposition of a natural number. The result is returned as a dictionary whose keys are powers and values are primes. E.g. decomp(12) -> {2:2, 3:1} A list of primes should be provided, with primes at least up to the square root of n. If the prime list doesn't go that high, a ValueError will be raised if any primes geater than the square root of the highest prime provided enters n. """ if n < 1: raise ValueError("n must be positive") record = {} if n == 1: return record for p in primes: power = 0 while n % p == 0: power += 1 n = n // p if power != 0: record[p] = power if p * p > n: if n != 1: record[n] = 1 #this is the last prime in the record return record #we have run out of primes to check... last_p = primes[-1] if last_p * last_p > n: record[n] = 1 else: raise ValueError("not enough prime numbers in primes") def factors(pd): """Yields all factors of a number given its prime decomposition.""" if pd: prime, power = pd.popitem() vals = [int_pow(prime, i) for i in range(power + 1)] for partial_factor in factors(pd): for val in vals: yield val * partial_factor pd[prime] = power else: yield 1 def sum_divisors(pd): """Calculate the lowercase sigma function (sum of divisors) of a natural number given its prime decomposition pd. """ if pd == {}: #decomp corresponds to 1 return 1 else: return reduce(mul, [(int_pow(p, pd[p]+1)-1) // (p-1) for p in pd]) def num_divisors(pd): """Calculates the tau function (number of divisors) of a natural number given its prime decomposition pd. """ if pd == {}: return 1 else: return reduce(mul, [pd[p] + 1 for p in pd]) def nominal_record(n, base): """Calculate the digital record of a natural number n with a certain base. """ if n < 1: raise ValueError("n must be >= 1") if base < 2: raise ValueError("base must be >= 2") record = [] while n > 0: record.insert(0, n % base) n = n // base return record def eval_nominal_record(record, base): """Calculates the integer representation given a digital record and its base. """ place_value = 1 value = 0 for digit in reversed(record): value += digit * place_value place_value *= base return value
# -*- coding: utf-8 -*- # This file is part of Eigen, a lightweight C++ template library # for linear algebra. # # Copyright (C) 2009 Benjamin Schindler <bschindler@inf.ethz.ch> # # Eigen is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 3 of the License, or (at your option) any later version. # # Alternatively, 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. # # Eigen is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the # GNU General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License and a copy of the GNU General Public License along with # Eigen. If not, see <http://www.gnu.org/licenses/>. # Pretty printers for Eigen::Matrix # This is still pretty basic as the python extension to gdb is still pretty basic. # It cannot handle complex eigen types and it doesn't support any of the other eigen types # Such as quaternion or some other type. # This code supports fixed size as well as dynamic size matrices # To use it: # # * Create a directory and put the file as well as an empty __init__.py in # that directory. # * Create a ~/.gdbinit file, that contains the following: # python # import sys # sys.path.insert(0, '/path/to/eigen/printer/directory') # from printers import register_eigen_printers # register_eigen_printers (None) # end import gdb import re import itertools class EigenMatrixPrinter: "Print Eigen Matrix or Array of some kind" def __init__(self, variety, val): "Extract all the necessary information" # Save the variety (presumably "Matrix" or "Array") for later usage self.variety = variety # The gdb extension does not support value template arguments - need to extract them by hand type = val.type if type.code == gdb.TYPE_CODE_REF: type = type.target() self.type = type.unqualified().strip_typedefs() tag = self.type.tag regex = re.compile('\<.*\>') m = regex.findall(tag)[0][1:-1] template_params = m.split(',') template_params = map(lambda x:x.replace(" ", ""), template_params) if template_params[1] == '-0x00000000000000001' or template_params[1] == '-0x000000001': self.rows = val['m_storage']['m_rows'] else: self.rows = int(template_params[1]) if template_params[2] == '-0x00000000000000001' or template_params[2] == '-0x000000001': self.cols = val['m_storage']['m_cols'] else: self.cols = int(template_params[2]) self.options = 0 # default value if len(template_params) > 3: self.options = template_params[3]; self.rowMajor = (int(self.options) & 0x1) self.innerType = self.type.template_argument(0) self.val = val # Fixed size matrices have a struct as their storage, so we need to walk through this self.data = self.val['m_storage']['m_data'] if self.data.type.code == gdb.TYPE_CODE_STRUCT: self.data = self.data['array'] self.data = self.data.cast(self.innerType.pointer()) class _iterator: def __init__ (self, rows, cols, dataPtr, rowMajor): self.rows = rows self.cols = cols self.dataPtr = dataPtr self.currentRow = 0 self.currentCol = 0 self.rowMajor = rowMajor def __iter__ (self): return self def next(self): row = self.currentRow col = self.currentCol if self.rowMajor == 0: if self.currentCol >= self.cols: raise StopIteration self.currentRow = self.currentRow + 1 if self.currentRow >= self.rows: self.currentRow = 0 self.currentCol = self.currentCol + 1 else: if self.currentRow >= self.rows: raise StopIteration self.currentCol = self.currentCol + 1 if self.currentCol >= self.cols: self.currentCol = 0 self.currentRow = self.currentRow + 1 item = self.dataPtr.dereference() self.dataPtr = self.dataPtr + 1 if (self.cols == 1): #if it's a column vector return ('[%d]' % (row,), item) elif (self.rows == 1): #if it's a row vector return ('[%d]' % (col,), item) return ('[%d,%d]' % (row, col), item) def children(self): return self._iterator(self.rows, self.cols, self.data, self.rowMajor) def to_string(self): return "Eigen::%s<%s,%d,%d,%s> (data ptr: %s)" % (self.variety, self.innerType, self.rows, self.cols, "RowMajor" if self.rowMajor else "ColMajor", self.data) class EigenQuaternionPrinter: "Print an Eigen Quaternion" def __init__(self, val): "Extract all the necessary information" # The gdb extension does not support value template arguments - need to extract them by hand type = val.type if type.code == gdb.TYPE_CODE_REF: type = type.target() self.type = type.unqualified().strip_typedefs() self.innerType = self.type.template_argument(0) self.val = val # Quaternions have a struct as their storage, so we need to walk through this self.data = self.val['m_coeffs']['m_storage']['m_data']['array'] self.data = self.data.cast(self.innerType.pointer()) class _iterator: def __init__ (self, dataPtr): self.dataPtr = dataPtr self.currentElement = 0 self.elementNames = ['x', 'y', 'z', 'w'] def __iter__ (self): return self def next(self): element = self.currentElement if self.currentElement >= 4: #there are 4 elements in a quanternion raise StopIteration self.currentElement = self.currentElement + 1 item = self.dataPtr.dereference() self.dataPtr = self.dataPtr + 1 return ('[%s]' % (self.elementNames[element],), item) def children(self): return self._iterator(self.data) def to_string(self): return "Eigen::Quaternion<%s> (data ptr: %s)" % (self.innerType, self.data) def build_eigen_dictionary (): pretty_printers_dict[re.compile('^Eigen::Quaternion<.*>$')] = lambda val: EigenQuaternionPrinter(val) pretty_printers_dict[re.compile('^Eigen::Matrix<.*>$')] = lambda val: EigenMatrixPrinter("Matrix", val) pretty_printers_dict[re.compile('^Eigen::Array<.*>$')] = lambda val: EigenMatrixPrinter("Array", val) def register_eigen_printers(obj): "Register eigen pretty-printers with objfile Obj" if obj == None: obj = gdb obj.pretty_printers.append(lookup_function) def lookup_function(val): "Look-up and return a pretty-printer that can print va." type = val.type if type.code == gdb.TYPE_CODE_REF: type = type.target() type = type.unqualified().strip_typedefs() typename = type.tag if typename == None: return None for function in pretty_printers_dict: if function.search(typename): return pretty_printers_dict[function](val) return None pretty_printers_dict = {} build_eigen_dictionary ()
from datetime import date, timedelta from decimal import Decimal from unittest.mock import Mock import pytest from gold_digger.data_providers import CurrencyLayer, Fixer, GrandTrunk from gold_digger.database.dao_exchange_rate import DaoExchangeRate from gold_digger.database.dao_provider import DaoProvider from gold_digger.database.db_model import ExchangeRate, Provider from gold_digger.managers.exchange_rate_manager import ExchangeRateManager @pytest.fixture def dao_exchange_rate_mock(): """ :return: Mock of gold_digger.database.DaoExchangeRate """ return Mock(DaoExchangeRate) @pytest.fixture def dao_provider_mock(): """ :return: Mock of gold_digger.database.DaoProvider """ mock = Mock(DaoProvider) def _get_or_create_provider_by_name(name): """ :type name: str :rtype: gold_digger.database.db_model.Provider """ return { CurrencyLayer.name: Provider(id=1, name=CurrencyLayer.name), GrandTrunk.name: Provider(id=2, name=GrandTrunk.name), }.get(name) mock.get_or_create_provider_by_name.side_effect = _get_or_create_provider_by_name return mock @pytest.fixture def currency_layer_mock(currencies): """ :type currencies: set[str] :return: Mock of gold_digger.data_providers.CurrencyLayer """ mock = Mock(CurrencyLayer) mock.name = CurrencyLayer.name mock.get_all_by_date.return_value = {"EUR": Decimal(0.77), "USD": Decimal(1)} mock.get_supported_currencies.return_value = currencies mock.has_request_limit = True return mock @pytest.fixture def fixer_mock(currencies): """ :type currencies: set[str] :return: Mock of gold_digger.data_providers.Fixer """ mock = Mock(Fixer) mock.name = Fixer.name mock.get_supported_currencies.return_value = currencies mock.has_request_limit = True return mock @pytest.fixture def grandtrunk_mock(currencies): """ :type currencies: set[str] :return: Mock of gold_digger.data_providers.GrandTrunk """ mock = Mock(GrandTrunk) mock.name = GrandTrunk.name mock.get_all_by_date.return_value = {"EUR": Decimal(0.75), "USD": Decimal(1)} mock.get_supported_currencies.return_value = currencies mock.has_request_limit = False return mock class TestUpdateAllRatesByDate: @staticmethod def test_update_all_rates_by_date(dao_exchange_rate_mock, dao_provider_mock, currency_layer_mock, base_currency, currencies, logger): """ Update rates of all providers for the specified date. :param dao_exchange_rate_mock: Mock of gold_digger.database.DaoExchangeRate :param dao_provider_mock: Mock of gold_digger.database.DaoProvider :param currency_layer_mock: Mock of gold_digger.data_providers.CurrencyLayer :type base_currency: str :type currencies: set[str] :type logger: gold_digger.utils.ContextLogger """ _date = date(2016, 2, 17) exchange_rate_manager = ExchangeRateManager(dao_exchange_rate_mock, dao_provider_mock, [currency_layer_mock], base_currency, currencies) exchange_rate_manager.update_all_rates_by_date(_date, [currency_layer_mock], logger) (actual_records, _), _ = dao_exchange_rate_mock.insert_exchange_rate_to_db.call_args (provider_name,), _ = dao_provider_mock.get_or_create_provider_by_name.call_args assert provider_name == currency_layer_mock.name assert sorted(actual_records, key=lambda x: x["currency"]) == [ {"provider_id": 1, "date": _date, "currency": "EUR", "rate": Decimal(0.77)}, {"provider_id": 1, "date": _date, "currency": "USD", "rate": Decimal(1)}, ] class TestGetOrUpdateRateByDate: @staticmethod def test_get_or_update_rate_by_date(dao_exchange_rate_mock, dao_provider_mock, currency_layer_mock, grandtrunk_mock, base_currency, currencies, logger): """ Get all rates by date. Case: 2 providers, rate of provider 'currency_layer' is in DB, rate of provider 'grandtrunk' miss. Get rate for missing provider and update DB. Finally return list of all rates of the day (all provider rates). :param dao_exchange_rate_mock: Mock of gold_digger.database.DaoExchangeRate :param dao_provider_mock: Mock of gold_digger.database.DaoProvider :param currency_layer_mock: Mock of gold_digger.data_providers.CurrencyLayer :param grandtrunk_mock: Mock of gold_digger.data_providers.GrandTrunk :type base_currency: str :type currencies: set[str] :type logger: gold_digger.utils.ContextLogger """ _date = date(2016, 2, 17) exchange_rate_manager = ExchangeRateManager( dao_exchange_rate_mock, dao_provider_mock, [currency_layer_mock, grandtrunk_mock], base_currency, currencies, ) grandtrunk_mock.get_by_date.return_value = Decimal(0.75) dao_exchange_rate_mock.get_rates_by_date_currency.return_value = [ ExchangeRate(provider=Provider(name=CurrencyLayer.name), date=_date, currency="EUR", rate=Decimal(0.77)), ] dao_exchange_rate_mock.insert_new_rate.return_value = [ ExchangeRate(provider=Provider(name=GrandTrunk.name), date=_date, currency="EUR", rate=Decimal(0.75)), ] exchange_rates = exchange_rate_manager.get_or_update_rate_by_date(_date, currency="EUR", logger=logger) insert_new_rate_args, _ = dao_exchange_rate_mock.insert_new_rate.call_args assert dao_exchange_rate_mock.insert_new_rate.call_count == 1 assert insert_new_rate_args[1].name == GrandTrunk.name assert len(exchange_rates) == 2 @staticmethod def test_get_or_update_rate_by_date__today_after_cron_update( dao_exchange_rate_mock, dao_provider_mock, currency_layer_mock, grandtrunk_mock, base_currency, currencies, logger, ): """ Get all rates by date. Case: 2 providers, both rates are in DB as well as yesterday's data. No requests for yesterday should be made. :param dao_exchange_rate_mock: Mock of gold_digger.database.DaoExchangeRate :param dao_provider_mock: Mock of gold_digger.database.DaoProvider :param currency_layer_mock: Mock of gold_digger.data_providers.CurrencyLayer :param grandtrunk_mock: Mock of gold_digger.data_providers.GrandTrunk :type base_currency: str :type currencies: set[str] :type logger: gold_digger.utils.ContextLogger """ today = date.today() exchange_rate_manager = ExchangeRateManager( dao_exchange_rate_mock, dao_provider_mock, [currency_layer_mock, grandtrunk_mock], base_currency, currencies, ) grandtrunk_mock.get_by_date.return_value = Decimal(0.75) dao_exchange_rate_mock.get_rates_by_date_currency.return_value = [ ExchangeRate(provider=Provider(name=CurrencyLayer.name), date=today, currency="EUR", rate=Decimal(0.77)), ExchangeRate(provider=Provider(name=GrandTrunk.name), date=today, currency="EUR", rate=Decimal(0.75)), ] dao_exchange_rate_mock.get_rate_by_date_currency_provider.return_value = [] exchange_rates = exchange_rate_manager.get_or_update_rate_by_date(today, currency="EUR", logger=logger) assert dao_exchange_rate_mock.get_rate_by_date_currency_provider.call_count == 0 assert len(exchange_rates) == 2 @staticmethod def test_get_or_update_rate_by_date__today_before_cron_update( dao_exchange_rate_mock, dao_provider_mock, currency_layer_mock, grandtrunk_mock, base_currency, currencies, logger, ): """ Get all rates by date. Case: 2 providers, rate of provider 'currency_layer' is in DB, rate of provider 'grandtrunk' miss, the date is today, yesterday's rates are in DB. Get rate for missing provider from yesterday. Finally return list of all rates of the day (all provider rates). :param dao_exchange_rate_mock: Mock of gold_digger.database.DaoExchangeRate :param dao_provider_mock: Mock of gold_digger.database.DaoProvider :param currency_layer_mock: Mock of gold_digger.data_providers.CurrencyLayer :param grandtrunk_mock: Mock of gold_digger.data_providers.GrandTrunk :type base_currency: str :type currencies: set[str] :type logger: gold_digger.utils.ContextLogger """ today = date.today() yesterday = today - timedelta(1) exchange_rate_manager = ExchangeRateManager( dao_exchange_rate_mock, dao_provider_mock, [currency_layer_mock, grandtrunk_mock], base_currency, currencies, ) grandtrunk_mock.get_by_date.return_value = Decimal(0.75) dao_exchange_rate_mock.get_rates_by_date_currency.return_value = [ ExchangeRate(provider=Provider(name=CurrencyLayer.name), date=today, currency="EUR", rate=Decimal(0.77)), ] dao_exchange_rate_mock.get_rate_by_date_currency_provider.return_value = [ ExchangeRate(provider=Provider(name=GrandTrunk.name), date=yesterday, currency="EUR", rate=Decimal(0.75)), ] exchange_rates = exchange_rate_manager.get_or_update_rate_by_date(today, currency="EUR", logger=logger) assert dao_exchange_rate_mock.get_rate_by_date_currency_provider.call_count == 1 assert dao_exchange_rate_mock.get_rate_by_date_currency_provider.call_args[0] == (yesterday, "EUR", GrandTrunk.name) assert len(exchange_rates) == 2 @staticmethod def test_get_or_update_rate_by_date__today_before_cron_update_no_yesterday_rates( dao_exchange_rate_mock, dao_provider_mock, currency_layer_mock, grandtrunk_mock, base_currency, currencies, logger, ): """ Get all rates by date. Case: 2 providers, rate of provider 'currency_layer' is in DB, rate of provider 'grandtrunk' miss, the date is today, yesterday's rates aren't in DB. Try to get rate for missing provider from yesterday, fail and request from API, store to DB. Finally return list of all rates of the day (all provider rates). :param dao_exchange_rate_mock: Mock of gold_digger.database.DaoExchangeRate :param dao_provider_mock: Mock of gold_digger.database.DaoProvider :param currency_layer_mock: Mock of gold_digger.data_providers.CurrencyLayer :param grandtrunk_mock: Mock of gold_digger.data_providers.GrandTrunk :type base_currency: str :type currencies: set[str] :type logger: gold_digger.utils.ContextLogger """ today = date.today() yesterday = today - timedelta(1) exchange_rate_manager = ExchangeRateManager( dao_exchange_rate_mock, dao_provider_mock, [currency_layer_mock, grandtrunk_mock], base_currency, currencies, ) grandtrunk_mock.get_by_date.return_value = Decimal(0.75) dao_exchange_rate_mock.get_rates_by_date_currency.return_value = [ ExchangeRate(provider=Provider(name=CurrencyLayer.name), date=today, currency="EUR", rate=Decimal(0.77)), ] dao_exchange_rate_mock.get_rate_by_date_currency_provider.return_value = [] dao_exchange_rate_mock.insert_new_rate.return_value = [ ExchangeRate(provider=Provider(name=GrandTrunk.name), date=today, currency="EUR", rate=Decimal(0.75)), ] exchange_rates = exchange_rate_manager.get_or_update_rate_by_date(today, currency="EUR", logger=logger) insert_new_rate_args, _ = dao_exchange_rate_mock.insert_new_rate.call_args assert dao_exchange_rate_mock.insert_new_rate.call_count == 1 assert insert_new_rate_args[1].name == GrandTrunk.name assert dao_exchange_rate_mock.get_rate_by_date_currency_provider.call_count == 1 assert dao_exchange_rate_mock.get_rate_by_date_currency_provider.call_args[0] == (yesterday, "EUR", GrandTrunk.name) assert len(exchange_rates) == 2 @staticmethod def test_get_or_update_rate_by_date__no_api_requests_for_historical_data_on_limited_providers( dao_exchange_rate_mock, dao_provider_mock, fixer_mock, currency_layer_mock, grandtrunk_mock, base_currency, currencies, logger, ): """ In case historical data are requested and they are not in database we don't want to request API if the provider has request limit. :param dao_exchange_rate_mock: Mock of gold_digger.database.DaoExchangeRate :param dao_provider_mock: Mock of gold_digger.database.DaoProvider :param fixer_mock: Mock of gold_digger.data_providers.Fixer :param currency_layer_mock: Mock of gold_digger.data_providers.CurrencyLayer :param grandtrunk_mock: Mock of gold_digger.data_providers.GrandTrunk :type base_currency: str :type currencies: set[str] :type logger: gold_digger.utils.ContextLogger """ yesterday = date.today() - timedelta(1) # yesterday's rates are treated as historical rates exchange_rate_manager = ExchangeRateManager( dao_exchange_rate_mock, dao_provider_mock, [fixer_mock, currency_layer_mock, grandtrunk_mock], base_currency, currencies, ) dao_exchange_rate_mock.get_rates_by_date_currency.return_value = [] exchange_rates = exchange_rate_manager.get_or_update_rate_by_date(yesterday, currency="EUR", logger=logger) assert dao_exchange_rate_mock.get_rates_by_date_currency.call_count == 1 assert dao_exchange_rate_mock.get_rate_by_date_currency_provider.call_count == 0 assert grandtrunk_mock.get_by_date.call_count == 1 assert currency_layer_mock.get_by_date.call_count == 0 assert fixer_mock.get_by_date.call_count == 0 assert len(exchange_rates) == 1 class TestGetExchangeRateByDate: @staticmethod def test_get_exchange_rate_by_date(dao_exchange_rate_mock, dao_provider_mock, base_currency, logger): """ :param dao_exchange_rate_mock: Mock of gold_digger.database.DaoExchangeRate :param dao_provider_mock: Mock of gold_digger.database.DaoProvider :type base_currency: str :type logger: gold_digger.utils.ContextLogger """ _date = date(2016, 2, 17) exchange_rate_manager = ExchangeRateManager(dao_exchange_rate_mock, dao_provider_mock, [], base_currency, set()) def _get_rates_by_date_currency(_, currency): """ :type currency: str :rtype: list[gold_digger.database.db_model.ExchangeRate] """ return { "EUR": [ExchangeRate(id=1, currency="EUR", rate=Decimal(0.89), provider=Provider(name=CurrencyLayer.name))], "CZK": [ExchangeRate(id=2, currency="CZK", rate=Decimal(24.20), provider=Provider(name=CurrencyLayer.name))], }.get(currency) dao_exchange_rate_mock.get_rates_by_date_currency.side_effect = _get_rates_by_date_currency exchange_rate = exchange_rate_manager.get_exchange_rate_by_date(_date, "EUR", "CZK", logger) assert exchange_rate == Decimal(24.20) / Decimal(0.89) class TestGetAverageExchangeRateByDates: @staticmethod def test_get_average_exchange_rate_by_dates(dao_exchange_rate_mock, dao_provider_mock, base_currency, logger): """ Get average exchange rate within specified period. Case: 10 days period, 10 'EUR' rates but only 9 'CZK' rates in DB, 1 provider exchange rate is computed as average rate within the period and 'warning' is logged for missing 'CZK' rate :param dao_exchange_rate_mock: Mock of gold_digger.database.DaoExchangeRate :param dao_provider_mock: Mock of gold_digger.database.DaoProvider :type base_currency: str :type logger: gold_digger.utils.ContextLogger """ _start_date = date(2016, 2, 7) _end_date = date(2016, 2, 17) logger_mock = Mock(logger) exchange_rate_manager = ExchangeRateManager(dao_exchange_rate_mock, dao_provider_mock, [], base_currency, set()) def _get_sum_of_rates_in_period(_, __, currency): return { "EUR": [[Provider(name=CurrencyLayer.name), 11, Decimal(8.9)]], "CZK": [[Provider(name=CurrencyLayer.name), 9, Decimal(217.8)]], }.get(currency) dao_exchange_rate_mock.get_sum_of_rates_in_period.side_effect = _get_sum_of_rates_in_period exchange_rate = exchange_rate_manager.get_average_exchange_rate_by_dates(_start_date, _end_date, "EUR", "CZK", logger_mock) eur_average = Decimal(8.9) / 11 czk_average = Decimal(217.8) / 9 assert exchange_rate == czk_average * (1 / eur_average) assert logger_mock.warning.call_count == 1 class TestPickTheBest: @staticmethod def test_pick_the_best__pick_rate_from_any_provider_if_rates_are_same(): """ Picked exchange rate is the same as the equal candidates. """ best = ExchangeRateManager.pick_the_best([Decimal(0.5), Decimal(0.5), Decimal(0.5)]) assert best == 0.5 @staticmethod def test_pick_the_best__pick_middle_rate_if_it_exists(): """ Picked exchange rate is the middle of the unique candidates. """ best = ExchangeRateManager.pick_the_best([Decimal(0.0), Decimal(0.5), Decimal(1.0)]) assert best == 0.5 @staticmethod def test_pick_the_best__pick_middle_rate_if_it_exists2(): """ Picked exchange rate is the middle of the unique candidates. """ best = ExchangeRateManager.pick_the_best([Decimal(1.5), Decimal(0.5), Decimal(1.0)]) assert best == 1.0 @staticmethod def test_pick_the_best__pick_rate_from_pair_of_same_rates_by_order_of_providers(): """ Picked exchange rate is the most common of the candidates. """ best = ExchangeRateManager.pick_the_best([Decimal(0.0), Decimal(0.7), Decimal(0.7)]) assert best == 0.7 @staticmethod def test_pick_the_best__pick_rate_from_most_similar_pair_of_rates_by_order_of_providers(): """ Picked exchange rate is the one most similar to the other candidates. """ best = ExchangeRateManager.pick_the_best([Decimal(0.02), Decimal(0.72), Decimal(0.74)]) assert best == 0.72 class TestGetExchangeRateInIntervalsByDate: @staticmethod def test_get_exchange_rate_in_intervals_by_date(dao_exchange_rate_mock, dao_provider_mock, base_currency, currencies, logger): """ :param dao_exchange_rate_mock: Mock of gold_digger.database.DaoExchangeRate :param dao_provider_mock: Mock of gold_digger.database.DaoProvider :type base_currency: str :type currencies: set[str] :type logger: gold_digger.utils.ContextLogger """ date_of_exchange_ = date(2020, 11, 30) start_date_6_days_ago = date_of_exchange_ - timedelta(days=6) start_date_30_days_ago = date_of_exchange_ - timedelta(days=30) provider = Provider(name=CurrencyLayer.name) rates = { "EUR": [ExchangeRate(provider=provider, date=date_of_exchange_, currency="EUR", rate=Decimal(10.0))], "CZK": [ExchangeRate(provider=provider, date=date_of_exchange_, currency="CZK", rate=Decimal(15.0))], } sum_of_rates = { "EUR": { date_of_exchange_: [(provider, 1, Decimal(10.0))], start_date_6_days_ago: [(provider, 7, Decimal(70.0))], start_date_30_days_ago: [(provider, 31, Decimal(310.0))], }, "CZK": { date_of_exchange_: [(provider, 1, Decimal(15.0))], start_date_6_days_ago: [(provider, 7, Decimal(140.0))], start_date_30_days_ago: [(provider, 31, Decimal(775.0))], }, } dao_exchange_rate_mock.get_sum_of_rates_in_period.side_effect = lambda start_date, _, currency: sum_of_rates[currency][start_date] dao_exchange_rate_mock.get_rates_by_date_currency.side_effect = lambda _, currency: rates[currency] exchange_rate_manager = ExchangeRateManager(dao_exchange_rate_mock, dao_provider_mock, [provider], base_currency, currencies) exchange_rate_in_intervals = exchange_rate_manager.get_exchange_rate_in_intervals_by_date(date_of_exchange_, "EUR", "CZK", logger) assert exchange_rate_in_intervals == [ { "interval": "daily", "exchange_rate": "1.5", }, { "interval": "weekly", "exchange_rate": "2.0", }, { "interval": "monthly", "exchange_rate": "2.5", }, ]
'''This module holds the base Harvester class and all its subclassess.''' import json import collections from radon.raw import analyze from radon.metrics import mi_visit, mi_rank from radon.complexity import (cc_visit, sorted_results, cc_rank, add_inner_blocks) from radon.cli.colors import RANKS_COLORS, MI_RANKS, RESET from radon.cli.tools import (iter_filenames, _open, cc_to_dict, dict_to_xml, dict_to_codeclimate_issues, cc_to_terminal, raw_to_dict) class Harvester(object): '''Base class defining the interface of a Harvester object. A Harvester has the following lifecycle: 1. **Initialization**: `h = Harvester(paths, config)` 2. **Execution**: `r = h.results`. `results` holds an iterable object. The first time `results` is accessed, `h.run()` is called. This method should not be subclassed. Instead, the :meth:`gobble` method should be implemented. 3. **Reporting**: the methods *as_json* and *as_xml* return a string with the corrisponding format. The method *to_terminal* is a generator that yields the lines to be printed in the terminal. This class is meant to be subclasses and cannot be used directly, since the methods :meth:`gobble`, :meth:`as_xml` and :meth:`to_terminal` are not implemented. ''' def __init__(self, paths, config): '''Initialize the Harvester. *paths* is a list of paths to analyze. *config* is a :class:`~radon.cli.Config` object holding the configuration values specific to the Harvester. ''' self.paths = paths self.config = config self._results = [] def _iter_filenames(self): '''A wrapper around :func:`~radon.cli.tools.iter_filenames`.''' return iter_filenames(self.paths, self.config.exclude, self.config.ignore) def gobble(self, fobj): '''Subclasses must implement this method to define behavior. This method is called for every file to analyze. *fobj* is the file object. This method should return the results from the analysis, preferably a dictionary. ''' raise NotImplementedError def run(self): '''Start the analysis. For every file, this method calls the :meth:`gobble` method. Results are yielded as tuple: ``(filename, analysis_results)``. ''' for name in self._iter_filenames(): with _open(name) as fobj: try: yield (name, self.gobble(fobj)) except Exception as e: yield (name, {'error': str(e)}) @property def results(self): '''This property holds the results of the analysis. The first time it is accessed, an iterator is returned. Its elements are cached into a list as it is iterated over. Therefore, if `results` is accessed multiple times after the first one, a list will be returned. ''' def caching_iterator(it, r): '''An iterator that caches another iterator.''' for t in it: yield t r.append(t) if self._results: return self._results return caching_iterator(self.run(), self._results) def as_json(self): '''Format the results as JSON.''' return json.dumps(dict(self.results)) def as_xml(self): '''Format the results as XML.''' raise NotImplementedError def as_codeclimate_issues(self): '''Format the results as Code Climate issues.''' raise NotImplementedError def to_terminal(self): '''Yields tuples representing lines to be printed to a terminal. The tuples have the following format: ``(line, args, kwargs)``. The line is then formatted with `line.format(*args, **kwargs)`. ''' raise NotImplementedError class CCHarvester(Harvester): '''A class that analyzes Python modules' Cyclomatic Complexity.''' def gobble(self, fobj): '''Analyze the content of the file object.''' r = cc_visit(fobj.read(), no_assert=self.config.no_assert) if self.config.show_closures: r = add_inner_blocks(r) return sorted_results(r, order=self.config.order) def _to_dicts(self): '''Format the results as a dictionary of dictionaries.''' result = {} for key, data in self.results: if 'error' in data: result[key] = data continue values = [v for v in map(cc_to_dict, data) if self.config.min <= v['rank'] <= self.config.max] if values: result[key] = values return result def as_json(self): '''Format the results as JSON.''' return json.dumps(self._to_dicts()) def as_xml(self): '''Format the results as XML. This is meant to be compatible with Jenkin's CCM plugin. Therefore not all the fields are kept. ''' return dict_to_xml(self._to_dicts()) def as_codeclimate_issues(self): '''Format the result as Code Climate issues.''' return dict_to_codeclimate_issues(self._to_dicts(), self.config.min) def to_terminal(self): '''Yield lines to be printed in a terminal.''' average_cc = .0 analyzed = 0 for name, blocks in self.results: if 'error' in blocks: yield name, (blocks['error'],), {'error': True} continue res, cc, n = cc_to_terminal(blocks, self.config.show_complexity, self.config.min, self.config.max, self.config.total_average) average_cc += cc analyzed += n if res: yield name, (), {} yield res, (), {'indent': 1} if (self.config.average or self.config.total_average) and analyzed: cc = average_cc / analyzed ranked_cc = cc_rank(cc) yield ('\n{0} blocks (classes, functions, methods) analyzed.', (analyzed,), {}) yield ('Average complexity: {0}{1} ({2}){3}', (RANKS_COLORS[ranked_cc], ranked_cc, cc, RESET), {}) class RawHarvester(Harvester): '''A class that analyzes Python modules' raw metrics.''' headers = ['LOC', 'LLOC', 'SLOC', 'Comments', 'Single comments', 'Multi', 'Blank'] def gobble(self, fobj): '''Analyze the content of the file object.''' return raw_to_dict(analyze(fobj.read())) def as_xml(self): '''Placeholder method. Currently not implemented.''' raise NotImplementedError('Cannot export results as XML') def to_terminal(self): '''Yield lines to be printed to a terminal.''' sum_metrics = collections.defaultdict(int) for path, mod in self.results: if 'error' in mod: yield path, (mod['error'],), {'error': True} continue yield path, (), {} for header in self.headers: value = mod[header.lower().replace(' ', '_')] yield '{0}: {1}', (header, value), {'indent': 1} sum_metrics[header] += value loc, comments = mod['loc'], mod['comments'] yield '- Comment Stats', (), {'indent': 1} yield ('(C % L): {0:.0%}', (comments / (float(loc) or 1),), {'indent': 2}) yield ('(C % S): {0:.0%}', (comments / (float(mod['sloc']) or 1),), {'indent': 2}) yield ('(C + M % L): {0:.0%}', ((comments + mod['multi']) / (float(loc) or 1),), {'indent': 2}) if self.config.summary: yield '** Total **', (), {} for header in self.headers: yield '{0}: {1}', (header, sum_metrics[header]), {'indent': 1} class MIHarvester(Harvester): '''A class that analyzes Python modules' Maintainability Index.''' def gobble(self, fobj): '''Analyze the content of the file object.''' mi = mi_visit(fobj.read(), self.config.multi) rank = mi_rank(mi) return {'mi': mi, 'rank': rank} @property def filtered_results(self): '''Filter results with respect with their rank.''' for key, value in self.results: if ('error' in value or self.config.min <= value['rank'] <= self.config.max): yield (key, value) def as_json(self): '''Format the results as JSON.''' return json.dumps(dict(self.filtered_results)) def as_xml(self): '''Placeholder method. Currently not implemented.''' raise NotImplementedError('Cannot export results as XML') def to_terminal(self): '''Yield lines to be printed to a terminal.''' for name, mi in self.filtered_results: if 'error' in mi: yield name, (mi['error'],), {'error': True} continue rank = mi['rank'] color = MI_RANKS[rank] to_show = '' if self.config.show: to_show = ' ({0:.2f})'.format(mi['mi']) yield '{0} - {1}{2}{3}{4}', (name, color, rank, to_show, RESET), {}
""" Copyright (c) 2014, Myles Braithwaite <me@mylesbraithwaite.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Monkey in your Soul nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import os import uuid import glob import datetime import textwrap import plistlib from collections import OrderedDict import markdown from pytz import timezone from tzlocal import get_localzone class Location(object): """Location data in an entry.""" def __init__(self, location_data): self.location_data = location_data def __repr__(self): return "%s.%s(%s, %s)" % ( self.__module__, self.__class__.__name__, self.latitude, self.longitude) def __str__(self): if self.place_name: return self.place_name else: return "%s, %s" % (self.latitude, self.longitude) @property def latitude(self): return self.location_data.get('Latitude', None) @property def longitude(self): return self.location_data.get('Longitude', None) @property def place_name(self): return self.location_data.get('Place Name', None) @property def foursquare_id(self): return self.location_data.get('Foursquare ID', None) @property def locality(self): return self.location_data.get('Locality', None) @property def administrative_area(self): return self.location_data.get('Administrative Area', None) @property def country(self): return self.location_data.get('Country', None) class Weather(object): """Location data in an entry.""" def __init__(self, weather_data): self.weather_data = weather_data def __repr__(self): return "%s.%s(%s, %s)" % ( self.__module__, self.__class__.__name__, self.description, self.celsius) def __str__(self): return "%s, %s" % (self.description, self.celsius) @property def celsius(self): return self.weather_data.get('Celsius', None) @property def fahrenheit(self): return self.weather_data.get('Fahrenheit', None) @property def description(self): return self.weather_data.get('Description', None) @property def icon_name(self): return self.weather_data.get('IconName', None) @property def pressure_mb(self): return self.weather_data.get('Pressure MB', None) @property def relative_humidity(self): return self.weather_data.get('Relative Humidity', None) @property def service(self): return self.weather_data.get('Service', None) @property def visibility_km(self): return self.weather_data.get('Visibility KM', None) @property def wind_bearing(self): return self.weather_data.get('Wind Bearing', None) @property def wind_speed_kph(self): return self.weather_data.get('Wind Speed KPH', None) class Entry(object): """A Journal Entry.""" def __init__(self, journal_dir, filename=None): self.entry_data = {} self.journal_dir = journal_dir self.filename = filename if self.filename: if not self.filename.endswith('.doentry'): self.filename = "%s.doentry" % filename self.load_file() def __repr__(self): if self.uuid: return "%s.%s(%s)" % ( self.__module__, self.__class__.__name__, self.uuid) else: return "%s.%s" % (self.__module__, self.__class__.__name__) def __str__(self): if self.text: return textwrap.wrap(self.text)[0] def load_file(self): entry_path = os.path.join(self.journal_dir, 'entries', self.filename) self.entry_data = plistlib.readPlist(entry_path) def save_file(self): if not self.text: raise Exception if self.filename: entry_path = os.path.join(self.journal_dir, 'entries', self.filename) else: _uuid = str(uuid.uuid4()).replace('-', '').upper() self.filename = "%s.doentry" % _uuid self.entry_data['UUID'] = _uuid self.entry_data['Creation Date'] = datetime.datetime.now() self.entry_data['Time Zone'] = str(get_localzone()) self.entry_data['Starred'] = False entry_path = os.path.join(self.journal_dir, 'entries', self.filename) plistlib.writePlist(self.entry_data, entry_path) self.load_file() @property def uuid(self): return self.entry_data['UUID'] @property def text(self): return self.entry_data['Entry Text'] @text.setter def text(self, x): self.entry_data['Entry Text'] = str(x) @property def text_html(self): return markdown.markdown(self.text, ['markdown.extensions.extra']) @property def tags(self): return self.entry_data.get('Tags', []) @tags.setter def tags(self, x): self.entry_data['Tags'] = x @property def photo(self): photos = glob.glob(os.path.join(self.journal_dir, "photos", "%s.*" % self.uuid)) if photos: return photos[0] else: return None @property def creation_date(self): if self.time_zone: return self.time_zone.localize(self.entry_data['Creation Date']) else: return self.entry_data['Creation Date'] @property def starred(self): return self.entry_data['Starred'] @starred.setter def starred(self, x): self.entry_data['Starred'] = bool(x) @property def activity(self): return self.entry_date['Activity'] @property def location(self): if self.entry_data.get('Location', None): return Location(self.entry_data.get('Location')) else: return None @property def weather(self): if self.entry_data.get('Weather', None): return Weather(self.entry_data.get('Weather')) else: return None @property def time_zone(self): if self.entry_data.get('Time Zone', None): return timezone(self.entry_data.get('Time Zone', None)) else: return get_localzone() class Journal(object): """A Day One Journal.""" def __init__(self, journal_dir): self.journal_dir = journal_dir self.entries_dir = os.path.join(journal_dir, "entries") self.photos_dir = os.path.join(journal_dir, "photos") # if not os.path.exists(self.entries_dir): # os.makedirs(self.entries_dir) # if not os.path.exists(self.photos_dir): # os.makedirs(self.photos_dir) self.journal_name = os.path.basename(self.journal_dir) self.entries = [] self.get_entries() def __repr__(self): return "%s.%s(%s)" % (self.__module__, self.__class__.__name__, self.journal_name) def get_entries(self): entries = glob.glob(os.path.join(self.entries_dir, "*.doentry")) for entry in entries: filename = os.path.basename(entry) self.entries += [Entry(self.journal_dir, filename)] self.entries.sort(key=lambda e: e.creation_date, reverse=True) def filter_by_date(self, date): def f(e): return e.creation_date.date() == date return filter(f, self.entries) def filter_between_dates(self, start_date, end_date): def f(e): return ((e.creation_date.date() >= start_date) and (e.creation_date.date() <= end_date)) return filter(f, self.entries)
"""AirTouch 4 component to control of AirTouch 4 Climate Devices.""" from __future__ import annotations import logging from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( FAN_AUTO, FAN_DIFFUSE, FAN_FOCUS, FAN_HIGH, FAN_LOW, FAN_MEDIUM, HVAC_MODE_AUTO, HVAC_MODE_COOL, HVAC_MODE_DRY, HVAC_MODE_FAN_ONLY, HVAC_MODE_HEAT, HVAC_MODE_OFF, SUPPORT_FAN_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_FAN_MODE AT_TO_HA_STATE = { "Heat": HVAC_MODE_HEAT, "Cool": HVAC_MODE_COOL, "AutoHeat": HVAC_MODE_AUTO, # airtouch reports either autoheat or autocool "AutoCool": HVAC_MODE_AUTO, "Auto": HVAC_MODE_AUTO, "Dry": HVAC_MODE_DRY, "Fan": HVAC_MODE_FAN_ONLY, } HA_STATE_TO_AT = { HVAC_MODE_HEAT: "Heat", HVAC_MODE_COOL: "Cool", HVAC_MODE_AUTO: "Auto", HVAC_MODE_DRY: "Dry", HVAC_MODE_FAN_ONLY: "Fan", HVAC_MODE_OFF: "Off", } AT_TO_HA_FAN_SPEED = { "Quiet": FAN_DIFFUSE, "Low": FAN_LOW, "Medium": FAN_MEDIUM, "High": FAN_HIGH, "Powerful": FAN_FOCUS, "Auto": FAN_AUTO, "Turbo": "turbo", } AT_GROUP_MODES = [HVAC_MODE_OFF, HVAC_MODE_FAN_ONLY] HA_FAN_SPEED_TO_AT = {value: key for key, value in AT_TO_HA_FAN_SPEED.items()} _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the Airtouch 4.""" coordinator = hass.data[DOMAIN][config_entry.entry_id] info = coordinator.data entities: list[ClimateEntity] = [ AirtouchGroup(coordinator, group["group_number"], info) for group in info["groups"] ] entities.extend( AirtouchAC(coordinator, ac["ac_number"], info) for ac in info["acs"] ) _LOGGER.debug(" Found entities %s", entities) async_add_entities(entities) class AirtouchAC(CoordinatorEntity, ClimateEntity): """Representation of an AirTouch 4 ac.""" _attr_supported_features = SUPPORT_TARGET_TEMPERATURE | SUPPORT_FAN_MODE _attr_temperature_unit = TEMP_CELSIUS def __init__(self, coordinator, ac_number, info): """Initialize the climate device.""" super().__init__(coordinator) self._ac_number = ac_number self._airtouch = coordinator.airtouch self._info = info self._unit = self._airtouch.GetAcs()[self._ac_number] @callback def _handle_coordinator_update(self): self._unit = self._airtouch.GetAcs()[self._ac_number] return super()._handle_coordinator_update() @property def device_info(self) -> DeviceInfo: """Return device info for this device.""" return DeviceInfo( identifiers={(DOMAIN, self.unique_id)}, name=self.name, manufacturer="Airtouch", model="Airtouch 4", ) @property def unique_id(self): """Return unique ID for this device.""" return f"ac_{self._ac_number}" @property def current_temperature(self): """Return the current temperature.""" return self._unit.Temperature @property def name(self): """Return the name of the climate device.""" return f"AC {self._ac_number}" @property def fan_mode(self): """Return fan mode of the AC this group belongs to.""" return AT_TO_HA_FAN_SPEED[self._airtouch.acs[self._ac_number].AcFanSpeed] @property def fan_modes(self): """Return the list of available fan modes.""" airtouch_fan_speeds = self._airtouch.GetSupportedFanSpeedsForAc(self._ac_number) return [AT_TO_HA_FAN_SPEED[speed] for speed in airtouch_fan_speeds] @property def hvac_mode(self): """Return hvac target hvac state.""" is_off = self._unit.PowerState == "Off" if is_off: return HVAC_MODE_OFF return AT_TO_HA_STATE[self._airtouch.acs[self._ac_number].AcMode] @property def hvac_modes(self): """Return the list of available operation modes.""" airtouch_modes = self._airtouch.GetSupportedCoolingModesForAc(self._ac_number) modes = [AT_TO_HA_STATE[mode] for mode in airtouch_modes] modes.append(HVAC_MODE_OFF) return modes async def async_set_hvac_mode(self, hvac_mode): """Set new operation mode.""" if hvac_mode not in HA_STATE_TO_AT: raise ValueError(f"Unsupported HVAC mode: {hvac_mode}") if hvac_mode == HVAC_MODE_OFF: return await self.async_turn_off() await self._airtouch.SetCoolingModeForAc( self._ac_number, HA_STATE_TO_AT[hvac_mode] ) # in case it isn't already, unless the HVAC mode was off, then the ac should be on await self.async_turn_on() self._unit = self._airtouch.GetAcs()[self._ac_number] _LOGGER.debug("Setting operation mode of %s to %s", self._ac_number, hvac_mode) self.async_write_ha_state() async def async_set_fan_mode(self, fan_mode): """Set new fan mode.""" if fan_mode not in self.fan_modes: raise ValueError(f"Unsupported fan mode: {fan_mode}") _LOGGER.debug("Setting fan mode of %s to %s", self._ac_number, fan_mode) await self._airtouch.SetFanSpeedForAc( self._ac_number, HA_FAN_SPEED_TO_AT[fan_mode] ) self._unit = self._airtouch.GetAcs()[self._ac_number] self.async_write_ha_state() async def async_turn_on(self): """Turn on.""" _LOGGER.debug("Turning %s on", self.unique_id) # in case ac is not on. Airtouch turns itself off if no groups are turned on # (even if groups turned back on) await self._airtouch.TurnAcOn(self._ac_number) async def async_turn_off(self): """Turn off.""" _LOGGER.debug("Turning %s off", self.unique_id) await self._airtouch.TurnAcOff(self._ac_number) self.async_write_ha_state() class AirtouchGroup(CoordinatorEntity, ClimateEntity): """Representation of an AirTouch 4 group.""" _attr_supported_features = SUPPORT_TARGET_TEMPERATURE _attr_temperature_unit = TEMP_CELSIUS _attr_hvac_modes = AT_GROUP_MODES def __init__(self, coordinator, group_number, info): """Initialize the climate device.""" super().__init__(coordinator) self._group_number = group_number self._airtouch = coordinator.airtouch self._info = info self._unit = self._airtouch.GetGroupByGroupNumber(self._group_number) @callback def _handle_coordinator_update(self): self._unit = self._airtouch.GetGroupByGroupNumber(self._group_number) return super()._handle_coordinator_update() @property def device_info(self) -> DeviceInfo: """Return device info for this device.""" return DeviceInfo( identifiers={(DOMAIN, self.unique_id)}, manufacturer="Airtouch", model="Airtouch 4", name=self.name, ) @property def unique_id(self): """Return unique ID for this device.""" return self._group_number @property def min_temp(self): """Return Minimum Temperature for AC of this group.""" return self._airtouch.acs[self._unit.BelongsToAc].MinSetpoint @property def max_temp(self): """Return Max Temperature for AC of this group.""" return self._airtouch.acs[self._unit.BelongsToAc].MaxSetpoint @property def name(self): """Return the name of the climate device.""" return self._unit.GroupName @property def current_temperature(self): """Return the current temperature.""" return self._unit.Temperature @property def target_temperature(self): """Return the temperature we are trying to reach.""" return self._unit.TargetSetpoint @property def hvac_mode(self): """Return hvac target hvac state.""" # there are other power states that aren't 'on' but still count as on (eg. 'Turbo') is_off = self._unit.PowerState == "Off" if is_off: return HVAC_MODE_OFF return HVAC_MODE_FAN_ONLY async def async_set_hvac_mode(self, hvac_mode): """Set new operation mode.""" if hvac_mode not in HA_STATE_TO_AT: raise ValueError(f"Unsupported HVAC mode: {hvac_mode}") if hvac_mode == HVAC_MODE_OFF: return await self.async_turn_off() if self.hvac_mode == HVAC_MODE_OFF: await self.async_turn_on() self._unit = self._airtouch.GetGroups()[self._group_number] _LOGGER.debug( "Setting operation mode of %s to %s", self._group_number, hvac_mode ) self.async_write_ha_state() @property def fan_mode(self): """Return fan mode of the AC this group belongs to.""" return AT_TO_HA_FAN_SPEED[self._airtouch.acs[self._unit.BelongsToAc].AcFanSpeed] @property def fan_modes(self): """Return the list of available fan modes.""" airtouch_fan_speeds = self._airtouch.GetSupportedFanSpeedsByGroup( self._group_number ) return [AT_TO_HA_FAN_SPEED[speed] for speed in airtouch_fan_speeds] async def async_set_temperature(self, **kwargs): """Set new target temperatures.""" temp = kwargs.get(ATTR_TEMPERATURE) _LOGGER.debug("Setting temp of %s to %s", self._group_number, str(temp)) self._unit = await self._airtouch.SetGroupToTemperature( self._group_number, int(temp) ) self.async_write_ha_state() async def async_set_fan_mode(self, fan_mode): """Set new fan mode.""" if fan_mode not in self.fan_modes: raise ValueError(f"Unsupported fan mode: {fan_mode}") _LOGGER.debug("Setting fan mode of %s to %s", self._group_number, fan_mode) self._unit = await self._airtouch.SetFanSpeedByGroup( self._group_number, HA_FAN_SPEED_TO_AT[fan_mode] ) self.async_write_ha_state() async def async_turn_on(self): """Turn on.""" _LOGGER.debug("Turning %s on", self.unique_id) await self._airtouch.TurnGroupOn(self._group_number) # in case ac is not on. Airtouch turns itself off if no groups are turned on # (even if groups turned back on) await self._airtouch.TurnAcOn( self._airtouch.GetGroupByGroupNumber(self._group_number).BelongsToAc ) # this might cause the ac object to be wrong, so force the shared data # store to update await self.coordinator.async_request_refresh() self.async_write_ha_state() async def async_turn_off(self): """Turn off.""" _LOGGER.debug("Turning %s off", self.unique_id) await self._airtouch.TurnGroupOff(self._group_number) # this will cause the ac object to be wrong # (ac turns off automatically if no groups are running) # so force the shared data store to update await self.coordinator.async_request_refresh() self.async_write_ha_state()
# Copyright (C) 2013 eNovance SAS <licensing@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 netaddr from oslo_log import log as logging from oslo_utils import uuidutils import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy import sql from neutron.api.rpc.agentnotifiers import metering_rpc_agent_api from neutron.api.v2 import attributes as attr from neutron.common import constants from neutron.db import common_db_mixin as base_db from neutron.db import l3_db from neutron.db import model_base from neutron.db import models_v2 from neutron.extensions import metering LOG = logging.getLogger(__name__) class MeteringLabelRule(model_base.BASEV2, models_v2.HasId): direction = sa.Column(sa.Enum('ingress', 'egress', name='meteringlabels_direction')) remote_ip_prefix = sa.Column(sa.String(64)) metering_label_id = sa.Column(sa.String(36), sa.ForeignKey("meteringlabels.id", ondelete="CASCADE"), nullable=False) excluded = sa.Column(sa.Boolean, default=False, server_default=sql.false()) class MeteringLabel(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant): name = sa.Column(sa.String(attr.NAME_MAX_LEN)) description = sa.Column(sa.String(attr.LONG_DESCRIPTION_MAX_LEN)) rules = orm.relationship(MeteringLabelRule, backref="label", cascade="delete", lazy="joined") routers = orm.relationship( l3_db.Router, primaryjoin="MeteringLabel.tenant_id==Router.tenant_id", foreign_keys='MeteringLabel.tenant_id', uselist=True) shared = sa.Column(sa.Boolean, default=False, server_default=sql.false()) class MeteringDbMixin(metering.MeteringPluginBase, base_db.CommonDbMixin): def __init__(self): self.meter_rpc = metering_rpc_agent_api.MeteringAgentNotifyAPI() def _make_metering_label_dict(self, metering_label, fields=None): res = {'id': metering_label['id'], 'name': metering_label['name'], 'description': metering_label['description'], 'shared': metering_label['shared'], 'tenant_id': metering_label['tenant_id']} return self._fields(res, fields) def create_metering_label(self, context, metering_label): m = metering_label['metering_label'] tenant_id = self._get_tenant_id_for_create(context, m) with context.session.begin(subtransactions=True): metering_db = MeteringLabel(id=uuidutils.generate_uuid(), description=m['description'], tenant_id=tenant_id, name=m['name'], shared=m['shared']) context.session.add(metering_db) return self._make_metering_label_dict(metering_db) def delete_metering_label(self, context, label_id): with context.session.begin(subtransactions=True): try: label = self._get_by_id(context, MeteringLabel, label_id) except orm.exc.NoResultFound: raise metering.MeteringLabelNotFound(label_id=label_id) context.session.delete(label) def get_metering_label(self, context, label_id, fields=None): try: metering_label = self._get_by_id(context, MeteringLabel, label_id) except orm.exc.NoResultFound: raise metering.MeteringLabelNotFound(label_id=label_id) return self._make_metering_label_dict(metering_label, fields) def get_metering_labels(self, context, filters=None, fields=None, sorts=None, limit=None, marker=None, page_reverse=False): marker_obj = self._get_marker_obj(context, 'metering_labels', limit, marker) return self._get_collection(context, MeteringLabel, self._make_metering_label_dict, filters=filters, fields=fields, sorts=sorts, limit=limit, marker_obj=marker_obj, page_reverse=page_reverse) def _make_metering_label_rule_dict(self, metering_label_rule, fields=None): res = {'id': metering_label_rule['id'], 'metering_label_id': metering_label_rule['metering_label_id'], 'direction': metering_label_rule['direction'], 'remote_ip_prefix': metering_label_rule['remote_ip_prefix'], 'excluded': metering_label_rule['excluded']} return self._fields(res, fields) def get_metering_label_rules(self, context, filters=None, fields=None, sorts=None, limit=None, marker=None, page_reverse=False): marker_obj = self._get_marker_obj(context, 'metering_label_rules', limit, marker) return self._get_collection(context, MeteringLabelRule, self._make_metering_label_rule_dict, filters=filters, fields=fields, sorts=sorts, limit=limit, marker_obj=marker_obj, page_reverse=page_reverse) def get_metering_label_rule(self, context, rule_id, fields=None): try: metering_label_rule = self._get_by_id(context, MeteringLabelRule, rule_id) except orm.exc.NoResultFound: raise metering.MeteringLabelRuleNotFound(rule_id=rule_id) return self._make_metering_label_rule_dict(metering_label_rule, fields) def _validate_cidr(self, context, label_id, remote_ip_prefix, direction, excluded): r_ips = self.get_metering_label_rules(context, filters={'metering_label_id': [label_id], 'direction': [direction], 'excluded': [excluded]}, fields=['remote_ip_prefix']) cidrs = [r['remote_ip_prefix'] for r in r_ips] new_cidr_ipset = netaddr.IPSet([remote_ip_prefix]) if (netaddr.IPSet(cidrs) & new_cidr_ipset): raise metering.MeteringLabelRuleOverlaps( remote_ip_prefix=remote_ip_prefix) def create_metering_label_rule(self, context, metering_label_rule): m = metering_label_rule['metering_label_rule'] with context.session.begin(subtransactions=True): label_id = m['metering_label_id'] ip_prefix = m['remote_ip_prefix'] direction = m['direction'] excluded = m['excluded'] self._validate_cidr(context, label_id, ip_prefix, direction, excluded) metering_db = MeteringLabelRule(id=uuidutils.generate_uuid(), metering_label_id=label_id, direction=direction, excluded=m['excluded'], remote_ip_prefix=ip_prefix) context.session.add(metering_db) return self._make_metering_label_rule_dict(metering_db) def delete_metering_label_rule(self, context, rule_id): with context.session.begin(subtransactions=True): try: rule = self._get_by_id(context, MeteringLabelRule, rule_id) except orm.exc.NoResultFound: raise metering.MeteringLabelRuleNotFound(rule_id=rule_id) context.session.delete(rule) return self._make_metering_label_rule_dict(rule) def _get_metering_rules_dict(self, metering_label): rules = [] for rule in metering_label.rules: rule_dict = self._make_metering_label_rule_dict(rule) rules.append(rule_dict) return rules def _make_router_dict(self, router): res = {'id': router['id'], 'name': router['name'], 'tenant_id': router['tenant_id'], 'admin_state_up': router['admin_state_up'], 'status': router['status'], 'gw_port_id': router['gw_port_id'], constants.METERING_LABEL_KEY: []} return res def _process_sync_metering_data(self, context, labels): all_routers = None routers_dict = {} for label in labels: if label.shared: if not all_routers: all_routers = self._get_collection_query(context, l3_db.Router) routers = all_routers else: routers = label.routers for router in routers: router_dict = routers_dict.get( router['id'], self._make_router_dict(router)) rules = self._get_metering_rules_dict(label) data = {'id': label['id'], 'rules': rules} router_dict[constants.METERING_LABEL_KEY].append(data) routers_dict[router['id']] = router_dict return list(routers_dict.values()) def get_sync_data_for_rule(self, context, rule): label = context.session.query(MeteringLabel).get( rule['metering_label_id']) if label.shared: routers = self._get_collection_query(context, l3_db.Router) else: routers = label.routers routers_dict = {} for router in routers: router_dict = routers_dict.get(router['id'], self._make_router_dict(router)) data = {'id': label['id'], 'rule': rule} router_dict[constants.METERING_LABEL_KEY].append(data) routers_dict[router['id']] = router_dict return list(routers_dict.values()) def get_sync_data_metering(self, context, label_id=None, router_ids=None): labels = context.session.query(MeteringLabel) if label_id: labels = labels.filter(MeteringLabel.id == label_id) elif router_ids: labels = (labels.join(MeteringLabel.routers). filter(l3_db.Router.id.in_(router_ids))) return self._process_sync_metering_data(context, labels)
import os import signal import sys import imp signal.signal(signal.SIGINT, lambda signal, frame: sys.exit(0)) import argparse import cmdr.action import cmdr.action_file import cmdr.yaml_conversion import cmdr.pyperclip ## http://www.py2exe.org/index.cgi/HowToDetermineIfRunningFromExe def main_is_frozen(): return (hasattr(sys, "frozen") or # new py2exe hasattr(sys, "importers") # old py2exe or imp.is_frozen("__main__")) # tools/freeze def get_main_dir(): if main_is_frozen(): return os.path.realpath(os.path.dirname(sys.executable)) return os.path.realpath(os.path.dirname(sys.argv[0])) ## end of http://www.py2exe.org/index.cgi/HowToDetermineIfRunningFromExe _FILE_PATH = os.path.join(get_main_dir(), "cmdr.yaml") _BACKUP_FILE_PATH = os.path.join(get_main_dir(), "cmdr.yamlbak") def get(args): action = cmdr.action.get(args.name) if action is None: print "Action '{0}' is not available".format(args.name) else: print_actions([action]) def backup_actions(): cmdr.action_file.save_actions(_BACKUP_FILE_PATH) print "Backed up actions to: '{0}'".format(_BACKUP_FILE_PATH) def add(args): print "Adding a new action. A new action can easily be added directly to the yaml file as well." name = none_empty_input("Name: ") if cmdr.action.get(name) is not None: print "Action with the same name already exist. It will be overwritten." description = raw_input("Description: ") statements = [] first_command = none_empty_input("Command: ") statements.append(cmdr.action.Statement(first_command)) printing_help = True while True: if printing_help: print "Enter 'a' to provide automatic answer to the previously entered command" print "Enter 'c' to add another command to this action" print "Enter 'e' to conclude and end this new action" printing_help = False choice = raw_input("[a/c/e]: ").lower() if choice == 'a': answer = raw_input("Answer: ") statements[len(statements) - 1].answers.append(answer) elif choice == 'c': command = none_empty_input("Command: ") statements.append(cmdr.action.Statement(command)) elif choice == 'e': break else: printing_help = True print new_action = cmdr.action.Action(name, statements, description) print "New action created:" print_actions([new_action]) print choice = query_yes_no("Save action '{0}'?".format(new_action.name)).lower() if choice == "yes": backup_actions() cmdr.action.add(new_action) cmdr.action_file.save_actions(_FILE_PATH) print "Action added." def delete(args): action = cmdr.action.get(args.name) if action is None: print "Action '{0}' is not available".format(args.name) return choice = query_yes_no("Delete action '{0}'?".format(args.name)).lower() if choice == "yes": backup_actions() cmdr.action.delete(action) cmdr.action_file.save_actions(_FILE_PATH) print "Action deleted." def none_empty_input(prompt): while True: value = raw_input(prompt) if not value: print "Empty value is not accepted" else: return value def all(args): print_actions(cmdr.action.get_all()) def find(args): print_actions(cmdr.action.find(args.keyword, args.description, args.statement)) def tag(args): print_actions(cmdr.action.find_tag(args.tag)) def execute(args): action = cmdr.action.get(args.name) if action is None: print "Action '{0}' is not available".format(args.name) else: cmdr.action.execute(action) def copy(args): action = cmdr.action.get(args.name) if action is None: print "Action '{0}' is not available".format(args.name) else: if args.verbose: cmdr.pyperclip.setcb(cmdr.yaml_conversion.exp([action])) else: commands = [] for statement in action.statements: commands.append(statement.command) cmdr.pyperclip.setcb(os.linesep.join(commands)) def print_actions(actions): if actions: print cmdr.yaml_conversion.exp(actions) def print_hints(): print ("-- Hint --\n" "* Please use the following format in the yaml file including the whitespaces and the indentations:\n" "{action name}:\n" "- description: {the description} # 1 space after '-'\n" "- statement:\n" " - {statement 1} # 2 spaces for indentation\n" " - {statement 2}\n" " - < {answer for statement 2} # 1 space after '-' and '<'\n") print "* Use yaml scalar when statements contains unintended yaml syntax" print '* Instead of adding action to the file manually, "add" command can be used' ## {{{ http://code.activestate.com/recipes/577058/ (r2) def query_yes_no(question, default="yes"): """Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer is required of the user). The "answer" return value is one of "yes" or "no". """ valid = {"yes": "yes", "y": "yes", "ye": "yes", "no": "no", "n": "no"} if default is None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default) while 1: sys.stdout.write(question + prompt) choice = raw_input().lower() if default is not None and choice == '': return default elif choice in valid.keys(): return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n") ## end of http://code.activestate.com/recipes/577058/ }}} def main(): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(title='actions') parser_get = subparsers.add_parser('get', help='print an action') parser_get.add_argument('name', type=str, help='the name of the action to be printed out') parser_get.set_defaults(func=get) parser_add = subparsers.add_parser('add', help='create a new action') parser_add.set_defaults(func=add) parser_delete = subparsers.add_parser('del', help='delete an action') parser_delete.add_argument('name', type=str, help='the name of the action to be deleted') parser_delete.set_defaults(func=delete) parser_all = subparsers.add_parser('all', help='print all actions') parser_all.set_defaults(func=all) parser_find = subparsers.add_parser('find', help='find actions matched with the keyword specified') parser_find.add_argument('keyword', type=str, help='the keyword to be matched with the actions') parser_find.add_argument('-d', '--description', help="find keyword in actions' description", action='store_true') parser_find.add_argument('-s', '--statement', help="find keyword in actions' statements", action='store_true') parser_find.set_defaults(func=find) parser_tag = subparsers.add_parser('tag', help='find actions tagged with the specified tag') parser_tag.add_argument('tag', type=str, help='the tag name to be searched for') parser_tag.set_defaults(func=tag) parser_execute = subparsers.add_parser('exe', help='execute an action') parser_execute.add_argument('name', type=str, help='the name of the action to be executed') parser_execute.set_defaults(func=execute) parser_copy = subparsers.add_parser('copy', help="copy an action's command to the clipboard") parser_copy.add_argument('name', type=str, help='the name of the action to be copied') parser_copy.add_argument('-v', '--verbose', help="copy all action's details", action='store_true') parser_copy.set_defaults(func=copy) try: cmdr.action_file.load_actions(_FILE_PATH) except cmdr.yaml_conversion.ConversionException as e: print "Error while loading actions:" print e.msg print_hints() sys.exit(1) try: args = parser.parse_args() args.func(args) except KeyboardInterrupt: sys.exit(0) if __name__ == '__main__': main()
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import click from flask_multipass import IdentityInfo from terminaltables import AsciiTable from indico.cli.core import cli_group from indico.core.db import db from indico.modules.auth import Identity from indico.modules.users import User from indico.modules.users.operations import create_user from indico.modules.users.util import search_users from indico.util.console import cformat, prompt_email, prompt_pass @cli_group() def cli(): pass def _print_user_info(user): flags = [] if user.is_admin: flags.append('%{yellow}admin%{reset}') if user.is_blocked: flags.append('%{red}blocked%{reset}') if user.is_deleted: flags.append('%{red!}deleted%{reset}') if user.is_pending: flags.append('%{cyan}pending%{reset}') print() print('User info:') print(f" ID: {user.id}") print(f" First name: {user.first_name}") print(f" Family name: {user.last_name}") print(f" Email: {user.email}") print(f" Affiliation: {user.affiliation}") if flags: print(cformat(" Flags: {}".format(', '.join(flags)))) print() def _safe_lower(s): return (s or '').lower() @cli.command() @click.option('--substring', is_flag=True, help='Whether to require exact matches (default) or do substring matches (slower)') @click.option('--include-deleted', '-D', is_flag=True, help='Include deleted users in the results') @click.option('--include-pending', '-P', is_flag=True, help='Include pending users in the results') @click.option('--include-blocked', '-B', is_flag=True, help='Include blocked users in the results') @click.option('--include-external', '-X', is_flag=True, help='Also include external users (e.g. from LDAP). This is potentially very slow in substring mode') @click.option('--include-system', '-S', is_flag=True, help='Also include the system user') @click.option('--first-name', '-n', help='First name of the user') @click.option('--last-name', '-s', help='Last name of the user') @click.option('--email', '-e', help='Email address of the user') @click.option('--affiliation', '-a', help='Affiliation of the user') def search(substring, include_deleted, include_pending, include_blocked, include_external, include_system, **criteria): """Search users matching some criteria.""" assert set(criteria.keys()) == {'first_name', 'last_name', 'email', 'affiliation'} criteria = {k: v for k, v in criteria.items() if v is not None} res = search_users(exact=(not substring), include_deleted=include_deleted, include_pending=include_pending, include_blocked=include_blocked, external=include_external, allow_system_user=include_system, **criteria) if not res: print(cformat('%{yellow}No results found')) return elif len(res) > 100: click.confirm(f'{len(res)} results found. Show them anyway?', abort=True) users = sorted((u for u in res if isinstance(u, User)), key=lambda x: (x.first_name.lower(), x.last_name.lower(), x.email)) externals = sorted((ii for ii in res if isinstance(ii, IdentityInfo)), key=lambda x: (_safe_lower(x.data.get('first_name')), _safe_lower(x.data.get('last_name')), _safe_lower(x.data['email']))) if users: table_data = [['ID', 'First Name', 'Last Name', 'Email', 'Affiliation']] for user in users: table_data.append([str(user.id), user.first_name, user.last_name, user.email, user.affiliation]) table = AsciiTable(table_data, cformat('%{white!}Users%{reset}')) table.justify_columns[0] = 'right' print(table.table) if externals: if users: print() table_data = [['First Name', 'Last Name', 'Email', 'Affiliation', 'Source', 'Identifier']] for ii in externals: data = ii.data table_data.append([data.get('first_name', ''), data.get('last_name', ''), data['email'], data.get('affiliation', '-'), ii.provider.name, ii.identifier]) table = AsciiTable(table_data, cformat('%{white!}Externals%{reset}')) print(table.table) @cli.command() @click.option('--admin/--no-admin', '-a/', 'grant_admin', is_flag=True, help='Grant admin rights') def create(grant_admin): """Create a new user.""" user_type = 'user' if not grant_admin else 'admin' while True: email = prompt_email() if email is None: return email = email.lower() if not User.query.filter(User.all_emails == email, ~User.is_deleted, ~User.is_pending).has_rows(): break print(cformat('%{red}Email already exists')) first_name = click.prompt("First name").strip() last_name = click.prompt("Last name").strip() affiliation = click.prompt("Affiliation", '').strip() print() while True: username = click.prompt("Enter username").lower().strip() if not Identity.query.filter_by(provider='indico', identifier=username).has_rows(): break print(cformat('%{red}Username already exists')) password = prompt_pass() if password is None: return identity = Identity(provider='indico', identifier=username, password=password) user = create_user(email, {'first_name': first_name, 'last_name': last_name, 'affiliation': affiliation}, identity) user.is_admin = grant_admin _print_user_info(user) if click.confirm(cformat("%{yellow}Create the new {}?").format(user_type), default=True): db.session.add(user) db.session.commit() print(cformat("%{green}New {} created successfully with ID: %{green!}{}").format(user_type, user.id)) @cli.command() @click.argument('user_id', type=int) def grant_admin(user_id): """Grant administration rights to a given user.""" user = User.get(user_id) if user is None: print(cformat("%{red}This user does not exist")) return _print_user_info(user) if user.is_admin: print(cformat("%{yellow}This user already has administration rights")) return if click.confirm(cformat("%{yellow}Grant administration rights to this user?")): user.is_admin = True db.session.commit() print(cformat("%{green}Administration rights granted successfully")) @cli.command() @click.argument('user_id', type=int) def revoke_admin(user_id): """Revoke administration rights from a given user.""" user = User.get(user_id) if user is None: print(cformat("%{red}This user does not exist")) return _print_user_info(user) if not user.is_admin: print(cformat("%{yellow}This user does not have administration rights")) return if click.confirm(cformat("%{yellow}Revoke administration rights from this user?")): user.is_admin = False db.session.commit() print(cformat("%{green}Administration rights revoked successfully")) @cli.command() @click.argument('user_id', type=int) def block(user_id): """Block a given user.""" user = User.get(user_id) if user is None: print(cformat("%{red}This user does not exist")) return _print_user_info(user) if user.is_blocked: print(cformat("%{yellow}This user is already blocked")) return if click.confirm(cformat("%{yellow}Block this user?")): user.is_blocked = True db.session.commit() print(cformat("%{green}Successfully blocked user")) @cli.command() @click.argument('user_id', type=int) def unblock(user_id): """Unblock a given user.""" user = User.get(user_id) if user is None: print(cformat("%{red}This user does not exist")) return _print_user_info(user) if not user.is_blocked: print(cformat("%{yellow}This user is not blocked")) return if click.confirm(cformat("%{yellow}Unblock this user?")): user.is_blocked = False db.session.commit() print(cformat("%{green}Successfully unblocked user"))
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ======================================================================== """Tensor Tracer report generation utilities.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import hashlib import os from tensorflow.python.platform import gfile from tensorflow.python.platform import tf_logging as logging from tensorflow.python.tpu import tensor_tracer_pb2 _TRACER_LOG_PREFIX = ' [>>>TT>>>]' _MARKER_SECTION_BEGIN = '!!!!!!! section-begin:' _MARKER_SECTION_END = '!!!!!!! section-end:' _SECTION_NAME_CONFIG = 'configuration' _SECTION_NAME_REASON = 'reason' _SECTION_NAME_OP_LIST = 'op-list' _SECTION_NAME_TENSOR_LIST = 'tensor-list' _SECTION_NAME_CACHE_INDEX_MAP = 'cache-index-map' _SECTION_NAME_GRAPH = 'graph' _SECTION_NAME_TENSOR_TRACER_CHECKPOINT = 'tensor_tracer_checkpoint' _FIELD_NAME_VERSION = 'version:' _FIELD_NAME_DEVICE = 'device:' _FIELD_NAME_TRACE_MODE = 'trace-mode:' _FIELD_NAME_SUBMODE = 'submode:' _FIELD_NAME_NUM_REPLICAS = 'num-replicas:' _FIELD_NAME_NUM_REPLICAS_PER_HOST = 'num-replicas-per-host:' _FIELD_NAME_NUM_HOSTS = 'num-hosts:' _FIELD_NAME_NUM_OPS = 'number-of-ops:' _FIELD_NAME_NUM_TENSORS = 'number-of-tensors:' _FIELD_NAME_NUM_CACHE_INDICES = 'number-of-indices:' _FIELD_NAME_TOPOLOGICAL_SORT_SUCCEED = 'topological-sort-succeed:' _CURRENT_VERSION = 'use-outside-compilation' _TT_REPORT_PROTO = 'tensor_tracer_report.report_pb' def report_proto_path(trace_dir): """Returns the path where report proto should be written. Args: trace_dir: String denoting the trace directory. Returns: A string denoting the path to the report proto. """ return os.path.join(trace_dir, _TT_REPORT_PROTO) def topological_sort(g): """Performs topological sort on the given graph. Args: g: the graph. Returns: A pair where the first element indicates if the topological sort succeeded (True if there is no cycle found; False if a cycle is found) and the second element is either the sorted list of nodes or the cycle of nodes found. """ def _is_loop_edge(op): """Returns true if the op is the end of a while-loop creating a cycle.""" return op.type in ['NextIteration'] def _in_op_degree(op): """Returns the number of incoming edges to the given op. The edge calculation skips the edges that come from 'NextIteration' ops. NextIteration creates a cycle in the graph. We break cycles by treating this op as 'sink' and ignoring all outgoing edges from it. Args: op: Tf.Operation Returns: the number of incoming edges. """ count = 0 for op in op.control_inputs + [in_tensor.op for in_tensor in op.inputs]: if not _is_loop_edge(op): count += 1 return count sorted_ops = [] op_in_degree = {op: _in_op_degree(op) for op in g.get_operations()} frontier = [op for (op, degree) in op_in_degree.items() if degree == 0] frontier.sort(key=lambda op: op.name) while frontier: op = frontier.pop() # Remove the op from graph, and remove its outgoing edges. sorted_ops.append(op) if _is_loop_edge(op): continue # pylint: disable=protected-access consumers = list(op._control_outputs) # pylint: enable=protected-access for out_tensor in op.outputs: consumers += [consumer_op for consumer_op in out_tensor.consumers()] consumers.sort(key=lambda op: op.name) for consumer in consumers: # For each deleted edge shift the bucket of the vertex. op_in_degree[consumer] -= 1 if op_in_degree[consumer] == 0: frontier.append(consumer) if op_in_degree[consumer] < 0: raise ValueError('consumer:%s degree mismatch'%consumer.name) left_ops = set(op for (op, degree) in op_in_degree.items() if degree > 0) if left_ops: return (True, left_ops) else: assert len(g.get_operations()) == len(sorted_ops) return (False, sorted_ops) class TensorTracerConfig(object): """Tensor Tracer config object.""" def __init__(self): self.version = _CURRENT_VERSION self.device_type = None self.num_replicas = None self.num_replicas_per_host = None self.num_hosts = None class TensorTraceOrder(object): """Class that is responsible from storing the trace-id of the tensors.""" def __init__(self, graph_order, traced_tensors): self.graph_order = graph_order self.traced_tensors = traced_tensors self._create_tensor_maps() def _create_tensor_maps(self): """Creates tensor to cache id maps.""" self.tensorname_to_cache_idx = {} self.cache_idx_to_tensor_idx = [] for out_tensor in self.traced_tensors: tensor_name = out_tensor.name if tensor_name in self.tensorname_to_cache_idx: raise ValueError('Tensor name {} should not be already in ' 'tensorname_to_cache_idx'.format(tensor_name)) if tensor_name not in self.graph_order.tensor_to_idx: raise ValueError( 'Tensor name {} is not in the tensor_to_idx, tensor_to_idx={} ' .format(tensor_name, self.graph_order.tensor_to_idx)) tensor_idx = self.graph_order.tensor_to_idx[tensor_name] cache_idx = len(self.tensorname_to_cache_idx) self.tensorname_to_cache_idx[tensor_name] = cache_idx self.cache_idx_to_tensor_idx.append(tensor_idx) if len(self.tensorname_to_cache_idx) != len( self.cache_idx_to_tensor_idx): raise RuntimeError( 'len(self.tensorname_to_cache_idx) must equal' 'len(self.cache_idx_to_tensor_idx), got ' 'len(self.tensorname_to_cache_idx)={}, ' 'len(self.cache_idx_to_tensor_idx)={}' .format( len(self.tensorname_to_cache_idx), len(self.cache_idx_to_tensor_idx))) def sort_tensors_and_ops(graph): """Returns a wrapper that has consistent tensor and op orders.""" graph_wrapper = collections.namedtuple('GraphWrapper', ['graph', 'operations', 'op_to_idx', 'tensors', 'tensor_to_idx', 'contains_cycle', 'topological_order_or_cycle']) contains_cycle, topological_order_or_cycle = topological_sort(graph) if not contains_cycle: operations = topological_order_or_cycle else: operations = graph.get_operations() op_to_idx = {op.name: index for index, op in enumerate(operations)} tensors = [] for op in operations: tensors.extend(op.outputs) tensor_to_idx = {tensor.name: index for index, tensor in enumerate(tensors)} return graph_wrapper(graph=graph, operations=operations, op_to_idx=op_to_idx, tensors=tensors, tensor_to_idx=tensor_to_idx, contains_cycle=contains_cycle, topological_order_or_cycle=topological_order_or_cycle) class OpenReportFile(object): """Context manager for writing report file.""" def __init__(self, tt_parameters): if not tt_parameters.report_file_path: self._report_file = None return try: self._report_file = gfile.Open(tt_parameters.report_file_path, 'w') except IOError as e: raise e def __enter__(self): return self._report_file def __exit__(self, unused_type, unused_value, unused_traceback): if self._report_file: self._report_file.close() def proto_fingerprint(message_proto): serialized_message = message_proto.SerializeToString() hasher = hashlib.sha256(serialized_message) return hasher.hexdigest() class TTReportHandle(object): """Utility class responsible from creating a tensor tracer report.""" def __init__(self): self.instrument_records = {} self._report_file = None def instrument(self, name, explanation): self.instrument_records[name] = explanation def instrument_op(self, op, explanation): self.instrument(op.name, explanation) def instrument_tensor(self, tensor, explanation): self.instrument(tensor.name, explanation) def create_report_proto(self, tt_config, tt_parameters, tensor_trace_order, tensor_trace_points, collected_signature_types): """Creates and returns a proto that stores tensor tracer configuration. Args: tt_config: TensorTracerConfig object holding information about the run environment (device, # cores, # hosts), and tensor tracer version information. tt_parameters: TTParameters objects storing the user provided parameters for tensor tracer. tensor_trace_order: TensorTraceOrder object storing a topological order of the graph. tensor_trace_points: Progromatically added trace_points/checkpoints. collected_signature_types: The signature types collected, e,g, norm, max, min, mean... Returns: TensorTracerReport proto. """ report = tensor_tracer_pb2.TensorTracerReport() report.config.version = tt_config.version report.config.device = tt_config.device_type report.config.num_cores = tt_config.num_replicas report.config.num_hosts = tt_config.num_hosts report.config.num_cores_per_host = tt_config.num_replicas_per_host report.config.submode = tt_parameters.submode report.config.trace_mode = tt_parameters.trace_mode for signature_name, _ in sorted(collected_signature_types.items(), key=lambda x: x[1]): report.config.signatures.append(signature_name) for tensor in tensor_trace_order.graph_order.tensors: tensor_def = tensor_tracer_pb2.TensorTracerReport.TracedTensorDef() tensor_def.name = tensor.name if tensor.name in tensor_trace_order.tensorname_to_cache_idx: tensor_def.is_traced = True tensor_def.cache_index = ( tensor_trace_order.tensorname_to_cache_idx[tensor.name]) else: # To prevent small changes affecting the fingerprint calculation, avoid # writing the untraced tensors to metadata. Fingerprints will be # different only when the list of the traced tensors are different. if tt_parameters.use_fingerprint_subdir: continue tensor_def.is_traced = False if tensor.name in tensor_trace_points: tensor_def.trace_point_name = tensor_trace_points[tensor.name] if tensor.name in self.instrument_records: tensor_def.explanation = self.instrument_records[tensor.name] elif tensor.op.name in self.instrument_records: tensor_def.explanation = self.instrument_records[tensor.op.name] report.tensordef[tensor.name].CopyFrom(tensor_def) report.fingerprint = proto_fingerprint(report) logging.info('TensorTracerProto fingerprint is %s.', report.fingerprint) tf_graph = tensor_trace_order.graph_order.graph report.graphdef.CopyFrom(tf_graph.as_graph_def()) return report def write_report_proto(self, report_proto, tt_parameters): """Writes the given report proto under trace_dir.""" gfile.MakeDirs(tt_parameters.trace_dir) report_path = report_proto_path(tt_parameters.trace_dir) with gfile.GFile(report_path, 'wb') as f: f.write(report_proto.SerializeToString()) def create_report(self, tt_config, tt_parameters, tensor_trace_order, tensor_trace_points): """Creates a report file and writes the trace information.""" with OpenReportFile(tt_parameters) as self._report_file: self._write_config_section(tt_config, tt_parameters) self._write_op_list_section(tensor_trace_order.graph_order) self._write_tensor_list_section(tensor_trace_order.graph_order) self._write_trace_points(tensor_trace_points) self._write_cache_index_map_section(tensor_trace_order) self._write_reason_section() self._write_graph_section(tensor_trace_order.graph_order) def _write_trace_points(self, tensor_trace_points): """Writes the list of checkpoints.""" self._write_report('%s %s\n'%(_MARKER_SECTION_BEGIN, _SECTION_NAME_TENSOR_TRACER_CHECKPOINT)) for (tensor, checkpoint_name) in tensor_trace_points: self._write_report('%s %s\n'%(tensor.name, checkpoint_name)) self._write_report('%s %s\n'%(_MARKER_SECTION_END, _SECTION_NAME_TENSOR_TRACER_CHECKPOINT)) def _write_report(self, content): """Writes the given content to the report.""" line = '%s %s'%(_TRACER_LOG_PREFIX, content) if self._report_file: self._report_file.write(line) else: logging.info(line) def _write_config_section(self, tt_config, tt_parameters): """Writes the config section of the report.""" self._write_report('%s %s\n'%(_MARKER_SECTION_BEGIN, _SECTION_NAME_CONFIG)) self._write_report('%s %s\n'%(_FIELD_NAME_VERSION, tt_config.version)) self._write_report('%s %s\n'%(_FIELD_NAME_DEVICE, tt_config.device_type)) self._write_report('%s %s\n'%(_FIELD_NAME_TRACE_MODE, tt_parameters.trace_mode)) self._write_report('%s %s\n'%(_FIELD_NAME_SUBMODE, tt_parameters.submode)) self._write_report('%s %s\n'%(_FIELD_NAME_NUM_REPLICAS, tt_config.num_replicas)) self._write_report('%s %s\n'%(_FIELD_NAME_NUM_REPLICAS_PER_HOST, tt_config.num_replicas_per_host)) self._write_report('%s %s\n'%(_FIELD_NAME_NUM_HOSTS, tt_config.num_hosts)) self._write_report('%s %s\n'%(_MARKER_SECTION_END, _SECTION_NAME_CONFIG)) def _write_reason_section(self): """Writes the reason section of the report.""" self._write_report('%s %s\n'%(_MARKER_SECTION_BEGIN, _SECTION_NAME_REASON)) for key in sorted(self.instrument_records): self._write_report('"%s" %s\n'%(key, self.instrument_records[key])) self._write_report('%s %s\n'%(_MARKER_SECTION_END, _SECTION_NAME_REASON)) def _write_op_list_section(self, graph_order): """Writes the Op-list section of the report.""" self._write_report('%s %s\n'%(_MARKER_SECTION_BEGIN, _SECTION_NAME_OP_LIST)) self._write_report('%s %d\n'%(_FIELD_NAME_NUM_OPS, len(graph_order.operations))) for i in range(0, len(graph_order.operations)): op = graph_order.operations[i] line = '%d "%s" %s'%(i, op.name, op.type) for out_tensor in op.outputs: if out_tensor.name not in graph_order.tensor_to_idx: raise ValueError( 'out_tensor is not in tensor_to_idx. out_tensor={}, ' 'tensor_to_idx={}' .format(out_tensor.name, graph_order.tensor_to_idx)) line += ' %d'%graph_order.tensor_to_idx[out_tensor.name] line += '\n' self._write_report(line) self._write_report('%s %s\n'%(_MARKER_SECTION_END, _SECTION_NAME_OP_LIST)) def _write_tensor_list_section(self, graph_order): """Writes the tensor-list section of the report.""" self._write_report('%s %s\n'%(_MARKER_SECTION_BEGIN, _SECTION_NAME_TENSOR_LIST)) self._write_report('%s %d\n'%(_FIELD_NAME_NUM_TENSORS, len(graph_order.tensors))) for i in range(0, len(graph_order.tensors)): tensor = graph_order.tensors[i] line = '%d "%s"'%(i, tensor.name) consumers = tensor.consumers() consumers.sort(key=lambda op: op.name) for consumer_op in consumers: if consumer_op.name not in graph_order.op_to_idx: raise ValueError( 'consumer_op is not in op_to_idx. ' 'got consumer_op={}, op_to_idx={}' .format(consumer_op.name, graph_order.op_to_idx)) line += ' %d'%graph_order.op_to_idx[consumer_op.name] line += '\n' self._write_report(line) self._write_report('%s %s\n'%(_MARKER_SECTION_END, _SECTION_NAME_TENSOR_LIST)) def _write_cache_index_map_section(self, tensor_trace_order): """Writes the mapping from cache index to tensor index to the report.""" self._write_report('%s %s\n'%(_MARKER_SECTION_BEGIN, _SECTION_NAME_CACHE_INDEX_MAP)) self._write_report('%s %d\n'%( _FIELD_NAME_NUM_CACHE_INDICES, len(tensor_trace_order.cache_idx_to_tensor_idx))) for cache_idx in range(0, len(tensor_trace_order.cache_idx_to_tensor_idx)): tensor_idx = tensor_trace_order.cache_idx_to_tensor_idx[cache_idx] line = '%d %d\n'%(cache_idx, tensor_idx) self._write_report(line) self._write_report('%s %s\n'%(_MARKER_SECTION_END, _SECTION_NAME_CACHE_INDEX_MAP)) def _write_graph_section(self, graph_order): """Writes the graph section of the report.""" self._write_report('%s %s\n'%(_MARKER_SECTION_BEGIN, _SECTION_NAME_GRAPH)) self._write_report('%s %s\n'%(_FIELD_NAME_TOPOLOGICAL_SORT_SUCCEED, not graph_order.contains_cycle)) l = list(graph_order.topological_order_or_cycle) for i in range(0, len(l)): self._write_report('%d "%s"\n'%(i, l[i].name)) self._write_report('%s %s\n'%(_MARKER_SECTION_END, _SECTION_NAME_GRAPH))
""" Copyright (c) 2016, Marcelo Leal Description: Simple Azure Media Services Python library License: MIT (see LICENSE.txt file for details) """ import os import re import json import azurerm import time #import pytz import logging import datetime from azure.storage.blob import BlockBlobService from azure.storage.blob import ContentSettings ########################################################################################### ##### DISCLAIMER ##### ##### DISCLAIMER ##### ##### DISCLAIMER ##### ##### DISCLAIMER ##### ########################################################################################### # ALL CODE IN THIS DIRECTOY (INCLUDING THIS FILE) ARE EXAMPLE CODES THAT WILL ACT ON YOUR # AMS ACCOUNT. IT ASSUMES THAT THE AMS ACCOUNT IS CLEAN (e.g.: BRAND NEW), WITH NO DATA OR # PRODUCTION CODE ON IT. DO NOT, AGAIN: DO NOT RUN ANY EXAMPLE CODE AGAINST PRODUCTION AMS # ACCOUNT! IF YOU RUN ANY EXAMPLE CODE AGAINST YOUR PRODUCTION AMS ACCOUNT, YOU CAN LOSE # DATA, AND/OR PUT YOUR AMS SERVICES IN A DEGRADED OR UNAVAILABLE STATE. BE WARNED! ########################################################################################### ##### DISCLAIMER ##### ##### DISCLAIMER ##### ##### DISCLAIMER ##### ##### DISCLAIMER ##### ########################################################################################### # Load Azure app defaults try: with open('config.json') as configFile: configData = json.load(configFile) except FileNotFoundError: print_phase_message("ERROR: Expecting config.json in current folder") sys.exit() account_name = configData['accountName'] account_key = configData['accountKey'] sto_account_name = configData['sto_accountName'] log_name = configData['logName'] log_level = configData['logLevel'] purge_log = configData['purgeLog'] #Initialization... print ("\n-----------------------= AMS Py =----------------------"); print ("Simple Python Library for Azure Media Services REST API"); print ("-------------------------------------------------------\n"); #Remove old log file if requested (default behavior)... if (purge_log.lower() == "yes"): if (os.path.isfile(log_name)): os.remove(log_name); #Basic Logging... logging.basicConfig(format='%(asctime)s - %(levelname)s:%(message)s', level=log_level, filename=log_name) # Get the access token... response = azurerm.get_ams_access_token(account_name, account_key) resjson = response.json() access_token = resjson["access_token"] #Some global vars... NAME = "movie" COUNTER = 0; ENCRYPTION = "1" # 0=None, StorageEncrypted=1, CommonEncryptionProtected=2, EnvelopeEncryptionProtected=4 ENCRYPTION_SCHEME = "StorageEncryption" # StorageEncryption or CommonEncryption. VIDEO_NAME = "movie.mp4" ISM_NAME = "movie.ism" VIDEO_PATH = "assets/movie.mp4" ISM_PATH = "assets/movie.ism" PROCESSOR_NAME = "Windows Azure Media Packager" AUTH_POLICY = '{"Name":"Open Authorization Policy"}' KEY_DELIVERY_TYPE = "2" # 1=PlayReady, 2=AES Envelope Encryption SCALE_UNIT = "1" # This will set the Scale Unit of the Streaming Unit to 1 (Each SU = 200mbs) # Just a simple wrapper function to print the title of each of our phases to the console... def print_phase_header(message): global COUNTER; print("\n[" + str("%02d" % int(COUNTER)) + "] >>> " + message) COUNTER += 1; # This wrapper function prints our messages to the console with a timestamp... def print_phase_message(message): time_stamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") print(str(time_stamp) + ": " + message) ### get ams redirected url response = azurerm.get_url(access_token) if (response.status_code == 200): ams_redirected_rest_endpoint = str(response.url) else: print_phase_message("GET Status: " + str(response.status_code) + " - Getting Redirected URL ERROR." + str(response.content)) exit(1); ### PRE-REQ We need to have a Content key to use for AES Encription and # at least 1 ("one") scale unit at the streaming endpoint (e.g.: default). # Here you can download a sample to create the Content Key for you: # https://github.com/msleal/create_ams_aeskey # The streaming endpoint will be scaled for you (to "1" scale unit). print_phase_header("Checking the AES Content Key and Setting Streaming Endpoint Scale Unit") response = azurerm.list_content_key(access_token) if (response.status_code == 200): resjson = response.json() count = len(resjson['d']['results']); if (count > 0): contentkey_id = str(resjson['d']['results'][0]['Id']) protectionkey_id = str(resjson['d']['results'][0]['ProtectionKeyId']) print_phase_message("GET Status..............................: " + str(response.status_code)) print_phase_message("AES Content Key Id......................: " + contentkey_id) print_phase_message("AES Content Key Name....................: " + str(resjson['d']['results'][0]['Name'])) print_phase_message("AES Content Protection Key Id...........: " + protectionkey_id) print_phase_message("AES Content Key Checksum................: " + str(resjson['d']['results'][0]['Checksum'])) else: print_phase_message("ERROR: AES Content Key Not Found. ") print_phase_message("Please create an AES Content Key and execute the script again. ") print_phase_message("Sample script to create one: https://github.com/msleal/create_ams_aeskey\n") exit(1); else: print_phase_message("GET Status.............................: " + str(response.status_code) + " - AES Content Key Listing ERROR." + str(response.content)) exit(1); # list and get the id of the default streaming endpoint print("") response = azurerm.list_streaming_endpoint(access_token) if (response.status_code == 200): resjson = response.json() for ea in resjson['d']['results']: print_phase_message("POST Status.............................: " + str(response.status_code)) print_phase_message("Streaming Endpoint Id...................: " + ea['Id']) print_phase_message("Streaming Endpoint Name.................: " + ea['Name']) print_phase_message("Streaming Endpoint Description..........: " + ea['Description']) if (ea['Name'] == 'default'): streaming_endpoint_id = ea['Id']; else: print_phase_message("POST Status.............................: " + str(response.status_code) + " - Streaming Endpoint Creation ERROR." + str(response.content)) # scale the default streaming endpoint print("") response = azurerm.scale_streaming_endpoint(access_token, streaming_endpoint_id, SCALE_UNIT) if (response.status_code == 202) or (response.status_code == 204): print_phase_message("POST Status.............................: " + str(response.status_code)) print_phase_message("Streaming Endpoint SU Configured to.....: " + SCALE_UNIT) else: print_phase_message("GET Status.............................: " + str(response.status_code) + " - Streaming Endpoint Scaling ERROR." + str(response.content)) exit(1); ######################### PHASE 1: UPLOAD and VALIDATE ######################### ### create an asset print_phase_header("Creating a Media Asset") response = azurerm.create_media_asset(access_token, NAME) if (response.status_code == 201): resjson = response.json() asset_id = str(resjson['d']['Id']); print_phase_message("POST Status.............................: " + str(response.status_code)) print_phase_message("Media Asset Name........................: " + NAME) print_phase_message("Media Asset Id..........................: " + asset_id) else: print_phase_message("POST Status.............................: " + str(response.status_code) + " - Media Asset: '" + NAME + "' Creation ERROR." + str(response.content)) ### list an asset print_phase_header("Listing a Media Asset") response = azurerm.list_media_asset(access_token, asset_id) if (response.status_code == 200): resjson = response.json() asset_uri = str(resjson['d']['Uri']) print_phase_message("GET Status..............................: " + str(response.status_code)) print_phase_message("Media Asset Name........................: " + str(resjson['d']['Name'])) print_phase_message("Media Asset Encryption..................: " + str(azurerm.translate_asset_options(resjson['d']['Options']))) print_phase_message("Media Asset Storage Account Name........: " + str(resjson['d']['StorageAccountName'])) print_phase_message("Media Asset Uri.........................: " + asset_uri) else: print_phase_message("GET Status..............................: " + str(response.status_code) + " - Media Asset: '" + asset_id + "' Listing ERROR." + str(response.content)) ### create an assetfile print_phase_header("Creating a Media Assetfile (for the video file)") response = azurerm.create_media_assetfile(access_token, asset_id, VIDEO_NAME, "false", "false") if (response.status_code == 201): resjson = response.json() video_assetfile_id = str(resjson['d']['Id']); print_phase_message("POST Status.............................: " + str(response.status_code)) print_phase_message("Media Assetfile Name....................: " + str(resjson['d']['Name'])) print_phase_message("Media Assetfile Id......................: " + video_assetfile_id) print_phase_message("Media Assetfile IsPrimary...............: " + str(resjson['d']['IsPrimary'])) else: print_phase_message("POST Status: " + str(response.status_code) + " - Media Assetfile: '" + VIDEO_NAME + "' Creation ERROR." + str(response.content)) ### create an assetfile print_phase_header("Creating a Media Assetfile (for the manifest file)") response = azurerm.create_media_assetfile(access_token, asset_id, ISM_NAME, "true", "false") if (response.status_code == 201): resjson = response.json() ism_assetfile_id = str(resjson['d']['Id']); print_phase_message("POST Status.............................: " + str(response.status_code)) print_phase_message("Media Assetfile Name....................: " + str(resjson['d']['Name'])) print_phase_message("Media Assetfile Id......................: " + ism_assetfile_id) print_phase_message("Media Assetfile IsPrimary...............: " + str(resjson['d']['IsPrimary'])) else: print_phase_message("POST Status: " + str(response.status_code) + " - Media Assetfile: '" + ISM_NAME + "' Creation ERROR." + str(response.content)) ### create an asset access policy print_phase_header("Creating an Asset Access Policy") duration = "440" response = azurerm.create_asset_accesspolicy(access_token, "NewUploadPolicy", duration, "2") if (response.status_code == 201): resjson = response.json() write_accesspolicy_id = str(resjson['d']['Id']); print_phase_message("POST Status.............................: " + str(response.status_code)) print_phase_message("Asset Access Policy Id..................: " + write_accesspolicy_id) print_phase_message("Asset Access Policy Duration/min........: " + str(resjson['d']['DurationInMinutes'])) else: print_phase_message("POST Status: " + str(response.status_code) + " - Asset Access Policy Creation ERROR." + str(response.content)) ### list an asset access policies print_phase_header("Listing a Asset Access Policies") response = azurerm.list_asset_accesspolicy(access_token) if (response.status_code == 200): resjson = response.json() print_phase_message("GET Status..............................: " + str(response.status_code)) for ap in resjson['d']['results']: print_phase_message("Asset Access Policie Id.................: " + str(ap['Id'])) else: print_phase_message("GET Status: " + str(response.status_code) + " - Asset Access Policy List ERROR." + str(response.content)) ### create a sas locator print_phase_header("Creating a SAS Locator") ## INFO: If you need to upload your files immediately, you should set your StartTime value to five minutes before the current time. #This is because there may be clock skew between your client machine and Media Services. #Also, your StartTime value must be in the following DateTime format: YYYY-MM-DDTHH:mm:ssZ (for example, "2014-05-23T17:53:50Z"). # EDITED: Not providing starttime is the best approach to be able to upload a file immediatly... #starttime = datetime.datetime.now(pytz.timezone(time_zone)).strftime("%Y-%m-%dT%H:%M:%SZ") #response = azurerm.create_sas_locator(access_token, asset_id, write_accesspolicy_id, starttime) response = azurerm.create_sas_locator(access_token, asset_id, write_accesspolicy_id) if (response.status_code == 201): resjson = response.json() saslocator_id = str(resjson['d']['Id']); saslocator_baseuri = str(resjson['d']['BaseUri']); sto_asset_name = os.path.basename(os.path.normpath(saslocator_baseuri)) saslocator_cac = str(resjson['d']['ContentAccessComponent']); print_phase_message("POST Status.............................: " + str(response.status_code)) print_phase_message("SAS URL Locator StartTime...............: " + str(resjson['d']['StartTime'])) print_phase_message("SAS URL Locator Id......................: " + saslocator_id) print_phase_message("SAS URL Locator Base URI................: " + saslocator_baseuri) print_phase_message("SAS URL Locator Content Access Component: " + saslocator_cac) else: print_phase_message("POST Status: " + str(response.status_code) + " - SAS URL Locator Creation ERROR." + str(response.content)) ### list the sas locator print_phase_header("Listing a SAS Locator") response = azurerm.list_sas_locator(access_token) if (response.status_code == 200): resjson = response.json() print_phase_message("GET Status..............................: " + str(response.status_code)) for sl in resjson['d']['results']: print_phase_message("SAS Locator Id..........................: " + str(sl['Id'])) else: print_phase_message("GET Status..............................: " + str(response.status_code) + " - SAS Locator List ERROR." + str(response.content)) ### Uploads block_blob_service = BlockBlobService(account_name=sto_account_name, sas_token=saslocator_cac[1:]) ### upload the video file print_phase_header("Uploading the Video File") with open(VIDEO_PATH, mode='rb') as file: video_content = file.read() video_content_length = len(video_content) response = block_blob_service.create_blob_from_path( sto_asset_name, VIDEO_NAME, VIDEO_PATH, max_connections=5, content_settings=ContentSettings(content_type='video/mp4') ) if (response == None): print_phase_message("PUT Status..............................: 201") print_phase_message("Video File Uploaded.....................: OK") ### upload the manifest file print_phase_header("Uploading the Manifest File") with open(ISM_PATH, mode='rb') as file: ism_content = file.read() ism_content_length = len(ism_content) response = block_blob_service.create_blob_from_path( sto_asset_name, ISM_NAME, ISM_PATH, max_connections=5, content_settings=ContentSettings(content_type='application/octet-stream') ) if (response == None): print_phase_message("PUT Status..............................: 201") print_phase_message("Manifest File Uploaded..................: OK") ### update the assetfile print_phase_header("Updating the Video Assetfile") response = azurerm.update_media_assetfile(access_token, asset_id, video_assetfile_id, video_content_length, VIDEO_NAME) if (response.status_code == 204): print_phase_message("MERGE Status............................: " + str(response.status_code)) print_phase_message("Assetfile Content Length Updated........: " + str(video_content_length)) else: print_phase_message("MERGE Status............................: " + str(response.status_code) + " - Assetfile: '" + VIDEO_NAME + "' Update ERROR." + str(response.content)) ### update the assetfile print_phase_header("Updating the Manifest Assetfile") response = azurerm.update_media_assetfile(access_token, asset_id, ism_assetfile_id, ism_content_length, ISM_NAME) if (response.status_code == 204): print_phase_message("MERGE Status............................: " + str(response.status_code)) print_phase_message("Assetfile Content Length Updated........: " + str(ism_content_length)) else: print_phase_message("MERGE Status............................: " + str(response.status_code) + " - Assetfile: '" + ISM_NAME + "' Update ERROR." + str(response.content)) ### delete the locator print_phase_header("Deleting the Locator") response = azurerm.delete_sas_locator(access_token, saslocator_id) if (response.status_code == 204): print_phase_message("DELETE Status...........................: " + str(response.status_code)) print_phase_message("SAS URL Locator Deleted.................: " + saslocator_id) else: print_phase_message("DELETE Status...........................: " + str(response.status_code) + " - SAS URL Locator: '" + saslocator_id + "' Delete ERROR." + str(response.content)) ### delete the asset access policy print_phase_header("Deleting the Acess Policy") response = azurerm.delete_asset_accesspolicy(access_token, write_accesspolicy_id) if (response.status_code == 204): print_phase_message("DELETE Status...........................: " + str(response.status_code)) print_phase_message("Asset Access Policy Deleted.............: " + write_accesspolicy_id) else: print_phase_message("DELETE Status...........................: " + str(response.status_code) + " - Asset Access Policy: '" + write_accesspolicy_id + "' Delete ERROR." + str(response.content)) ### get the media processor print_phase_header("Getting the Media Processor") response = azurerm.list_media_processor(access_token) if (response.status_code == 200): resjson = response.json() print_phase_message("GET Status..............................: " + str(response.status_code)) for mp in resjson['d']['results']: if(str(mp['Name']) == PROCESSOR_NAME): processor_id = str(mp['Id']) print_phase_message("MEDIA Processor Id......................: " + processor_id) print_phase_message("MEDIA Processor Name....................: " + PROCESSOR_NAME) else: print_phase_message("GET Status: " + str(response.status_code) + " - Media Processors Listing ERROR." + str(response.content)) ## create a media validation job print_phase_header("Creating a Media Job to validate the mp4") response = azurerm.validate_mp4_asset(access_token, processor_id, asset_id, "mp4validated") if (response.status_code == 201): resjson = response.json() job_id = str(resjson['d']['Id']); print_phase_message("POST Status.............................: " + str(response.status_code)) print_phase_message("Media Job Id............................: " + job_id) else: print_phase_message("POST Status.............................: " + str(response.status_code) + " - Media Job Creation ERROR." + str(response.content)) ### list a media job print_phase_header("Getting the Media Job Status") flag = 1 while (flag): response = azurerm.list_media_job(access_token, job_id) if (response.status_code == 200): resjson = response.json() job_state = str(resjson['d']['State']) if (resjson['d']['EndTime'] != None): joboutputassets_uri = resjson['d']['OutputMediaAssets']['__deferred']['uri'] flag = 0; print_phase_message("GET Status..............................: " + str(response.status_code)) print_phase_message("Media Job Status........................: " + azurerm.translate_job_state(job_state)) else: print_phase_message("GET Status..............................: " + str(response.status_code) + " - Media Job: '" + asset_id + "' Listing ERROR." + str(response.content)) time.sleep(5); ######################### PHASE 2: PROTECT and STREAM ######################### ### delete an asset if (azurerm.translate_job_state(job_state) == 'Finished'): ### delete an asset print_phase_header("Deleting the Original Asset") response = azurerm.delete_media_asset(access_token, asset_id) if (response.status_code == 204): print_phase_message("DELETE Status...........................: " + str(response.status_code)) print_phase_message("Asset Deleted...........................: " + asset_id) else: print_phase_message("DELETE Status...........................: " + str(response.status_code) + " - Asset: '" + asset_id + "' Delete ERROR." + str(response.content)) ## getting the encoded asset id print_phase_header("Getting the Encoded Media Asset Id") response = azurerm.get_url(access_token, joboutputassets_uri, False) if (response.status_code == 200): resjson = response.json() encoded_asset_id = resjson['d']['results'][0]['Id'] print_phase_message("GET Status..............................: " + str(response.status_code)) print_phase_message("Encoded Media Asset Id..................: " + encoded_asset_id) else: print_phase_message("GET Status..............................: " + str(response.status_code) + " - Media Job Output Asset: '" + job_id + "' Getting ERROR." + str(response.content)) ### link a content key print_phase_header("Linking the Content Key to the Encoded Asset") response = azurerm.link_asset_content_key(access_token, encoded_asset_id, contentkey_id, ams_redirected_rest_endpoint) if (response.status_code == 204): print_phase_message("GET Status..............................: " + str(response.status_code)) print_phase_message("Media Content Key Linked................: OK") else: print_phase_message("GET Status..............................: " + str(response.status_code) + " - Media Asset: '" + encoded_asset_id + "' Content Key Linking ERROR." + str(response.content)) ### configure content key authorization policy print_phase_header("Creating the Content Key Authorization Policy") response = azurerm.create_contentkey_authorization_policy(access_token, AUTH_POLICY) if (response.status_code == 201): resjson = response.json() authorization_policy_id = str(resjson['d']['Id']); print_phase_message("POST Status.............................: " + str(response.status_code)) print_phase_message("CK Authorization Policy Id..............: " + authorization_policy_id) else: print_phase_message("POST Status.............................: " + str(response.status_code) + " - Content Key Authorization Policy Creation ERROR." + str(response.content)) ### configure asset delivery policy print_phase_header("Creating the Content Key Authorization Policy Options") response = azurerm.create_contentkey_authorization_policy_options(access_token) if (response.status_code == 201): resjson = response.json() authorization_policy_options_id = str(resjson['d']['Id']); print_phase_message("POST Status.............................: " + str(response.status_code)) print_phase_message("CK Authorization Policy Options Id......: " + authorization_policy_options_id) else: print_phase_message("POST Status.............................: " + str(response.status_code) + " - Content Key Authorization Policy Options Creation ERROR." + str(response.content)) ### link a contentkey authorization policies with options print_phase_header("Linking the Content Key Authorization Policy with Options") response = azurerm.link_contentkey_authorization_policy(access_token, authorization_policy_id, authorization_policy_options_id, ams_redirected_rest_endpoint) if (response.status_code == 204): print_phase_message("GET Status..............................: " + str(response.status_code)) print_phase_message("CK Authorization Policy Linked..........: OK") else: print_phase_message("GET Status..............................: " + str(response.status_code) + " - Content Key Authorization Policy '" + authorization_policy_id + "' Linking ERROR." + str(response.content)) ### link a contentkey authorization policies with options print_phase_header("Add the Authorization Policy to the Content Key") response = azurerm.add_authorization_policy(access_token, contentkey_id, authorization_policy_id) if (response.status_code == 204): print_phase_message("GET Status..............................: " + str(response.status_code)) print_phase_message("Authorization Policy Added..............: OK") else: print_phase_message("GET Status..............................: " + str(response.status_code) + " - Authorization Policy: '" + authorization_policy_id + "' Adding ERROR." + str(response.content)) ### get the delivery url print_phase_header("Getting the Key Delivery URL") response = azurerm.get_key_delivery_url(access_token, contentkey_id, KEY_DELIVERY_TYPE) if (response.status_code == 200): resjson = response.json() keydelivery_url = re.sub("\?.*$","", str(resjson['d']['GetKeyDeliveryUrl'])); print_phase_message("POST Status.............................: " + str(response.status_code)) print_phase_message("Key Delivery URL........................: " + keydelivery_url) else: print_phase_message("POST Status.............................: " + str(response.status_code) + " - Key Delivery: '" + contentkey_id + "' URL Getting ERROR." + str(response.content)) ### create asset delivery policy print_phase_header("Creating Asset Delivery Policy") response = azurerm.create_asset_delivery_policy(access_token, account_name, keydelivery_url) if (response.status_code == 201): resjson = response.json() assetdeliverypolicy_id = str(resjson['d']['Id']); print_phase_message("POST Status.............................: " + str(response.status_code)) print_phase_message("Asset Delivery Policy Id................: " + assetdeliverypolicy_id) else: print_phase_message("POST Status.............................: " + str(response.status_code) + " - Asset Delivery Policy Creating ERROR." + str(response.content)) ### link the asset with the asset delivery policy print_phase_header("Linking the Asset with the Asset Delivery Policy") response = azurerm.link_asset_delivery_policy(access_token, encoded_asset_id, assetdeliverypolicy_id, ams_redirected_rest_endpoint) if (response.status_code == 204): print_phase_message("GET Status..............................: " + str(response.status_code)) print_phase_message("Asset Delivery Policy Linked............: OK") else: print_phase_message("GET Status..............................: " + str(response.status_code) + " - Asset: '" + encoded_asset_id + "' Delivery Policy Linking ERROR." + str(response.content)) ### create an asset access policy print_phase_header("Creating an Asset Access Policy") duration = "43200" response = azurerm.create_asset_accesspolicy(access_token, "NewViewAccessPolicy", duration) if (response.status_code == 201): resjson = response.json() view_accesspolicy_id = str(resjson['d']['Id']); print_phase_message("POST Status.............................: " + str(response.status_code)) print_phase_message("Asset Access Policy Id..................: " + view_accesspolicy_id) print_phase_message("Asset Access Policy Duration/min........: " + str(resjson['d']['DurationInMinutes'])) else: print_phase_message("POST Status: " + str(response.status_code) + " - Asset Access Policy Creation ERROR." + str(response.content)) ### create an ondemand streaming locator print_phase_header("Create an OnDemand Streaming Locator") #starttime = datetime.datetime.now(pytz.timezone(time_zone)).strftime("%Y-%m-%dT%H:%M:%SZ") #response = azurerm.create_ondemand_streaming_locator(access_token, encoded_asset_id, view_accesspolicy_id, starttime) response = azurerm.create_ondemand_streaming_locator(access_token, encoded_asset_id, view_accesspolicy_id) if (response.status_code == 201): resjson = response.json() ondemandlocator_id = str(resjson['d']['Id']); print_phase_message("GET Status..............................: " + str(response.status_code)) print_phase_message("OnDemand Streaming Locator Id...........: " + ondemandlocator_id) print_phase_message("OnDemand Streaming Locator Path.........: " + str(resjson['d']['Path'])) print_phase_message("HLS + AES URL...........................: " + str(resjson['d']['Path']) + ISM_NAME + "/manifest(format=m3u8-aapl)") print ("\n -> We got here? Cool! Now you just need the popcorn...") else: print_phase_message("GET Status..............................: " + str(response.status_code) + " - OnDemand Streaming Locator Creating ERROR." + str(response.content)) else: print ("\n Something went wrong... we could not validate the MP4 Asset!")
#!/usr/bin/env python # coding=UTF-8 # Requires https://github.com/moble/quaternion import argparse import ntpath import sys import math import numpy as np import numpy.linalg import matplotlib.pyplot as plt import matplotlib.ticker as tk import quaternion def str2bool(v): return v.lower() in ("yes", "true", "t", "1") def euclidean_distance(point1, point2): return numpy.sqrt(numpy.sum((point2 - point1)**2)) def angular_difference_degrees(quaternion1, quaternion2): diff_quaternion = (quaternion1 * quaternion2.conjugate()).normalized() if (diff_quaternion.w < 0.0): # shortest path angle diff_quaternion = -diff_quaternion return math.degrees(2.0 * math.acos(diff_quaternion.w)) ########################################################################## # Velocity and acceleration Savitzky-Golay filtering computation (http://dsp.stackexchange.com/questions/9498/have-position-want-to-calculate-velocity-and-acceleration) def sg_filter(time_values, polynomial_order, derivative=0): """ time_values = Vector of sample times polynomial_order = Order of the smoothing polynomial derivative = Which derivative """ mid = len(time_values) / 2 a = time_values - time_values[mid] expa = lambda time_values: map(lambda i: i**time_values, a) A = np.r_[map(expa, range(0,polynomial_order+1))].transpose() Ai = np.linalg.pinv(A) return Ai[derivative] def smooth(x, y, window_size=5, polynomial_order=2, derivative=0): if derivative > polynomial_order: raise Exception, "derivative must be <= polynomial_order" data_length = len(x) result = np.zeros(data_length) for i in xrange(window_size, data_length - window_size): start, end = i - window_size, i + window_size + 1 f = sg_filter(x[start:end], polynomial_order, derivative) result[i] = np.dot(f, y[start:end]) if derivative > 1: result *= math.factorial(derivative) return result if __name__ == "__main__": ########################################################################## # args parser = argparse.ArgumentParser(description='PLots line graphs from CSV file') parser.register('type', 'bool', str2bool) parser.add_argument('-i', metavar='INPUT_FILE', type=str, required=True, help='CSV input file name') parser.add_argument('-f', metavar='DERIVATIVE_ORDER', type=int, required=False, default=1, help='Order of derivative (0 -> original data, 1 -> velocity, 2 -> acceleration)') parser.add_argument('-r', metavar='NUMBER_POINTS_FOR_SMOOTHING', type=int, required=False, default=7, help='Number of data points that will be used to perform Savitzky-Golay filtering (0 disables smoothing, and result is the max of -r and data_points_nr * --smooth)') parser.add_argument('--smooth', metavar='NUMBER_PERCENTAGE_OF_POINTS_FOR_SMOOTHING', type=float, required=False, default=0.05, help='Percentage of data points that will be used to perform Savitzky-Golay filtering') parser.add_argument('-g', metavar='POLYNOMIAL_ORDER_FOR_SMOOTHING', type=int, required=False, default=2, help='Polynomial order that will be used to perform Savitzky-Golay filtering') parser.add_argument('-o', metavar='OUTPUT_FILE_NAME', type=str, required=False, default='results', help='Output file name (exports in svg, eps and pdf)') parser.add_argument('-p', metavar='INPUT_FILE_WITH_POSITIONS', type='bool', required=False, default=True, help='Whether the file has position or quaternion orientations (computes either the linear or angular velocity)') parser.add_argument('-x', metavar='FILES_TIME_COLUNM', type=str, required=False, default=0, help='CSV data column with the x data for each file split by -') parser.add_argument('--sort', metavar='SORT_TIME_COLUNM', type='bool', required=False, default=1, help='Sort all data by their time stamp') parser.add_argument('-y', metavar='FILES_POSE_START_COLUNMS', type=str, required=False, default=1, help='CSV data columns with the y data separated with + within file and split by - for each file') parser.add_argument('-z', metavar='FILE_VALUE_DELIMITER', type=str, required=False, default=',', help='Value delimiter in each line') parser.add_argument('-e', metavar='FILE_N_SKIP_ROWS', type=int, required=False, default=1, help='Number of rows to skip when reading files') parser.add_argument('-w', metavar='PLOT_LINE_WIDTH', type=float, required=False, default=0.25, help='Plot line width') parser.add_argument('-u', metavar='PLOT_LINE_STYLE', type=str, required=False, default='-', help='Plot line style') parser.add_argument('-a', metavar='PLOT_LINE_STYLE_ALPHA', type=float, required=False, default=0.75, help='Plot line alpha') parser.add_argument('-j', metavar='PLOT_LINE_MARKER', type=str, required=False, default='.', help='Plot line marker') parser.add_argument('-k', metavar='PLOT_LINE_MARKER_SIZE_WIDTH_MULTIPLIER', type=float, required=False, default=0.75, help='Plot line marker size will be PLOT_LINE_WIDTH * PLOT_LINE_MARKER_SIZE_WIDTH_MULTIPLIER') parser.add_argument('-m', metavar='X_AXIS_SCALE', type=float, required=False, default=0.000000001, help='X axis scale') parser.add_argument('-n', metavar='Y_AXIS_SCALE', type=float, required=False, default=1, help='Y axis scale') parser.add_argument('-b', metavar='X_AXIS_LABEL', type=str, required=False, default='X', help='X axis label') parser.add_argument('-v', metavar='Y_AXIS_LABEL', type=str, required=False, default='Y', help='Y axis label') parser.add_argument('-l', metavar='Y_LINES_LABELS', type=str, required=False, default='Data', help='Legend for each y plot line, separated by +') parser.add_argument('-c', metavar='Y_AXIS_COLORS', type=str, required=False, default='g', help='Y axis colors, separated by + in hex format #rrggbb') parser.add_argument('-t', metavar='GRAPH_TITLE', type=str, required=False, default='Paths', help='Graph title') parser.add_argument('--reset', metavar='RESET_X_VALUES', type='bool', required=False, default=False, help='Reset the x values so that they are in range [0..(max-min)]') parser.add_argument('--grid', metavar='DISPLAY_GRID', type='bool', required=False, default=True, help='Show graph grid') parser.add_argument('-s', metavar='SAVE_GRAPH', type='bool', required=False, default=True, help='Save graphs to files using the name prefix specified with -o') parser.add_argument('-q', metavar='ADD_FILE_EXTENSION_TO_PATH', type='bool', required=False, default=False, help='Prepend to path the extension of the output file') parser.add_argument('-d', metavar='DISPLAY_GRAPH', type='bool', required=False, default=False, help='Show graph') args = parser.parse_args() ########################################################################## # graph setup fig, ax = plt.subplots(figsize=(19.2, 10.8), dpi=100) plt.xlabel(args.b) plt.ylabel(args.v) graph_title = plt.title(args.t, fontsize=16) graph_title.set_y(1.01) plt.minorticks_on() if args.grid: plt.grid(b=True, which='major', color='k', linestyle='--', linewidth=0.30, alpha=0.5) plt.grid(b=True, which='minor', color='k', linestyle=':', linewidth=0.01, alpha=0.2) x_min = sys.maxint x_max = -sys.maxint y_min = sys.maxint y_max = -sys.maxint ########################################################################## # graph plotting file_names = args.i.split('+') time_columns = args.x.split('-') pose_start_columns_per_file = args.y.split('-') y_colors = args.c.split('+') y_labels = args.l.split('+') for idx_file, file in enumerate(file_names): time_values = np.loadtxt(file, dtype=float, delimiter=args.z, skiprows=args.e, usecols=(int(time_columns[idx_file]),)) if (args.sort): time_values_sorted_indexs = np.argsort(time_values) time_values = time_values[time_values_sorted_indexs] if args.m != 1: time_values *= args.m if args.reset: time_values -= np.min(time_values) pose_x = np.loadtxt(file, dtype=float, delimiter=args.z, skiprows=args.e, usecols=(int(pose_start_columns_per_file[idx_file]),)) pose_y = np.loadtxt(file, dtype=float, delimiter=args.z, skiprows=args.e, usecols=(int(pose_start_columns_per_file[idx_file]) + 1,)) pose_z = np.loadtxt(file, dtype=float, delimiter=args.z, skiprows=args.e, usecols=(int(pose_start_columns_per_file[idx_file]) + 2,)) if (args.sort): pose_x = pose_x[time_values_sorted_indexs] pose_y = pose_y[time_values_sorted_indexs] pose_z = pose_z[time_values_sorted_indexs] values_count = np.min([pose_x.size, pose_y.size, pose_z.size]) y_values = np.zeros(values_count) if args.p: for i in xrange(1, values_count): y_values[i] = euclidean_distance(np.array([ pose_x[i-1], pose_y[i-1], pose_z[i-1] ]), np.array([ pose_x[i], pose_y[i], pose_z[i] ])) else: pose_w = np.loadtxt(file, dtype=float, delimiter=args.z, skiprows=args.e, usecols=(int(pose_start_columns_per_file[idx_file]) + 3,)) if (args.sort): pose_w = pose_w[time_values_sorted_indexs] for i in range(1, values_count): y_values[i] = angular_difference_degrees( np.quaternion(pose_w[i-1], pose_x[i-1], pose_y[i-1], pose_z[i-1]), np.quaternion(pose_w[i], pose_x[i], pose_y[i], pose_z[i]) ) if args.n != 1: y_values *= args.n if args.f >= 0: if args.r == 0: for i in xrange(0, values_count-1): time_diff = time_values[i+1] - time_values[i] y_values[i] = y_values[i] / (time_diff ** args.f) else: y_values = np.cumsum(y_values) if args.f >= 1: number_smooth_points = int(np.max([args.r, values_count * args.smooth])) y_values = smooth(time_values, y_values, number_smooth_points, args.g, args.f) x_min = np.min([np.min(time_values), x_min]) x_max = np.max([np.max(time_values), x_max]) y_min = np.min([np.min(y_values), y_min]) y_max = np.max([np.max(y_values), y_max]) plt.plot(time_values, y_values, y_colors[idx_file], linewidth=args.w, label=y_labels[idx_file], alpha=args.a, linestyle=args.u, marker=args.j, markersize=args.w * args.k) plt.axis('tight') axlim = list(plt.axis()) diff_x = abs(x_max - x_min) diff_y = abs(y_max - y_min) axlim[0] = x_min - diff_x * 0.01 axlim[1] = x_max + diff_x * 0.01 axlim[2] = y_min - diff_y * 0.02 axlim[3] = y_max + diff_y * (0.042 * len(y_labels)) if axlim[0] == axlim[1]: axlim[0] -= 1 axlim[1] += 1 if axlim[2] == axlim[3]: axlim[2] -= 1 axlim[3] += 1 plt.axis(axlim) graph_legend = plt.legend(fancybox=True, prop={'size':12}) graph_legend.get_frame().set_alpha(0.75) plt.draw() ########################################################################## # output if args.s: if args.q: output_path = ntpath.dirname(args.o) output_file_name=ntpath.basename(args.o) plt.savefig('%s/svg/%s.svgz' % (output_path, output_file_name), bbox_inches='tight') plt.savefig('%s/eps/%s.eps' % (output_path, output_file_name), bbox_inches='tight') plt.savefig('%s/pdf/%s.pdf' % (output_path, output_file_name), bbox_inches='tight') # plt.savefig('%s/png/%s.png' % (output_path, output_file_name), dpi=300, bbox_inches='tight') else: plt.savefig('%s.svgz' % args.o, bbox_inches='tight') plt.savefig('%s.eps' % args.o, bbox_inches='tight') plt.savefig('%s.pdf' % args.o, bbox_inches='tight') # plt.savefig('%s.png' % args.o, dpi=300, bbox_inches='tight') if args.d: plt.show() exit(0)
# # 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. # """Fourth in a series of four pipelines that tell a story in a 'gaming' domain. New concepts: session windows and finding session duration; use of both singleton and non-singleton side inputs. This pipeline builds on the {@link LeaderBoard} functionality, and adds some "business intelligence" analysis: abuse detection and usage patterns. The pipeline derives the Mean user score sum for a window, and uses that information to identify likely spammers/robots. (The robots have a higher click rate than the human users). The 'robot' users are then filtered out when calculating the team scores. Additionally, user sessions are tracked: that is, we find bursts of user activity using session windows. Then, the mean session duration information is recorded in the context of subsequent fixed windowing. (This could be used to tell us what games are giving us greater user retention). Run injector.Injector to generate pubsub data for this pipeline. The Injector documentation provides more detail on how to do this. The injector is currently implemented in Java only, it can be used from the Java SDK. The PubSub topic you specify should be the same topic to which the Injector is publishing. To run the Java injector: <beam_root>/examples/java$ mvn compile exec:java \ -Dexec.mainClass=org.apache.beam.examples.complete.game.injector.Injector \ -Dexec.args="$PROJECT_ID $PUBSUB_TOPIC none" For a description of the usage and options, use -h or --help. To specify a different runner: --runner YOUR_RUNNER NOTE: When specifying a different runner, additional runner-specific options may have to be passed in as well EXAMPLES -------- # DirectRunner python game_stats.py \ --project $PROJECT_ID \ --topic projects/$PROJECT_ID/topics/$PUBSUB_TOPIC \ --dataset $BIGQUERY_DATASET # DataflowRunner python game_stats.py \ --project $PROJECT_ID \ --region $REGION_ID \ --topic projects/$PROJECT_ID/topics/$PUBSUB_TOPIC \ --dataset $BIGQUERY_DATASET \ --runner DataflowRunner \ --temp_location gs://$BUCKET/user_score/temp """ # pytype: skip-file from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import csv import logging import sys import time from datetime import datetime import apache_beam as beam from apache_beam.metrics.metric import Metrics from apache_beam.options.pipeline_options import GoogleCloudOptions from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import SetupOptions from apache_beam.options.pipeline_options import StandardOptions def timestamp2str(t, fmt='%Y-%m-%d %H:%M:%S.000'): """Converts a unix timestamp into a formatted string.""" return datetime.fromtimestamp(t).strftime(fmt) class ParseGameEventFn(beam.DoFn): """Parses the raw game event info into a Python dictionary. Each event line has the following format: username,teamname,score,timestamp_in_ms,readable_time e.g.: user2_AsparagusPig,AsparagusPig,10,1445230923951,2015-11-02 09:09:28.224 The human-readable time string is not used here. """ def __init__(self): # TODO(BEAM-6158): Revert the workaround once we can pickle super() on py3. # super(ParseGameEventFn, self).__init__() beam.DoFn.__init__(self) self.num_parse_errors = Metrics.counter(self.__class__, 'num_parse_errors') def process(self, elem): try: row = list(csv.reader([elem]))[0] yield { 'user': row[0], 'team': row[1], 'score': int(row[2]), 'timestamp': int(row[3]) / 1000.0, } except: # pylint: disable=bare-except # Log and count parse errors self.num_parse_errors.inc() logging.error('Parse error on "%s"', elem) class ExtractAndSumScore(beam.PTransform): """A transform to extract key/score information and sum the scores. The constructor argument `field` determines whether 'team' or 'user' info is extracted. """ def __init__(self, field): # TODO(BEAM-6158): Revert the workaround once we can pickle super() on py3. # super(ExtractAndSumScore, self).__init__() beam.PTransform.__init__(self) self.field = field def expand(self, pcoll): return ( pcoll | beam.Map(lambda elem: (elem[self.field], elem['score'])) | beam.CombinePerKey(sum)) class TeamScoresDict(beam.DoFn): """Formats the data into a dictionary of BigQuery columns with their values Receives a (team, score) pair, extracts the window start timestamp, and formats everything together into a dictionary. The dictionary is in the format {'bigquery_column': value} """ def process(self, team_score, window=beam.DoFn.WindowParam): team, score = team_score start = timestamp2str(int(window.start)) yield { 'team': team, 'total_score': score, 'window_start': start, 'processing_time': timestamp2str(int(time.time())) } class WriteToBigQuery(beam.PTransform): """Generate, format, and write BigQuery table row information.""" def __init__(self, table_name, dataset, schema, project): """Initializes the transform. Args: table_name: Name of the BigQuery table to use. dataset: Name of the dataset to use. schema: Dictionary in the format {'column_name': 'bigquery_type'} project: Name of the Cloud project containing BigQuery table. """ # TODO(BEAM-6158): Revert the workaround once we can pickle super() on py3. # super(WriteToBigQuery, self).__init__() beam.PTransform.__init__(self) self.table_name = table_name self.dataset = dataset self.schema = schema self.project = project def get_schema(self): """Build the output table schema.""" return ', '.join('%s:%s' % (col, self.schema[col]) for col in self.schema) def expand(self, pcoll): return ( pcoll | 'ConvertToRow' >> beam.Map(lambda elem: {col: elem[col] for col in self.schema}) | beam.io.WriteToBigQuery( self.table_name, self.dataset, self.project, self.get_schema())) # [START abuse_detect] class CalculateSpammyUsers(beam.PTransform): """Filter out all but those users with a high clickrate, which we will consider as 'spammy' uesrs. We do this by finding the mean total score per user, then using that information as a side input to filter out all but those user scores that are larger than (mean * SCORE_WEIGHT). """ SCORE_WEIGHT = 2.5 def expand(self, user_scores): # Get the sum of scores for each user. sum_scores = (user_scores | 'SumUsersScores' >> beam.CombinePerKey(sum)) # Extract the score from each element, and use it to find the global mean. global_mean_score = ( sum_scores | beam.Values() | beam.CombineGlobally(beam.combiners.MeanCombineFn())\ .as_singleton_view()) # Filter the user sums using the global mean. filtered = ( sum_scores # Use the derived mean total score (global_mean_score) as a side input. | 'ProcessAndFilter' >> beam.Filter( lambda key_score, global_mean:\ key_score[1] > global_mean * self.SCORE_WEIGHT, global_mean_score)) return filtered # [END abuse_detect] class UserSessionActivity(beam.DoFn): """Calculate and output an element's session duration, in seconds.""" def process(self, elem, window=beam.DoFn.WindowParam): yield (window.end.micros - window.start.micros) // 1000000 def run(argv=None, save_main_session=True): """Main entry point; defines and runs the hourly_team_score pipeline.""" parser = argparse.ArgumentParser() parser.add_argument('--topic', type=str, help='Pub/Sub topic to read from') parser.add_argument( '--subscription', type=str, help='Pub/Sub subscription to read from') parser.add_argument( '--dataset', type=str, required=True, help='BigQuery Dataset to write tables to. ' 'Must already exist.') parser.add_argument( '--table_name', type=str, default='game_stats', help='The BigQuery table name. Should not already exist.') parser.add_argument( '--fixed_window_duration', type=int, default=60, help='Numeric value of fixed window duration for user ' 'analysis, in minutes') parser.add_argument( '--session_gap', type=int, default=5, help='Numeric value of gap between user sessions, ' 'in minutes') parser.add_argument( '--user_activity_window_duration', type=int, default=30, help='Numeric value of fixed window for finding mean of ' 'user session duration, in minutes') args, pipeline_args = parser.parse_known_args(argv) if args.topic is None and args.subscription is None: parser.print_usage() print(sys.argv[0] + ': error: one of --topic or --subscription is required') sys.exit(1) options = PipelineOptions(pipeline_args) # We also require the --project option to access --dataset if options.view_as(GoogleCloudOptions).project is None: parser.print_usage() print(sys.argv[0] + ': error: argument --project is required') sys.exit(1) fixed_window_duration = args.fixed_window_duration * 60 session_gap = args.session_gap * 60 user_activity_window_duration = args.user_activity_window_duration * 60 # We use the save_main_session option because one or more DoFn's in this # workflow rely on global context (e.g., a module imported at module level). options.view_as(SetupOptions).save_main_session = save_main_session # Enforce that this pipeline is always run in streaming mode options.view_as(StandardOptions).streaming = True with beam.Pipeline(options=options) as p: # Read game events from Pub/Sub using custom timestamps, which # are extracted from the data elements, and parse the data. if args.subscription: scores = p | 'ReadPubSub' >> beam.io.ReadFromPubSub( subscription=args.subscription) else: scores = p | 'ReadPubSub' >> beam.io.ReadFromPubSub(topic=args.topic) raw_events = ( scores | 'DecodeString' >> beam.Map(lambda b: b.decode('utf-8')) | 'ParseGameEventFn' >> beam.ParDo(ParseGameEventFn()) | 'AddEventTimestamps' >> beam.Map( lambda elem: beam.window.TimestampedValue(elem, elem['timestamp']))) # Extract username/score pairs from the event stream user_events = ( raw_events | 'ExtractUserScores' >> beam.Map(lambda elem: (elem['user'], elem['score']))) # Calculate the total score per user over fixed windows, and cumulative # updates for late data spammers_view = ( user_events | 'UserFixedWindows' >> beam.WindowInto( beam.window.FixedWindows(fixed_window_duration)) # Filter out everyone but those with (SCORE_WEIGHT * avg) clickrate. # These might be robots/spammers. | 'CalculateSpammyUsers' >> CalculateSpammyUsers() # Derive a view from the collection of spammer users. It will be used as # a side input in calculating the team score sums, below | 'CreateSpammersView' >> beam.CombineGlobally( beam.combiners.ToDictCombineFn()).as_singleton_view()) # [START filter_and_calc] # Calculate the total score per team over fixed windows, and emit cumulative # updates for late data. Uses the side input derived above --the set of # suspected robots-- to filter out scores from those users from the sum. # Write the results to BigQuery. ( # pylint: disable=expression-not-assigned raw_events | 'WindowIntoFixedWindows' >> beam.WindowInto( beam.window.FixedWindows(fixed_window_duration)) # Filter out the detected spammer users, using the side input derived # above | 'FilterOutSpammers' >> beam.Filter( lambda elem, spammers: elem['user'] not in spammers, spammers_view) # Extract and sum teamname/score pairs from the event data. | 'ExtractAndSumScore' >> ExtractAndSumScore('team') # [END filter_and_calc] | 'TeamScoresDict' >> beam.ParDo(TeamScoresDict()) | 'WriteTeamScoreSums' >> WriteToBigQuery( args.table_name + '_teams', args.dataset, { 'team': 'STRING', 'total_score': 'INTEGER', 'window_start': 'STRING', 'processing_time': 'STRING', }, options.view_as(GoogleCloudOptions).project)) # [START session_calc] # Detect user sessions-- that is, a burst of activity separated by a gap # from further activity. Find and record the mean session lengths. # This information could help the game designers track the changing user # engagement as their set of game changes. ( # pylint: disable=expression-not-assigned user_events | 'WindowIntoSessions' >> beam.WindowInto( beam.window.Sessions(session_gap), timestamp_combiner=beam.window.TimestampCombiner.OUTPUT_AT_EOW) # For this use, we care only about the existence of the session, not any # particular information aggregated over it, so we can just group by key # and assign a "dummy value" of None. | beam.CombinePerKey(lambda _: None) # Get the duration of the session | 'UserSessionActivity' >> beam.ParDo(UserSessionActivity()) # [END session_calc] # [START rewindow] # Re-window to process groups of session sums according to when the # sessions complete | 'WindowToExtractSessionMean' >> beam.WindowInto( beam.window.FixedWindows(user_activity_window_duration)) # Find the mean session duration in each window | beam.CombineGlobally( beam.combiners.MeanCombineFn()).without_defaults() | 'FormatAvgSessionLength' >> beam.Map(lambda elem: {'mean_duration': float(elem)}) | 'WriteAvgSessionLength' >> WriteToBigQuery( args.table_name + '_sessions', args.dataset, { 'mean_duration': 'FLOAT', }, options.view_as(GoogleCloudOptions).project)) # [END rewindow] if __name__ == '__main__': logging.getLogger().setLevel(logging.INFO) run()
# -*- coding: utf-8 -*- # # Copyright (C)2005-2009 Edgewall Software # Copyright (C) 2005 Christopher Lenz <cmlenz@gmx.de> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://trac.edgewall.org/log/. # # Author: Christopher Lenz <cmlenz@gmx.de> from __future__ import with_statement import os import sys import time from trac.core import TracError from trac.db.util import ConnectionWrapper from trac.util.concurrency import threading from trac.util.text import exception_to_unicode from trac.util.translation import _ class TimeoutError(TracError): """Exception raised by the connection pool when no connection has become available after a given timeout.""" class PooledConnection(ConnectionWrapper): """A database connection that can be pooled. When closed, it gets returned to the pool. """ def __init__(self, pool, cnx, key, tid, log=None): ConnectionWrapper.__init__(self, cnx, log) self._pool = pool self._key = key self._tid = tid def close(self): if self.cnx: cnx = self.cnx self.cnx = None self.log = None self._pool._return_cnx(cnx, self._key, self._tid) def __del__(self): self.close() class ConnectionPoolBackend(object): """A process-wide LRU-based connection pool. """ def __init__(self, maxsize): self._available = threading.Condition(threading.RLock()) self._maxsize = maxsize self._active = {} self._pool = [] self._pool_key = [] self._pool_time = [] self._waiters = 0 def get_cnx(self, connector, kwargs, timeout=None): cnx = None log = kwargs.get('log') key = unicode(kwargs) start = time.time() tid = threading._get_ident() # Get a Connection, either directly or a deferred one with self._available: # First choice: Return the same cnx already used by the thread if (tid, key) in self._active: cnx, num = self._active[(tid, key)] num += 1 else: if self._waiters == 0: cnx = self._take_cnx(connector, kwargs, key, tid) if not cnx: self._waiters += 1 self._available.wait() self._waiters -= 1 cnx = self._take_cnx(connector, kwargs, key, tid) num = 1 if cnx: self._active[(tid, key)] = (cnx, num) deferred = num == 1 and isinstance(cnx, tuple) exc_info = (None, None, None) if deferred: # Potentially lengthy operations must be done without lock held op, cnx = cnx try: if op == 'ping': cnx.ping() elif op == 'close': cnx.close() if op in ('close', 'create'): cnx = connector.get_connection(**kwargs) except TracError: exc_info = sys.exc_info() cnx = None except Exception: exc_info = sys.exc_info() if log: log.error('Exception caught on %s', op, exc_info=True) cnx = None if cnx and not isinstance(cnx, tuple): if deferred: # replace placeholder with real Connection with self._available: self._active[(tid, key)] = (cnx, num) return PooledConnection(self, cnx, key, tid, log) if deferred: # cnx couldn't be reused, clear placeholder with self._available: del self._active[(tid, key)] if op == 'ping': # retry return self.get_cnx(connector, kwargs) # if we didn't get a cnx after wait(), something's fishy... if isinstance(exc_info[1], TracError): raise exc_info[0], exc_info[1], exc_info[2] timeout = time.time() - start errmsg = _("Unable to get database connection within %(time)d seconds.", time=timeout) if exc_info[1]: errmsg += " (%s)" % exception_to_unicode(exc_info[1]) raise TimeoutError(errmsg) def _take_cnx(self, connector, kwargs, key, tid): """Note: _available lock must be held when calling this method.""" # Second best option: Reuse a live pooled connection if key in self._pool_key: idx = self._pool_key.index(key) self._pool_key.pop(idx) self._pool_time.pop(idx) cnx = self._pool.pop(idx) # If possible, verify that the pooled connection is # still available and working. if hasattr(cnx, 'ping'): return ('ping', cnx) return cnx # Third best option: Create a new connection elif len(self._active) + len(self._pool) < self._maxsize: return ('create', None) # Forth best option: Replace a pooled connection with a new one elif len(self._active) < self._maxsize: # Remove the LRU connection in the pool cnx = self._pool.pop(0) self._pool_key.pop(0) self._pool_time.pop(0) return ('close', cnx) def _return_cnx(self, cnx, key, tid): # Decrement active refcount, clear slot if 1 with self._available: assert (tid, key) in self._active cnx, num = self._active[(tid, key)] if num == 1: del self._active[(tid, key)] else: self._active[(tid, key)] = (cnx, num - 1) if num == 1: # Reset connection outside of critical section try: cnx.rollback() # resets the connection except Exception: cnx.close() cnx = None # Connection available, from reuse or from creation of a new one with self._available: if cnx and cnx.poolable: self._pool.append(cnx) self._pool_key.append(key) self._pool_time.append(time.time()) self._available.notify() def shutdown(self, tid=None): """Close pooled connections not used in a while""" delay = 120 if tid is None: delay = 0 when = time.time() - delay with self._available: if tid is None: # global shutdown, also close active connections for db, num in self._active.values(): db.close() self._active = {} while self._pool_time and self._pool_time[0] <= when: db = self._pool.pop(0) db.close() self._pool_key.pop(0) self._pool_time.pop(0) _pool_size = int(os.environ.get('TRAC_DB_POOL_SIZE', 10)) _backend = ConnectionPoolBackend(_pool_size) class ConnectionPool(object): def __init__(self, maxsize, connector, **kwargs): # maxsize not used right now but kept for api compatibility self._connector = connector self._kwargs = kwargs def get_cnx(self, timeout=None): return _backend.get_cnx(self._connector, self._kwargs, timeout) def shutdown(self, tid=None): _backend.shutdown(tid)