gt
stringclasses
1 value
context
stringlengths
2.49k
119k
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains the definition for inception v3 classification network.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import inception_utils slim = tf.contrib.slim trunc_normal = lambda stddev: tf.truncated_normal_initializer(0.0, stddev) def inception_v3_base(inputs, final_endpoint='Mixed_7c', min_depth=16, depth_multiplier=1.0, scope=None): """Inception model from http://arxiv.org/abs/1512.00567. Constructs an Inception v3 network from inputs to the given final endpoint. This method can construct the network up to the final inception block Mixed_7c. Note that the names of the layers in the paper do not correspond to the names of the endpoints registered by this function although they build the same network. Here is a mapping from the old_names to the new names: Old name | New name ======================================= conv0 | Conv2d_1a_3x3 conv1 | Conv2d_2a_3x3 conv2 | Conv2d_2b_3x3 pool1 | MaxPool_3a_3x3 conv3 | Conv2d_3b_1x1 conv4 | Conv2d_4a_3x3 pool2 | MaxPool_5a_3x3 mixed_35x35x256a | Mixed_5b mixed_35x35x288a | Mixed_5c mixed_35x35x288b | Mixed_5d mixed_17x17x768a | Mixed_6a mixed_17x17x768b | Mixed_6b mixed_17x17x768c | Mixed_6c mixed_17x17x768d | Mixed_6d mixed_17x17x768e | Mixed_6e mixed_8x8x1280a | Mixed_7a mixed_8x8x2048a | Mixed_7b mixed_8x8x2048b | Mixed_7c Args: inputs: a tensor of size [batch_size, height, width, channels]. final_endpoint: specifies the endpoint to construct the network up to. It can be one of ['Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3', 'MaxPool_3a_3x3', 'Conv2d_3b_1x1', 'Conv2d_4a_3x3', 'MaxPool_5a_3x3', 'Mixed_5b', 'Mixed_5c', 'Mixed_5d', 'Mixed_6a', 'Mixed_6b', 'Mixed_6c', 'Mixed_6d', 'Mixed_6e', 'Mixed_7a', 'Mixed_7b', 'Mixed_7c']. min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. scope: Optional variable_scope. Returns: tensor_out: output tensor corresponding to the final_endpoint. end_points: a set of activations for external use, for example summaries or losses. Raises: ValueError: if final_endpoint is not set to one of the predefined values, or depth_multiplier <= 0 """ # end_points will collect relevant activations for external use, for example # summaries or losses. end_points = {} if depth_multiplier <= 0: raise ValueError('depth_multiplier is not greater than zero.') depth = lambda d: max(int(d * depth_multiplier), min_depth) with tf.variable_scope(scope, 'InceptionV3', [inputs]): with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='VALID'): # 299 x 299 x 3 end_point = 'Conv2d_1a_3x3' net = slim.conv2d(inputs, depth(32), [3, 3], stride=2, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 149 x 149 x 32 end_point = 'Conv2d_2a_3x3' net = slim.conv2d(net, depth(32), [3, 3], scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 147 x 147 x 32 end_point = 'Conv2d_2b_3x3' net = slim.conv2d(net, depth(64), [3, 3], padding='SAME', scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 147 x 147 x 64 end_point = 'MaxPool_3a_3x3' net = slim.max_pool2d(net, [3, 3], stride=2, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 73 x 73 x 64 end_point = 'Conv2d_3b_1x1' net = slim.conv2d(net, depth(80), [1, 1], scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 73 x 73 x 80. end_point = 'Conv2d_4a_3x3' net = slim.conv2d(net, depth(192), [3, 3], scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 71 x 71 x 192. end_point = 'MaxPool_5a_3x3' net = slim.max_pool2d(net, [3, 3], stride=2, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 35 x 35 x 192. # Inception blocks with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='SAME'): # mixed: 35 x 35 x 256. end_point = 'Mixed_5b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(48), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(64), [5, 5], scope='Conv2d_0b_5x5') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(32), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_1: 35 x 35 x 288. end_point = 'Mixed_5c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(48), [1, 1], scope='Conv2d_0b_1x1') branch_1 = slim.conv2d(branch_1, depth(64), [5, 5], scope='Conv_1_0c_5x5') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(64), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_2: 35 x 35 x 288. end_point = 'Mixed_5d' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(48), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(64), [5, 5], scope='Conv2d_0b_5x5') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(64), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_3: 17 x 17 x 768. end_point = 'Mixed_6a' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(384), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_1 = slim.conv2d(branch_1, depth(96), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_1x1') with tf.variable_scope('Branch_2'): branch_2 = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='MaxPool_1a_3x3') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed4: 17 x 17 x 768. end_point = 'Mixed_6b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(128), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(128), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(128), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(128), [7, 1], scope='Conv2d_0b_7x1') branch_2 = slim.conv2d(branch_2, depth(128), [1, 7], scope='Conv2d_0c_1x7') branch_2 = slim.conv2d(branch_2, depth(128), [7, 1], scope='Conv2d_0d_7x1') branch_2 = slim.conv2d(branch_2, depth(192), [1, 7], scope='Conv2d_0e_1x7') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_5: 17 x 17 x 768. end_point = 'Mixed_6c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(160), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(160), [7, 1], scope='Conv2d_0b_7x1') branch_2 = slim.conv2d(branch_2, depth(160), [1, 7], scope='Conv2d_0c_1x7') branch_2 = slim.conv2d(branch_2, depth(160), [7, 1], scope='Conv2d_0d_7x1') branch_2 = slim.conv2d(branch_2, depth(192), [1, 7], scope='Conv2d_0e_1x7') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_6: 17 x 17 x 768. end_point = 'Mixed_6d' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(160), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(160), [7, 1], scope='Conv2d_0b_7x1') branch_2 = slim.conv2d(branch_2, depth(160), [1, 7], scope='Conv2d_0c_1x7') branch_2 = slim.conv2d(branch_2, depth(160), [7, 1], scope='Conv2d_0d_7x1') branch_2 = slim.conv2d(branch_2, depth(192), [1, 7], scope='Conv2d_0e_1x7') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_7: 17 x 17 x 768. end_point = 'Mixed_6e' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(192), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(192), [7, 1], scope='Conv2d_0b_7x1') branch_2 = slim.conv2d(branch_2, depth(192), [1, 7], scope='Conv2d_0c_1x7') branch_2 = slim.conv2d(branch_2, depth(192), [7, 1], scope='Conv2d_0d_7x1') branch_2 = slim.conv2d(branch_2, depth(192), [1, 7], scope='Conv2d_0e_1x7') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_8: 8 x 8 x 1280. end_point = 'Mixed_7a' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_0 = slim.conv2d(branch_0, depth(320), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(192), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') branch_1 = slim.conv2d(branch_1, depth(192), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='MaxPool_1a_3x3') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_9: 8 x 8 x 2048. end_point = 'Mixed_7b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(320), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(384), [1, 1], scope='Conv2d_0a_1x1') branch_1 = tf.concat(axis=3, values=[ slim.conv2d(branch_1, depth(384), [1, 3], scope='Conv2d_0b_1x3'), slim.conv2d(branch_1, depth(384), [3, 1], scope='Conv2d_0b_3x1')]) with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(448), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d( branch_2, depth(384), [3, 3], scope='Conv2d_0b_3x3') branch_2 = tf.concat(axis=3, values=[ slim.conv2d(branch_2, depth(384), [1, 3], scope='Conv2d_0c_1x3'), slim.conv2d(branch_2, depth(384), [3, 1], scope='Conv2d_0d_3x1')]) with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d( branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_10: 8 x 8 x 2048. end_point = 'Mixed_7c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(320), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(384), [1, 1], scope='Conv2d_0a_1x1') branch_1 = tf.concat(axis=3, values=[ slim.conv2d(branch_1, depth(384), [1, 3], scope='Conv2d_0b_1x3'), slim.conv2d(branch_1, depth(384), [3, 1], scope='Conv2d_0c_3x1')]) with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(448), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d( branch_2, depth(384), [3, 3], scope='Conv2d_0b_3x3') branch_2 = tf.concat(axis=3, values=[ slim.conv2d(branch_2, depth(384), [1, 3], scope='Conv2d_0c_1x3'), slim.conv2d(branch_2, depth(384), [3, 1], scope='Conv2d_0d_3x1')]) with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d( branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points raise ValueError('Unknown final endpoint %s' % final_endpoint) def inception_v3(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.8, min_depth=16, depth_multiplier=1.0, prediction_fn=slim.softmax, spatial_squeeze=True, reuse=None, create_aux_logits=True, scope='InceptionV3'): """Inception model from http://arxiv.org/abs/1512.00567. "Rethinking the Inception Architecture for Computer Vision" Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, Zbigniew Wojna. With the default arguments this method constructs the exact model defined in the paper. However, one can experiment with variations of the inception_v3 network by changing arguments dropout_keep_prob, min_depth and depth_multiplier. The default image size used to train this network is 299x299. Args: inputs: a tensor of size [batch_size, height, width, channels]. num_classes: number of predicted classes. is_training: whether is training or not. dropout_keep_prob: the percentage of activation values that are retained. min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. prediction_fn: a function to get predictions out of logits. spatial_squeeze: if True, logits is of shape [B, C], if false logits is of shape [B, 1, 1, C], where B is batch_size and C is number of classes. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. create_aux_logits: Whether to create the auxiliary logits. scope: Optional variable_scope. Returns: logits: the pre-softmax activations, a tensor of size [batch_size, num_classes] end_points: a dictionary from components of the network to the corresponding activation. Raises: ValueError: if 'depth_multiplier' is less than or equal to zero. """ if depth_multiplier <= 0: raise ValueError('depth_multiplier is not greater than zero.') depth = lambda d: max(int(d * depth_multiplier), min_depth) with tf.variable_scope(scope, 'InceptionV3', [inputs, num_classes], reuse=reuse) as scope: with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training): net, end_points = inception_v3_base( inputs, scope=scope, min_depth=min_depth, depth_multiplier=depth_multiplier) # Auxiliary Head logits if create_aux_logits: with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='SAME'): aux_logits = end_points['Mixed_6e'] with tf.variable_scope('AuxLogits'): aux_logits = slim.avg_pool2d( aux_logits, [5, 5], stride=3, padding='VALID', scope='AvgPool_1a_5x5') aux_logits = slim.conv2d(aux_logits, depth(128), [1, 1], scope='Conv2d_1b_1x1') # Shape of feature map before the final layer. kernel_size = _reduced_kernel_size_for_small_input( aux_logits, [5, 5]) aux_logits = slim.conv2d( aux_logits, depth(768), kernel_size, weights_initializer=trunc_normal(0.01), padding='VALID', scope='Conv2d_2a_{}x{}'.format(*kernel_size)) aux_logits = slim.conv2d( aux_logits, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, weights_initializer=trunc_normal(0.001), scope='Conv2d_2b_1x1') if spatial_squeeze: aux_logits = tf.squeeze(aux_logits, [1, 2], name='SpatialSqueeze') end_points['AuxLogits'] = aux_logits # Final pooling and prediction with tf.variable_scope('Logits'): kernel_size = _reduced_kernel_size_for_small_input(net, [8, 8]) net = slim.avg_pool2d(net, kernel_size, padding='VALID', scope='AvgPool_1a_{}x{}'.format(*kernel_size)) # 1 x 1 x 2048 net = slim.dropout(net, keep_prob=dropout_keep_prob, scope='Dropout_1b') end_points['PreLogits'] = net # 2048 logits = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, scope='Conv2d_1c_1x1') if spatial_squeeze: logits = tf.squeeze(logits, [1, 2], name='SpatialSqueeze') # 1000 end_points['Logits'] = logits end_points['Predictions'] = prediction_fn(logits, scope='Predictions') return logits, end_points inception_v3.default_image_size = 299 def _reduced_kernel_size_for_small_input(input_tensor, kernel_size): """Define kernel size which is automatically reduced for small input. If the shape of the input images is unknown at graph construction time this function assumes that the input images are is large enough. Args: input_tensor: input tensor of size [batch_size, height, width, channels]. kernel_size: desired kernel size of length 2: [kernel_height, kernel_width] Returns: a tensor with the kernel size. TODO(jrru): Make this function work with unknown shapes. Theoretically, this can be done with the code below. Problems are two-fold: (1) If the shape was known, it will be lost. (2) inception.slim.ops._two_element_tuple cannot handle tensors that define the kernel size. shape = tf.shape(input_tensor) return = tf.pack([tf.minimum(shape[1], kernel_size[0]), tf.minimum(shape[2], kernel_size[1])]) """ shape = input_tensor.get_shape().as_list() if shape[1] is None or shape[2] is None: kernel_size_out = kernel_size else: kernel_size_out = [min(shape[1], kernel_size[0]), min(shape[2], kernel_size[1])] return kernel_size_out inception_v3_arg_scope = inception_utils.inception_arg_scope
# -*- coding: utf-8 -*- ''' Return salt data via slack This version of the returner is designed to be used with hubblestack pulsar, as it expects the limited data which pulsar provides. The following fields can be set in the minion conf file:: .. code-block:: yaml slack_pulsar.channel (required) slack_pulsar.api_key (required) slack_pulsar.username (required) slack_pulsar.as_user (required to see the profile picture of your bot) slack_pulsar.profile (optional) Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location: .. code-block:: yaml slack_pulsar.channel slack_pulsar.api_key slack_pulsar.username slack_pulsar.as_user Slack settings may also be configured as: .. code-block:: yaml slack: channel: RoomName api_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx username: user as_user: true alternative.slack: room_id: RoomName api_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx from_name: user@email.com slack_profile: api_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx from_name: user@email.com slack: profile: slack_profile channel: RoomName alternative.slack: profile: slack_profile channel: RoomName ''' from __future__ import absolute_import # Import Python libs import pprint import logging import urllib # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext.six.moves.urllib.parse import urljoin as _urljoin # pylint: disable=import-error,no-name-in-module import salt.ext.six.moves.http_client # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import Salt Libs import salt.returners __version__ = 'v2016.10.4' log = logging.getLogger(__name__) __virtualname__ = 'slack_pulsar' def _get_options(ret=None): ''' Get the slack options from salt. ''' defaults = {'channel': '#general'} attrs = {'slack_profile': 'profile', 'channel': 'channel', 'username': 'username', 'as_user': 'as_user', 'api_key': 'api_key', } profile_attr = 'slack_profile' profile_attrs = {'from_jid': 'from_jid', 'api_key': 'api_key', 'api_version': 'api_key' } _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, profile_attr=profile_attr, profile_attrs=profile_attrs, __salt__=__salt__, __opts__=__opts__, defaults=defaults) return _options def __virtual__(): ''' Return virtual name of the module. :return: The virtual name of the module. ''' return __virtualname__ def _query(function, api_key=None, args=None, method='GET', header_dict=None, data=None): ''' Slack object method function to construct and execute on the API URL. :param api_key: The Slack api key. :param function: The Slack api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. :return: The json response from the API call or False. ''' query_params = {} ret = {'message': '', 'res': True} slack_functions = { 'rooms': { 'request': 'channels.list', 'response': 'channels', }, 'users': { 'request': 'users.list', 'response': 'members', }, 'message': { 'request': 'chat.postMessage', 'response': 'channel', }, } if not api_key: try: options = __salt__['config.option']('slack') if not api_key: api_key = options.get('api_key') except (NameError, KeyError, AttributeError): log.error('No Slack api key found.') ret['message'] = 'No Slack api key found.' ret['res'] = False return ret api_url = 'https://slack.com' base_url = _urljoin(api_url, '/api/') path = slack_functions.get(function).get('request') url = _urljoin(base_url, path, False) if not isinstance(args, dict): query_params = {} query_params['token'] = api_key if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' result = salt.utils.http.query( url, method, params=query_params, data=data, decode=True, status=True, header_dict=header_dict, opts=__opts__, ) if result.get('status', None) == salt.ext.six.moves.http_client.OK: _result = result['dict'] response = slack_functions.get(function).get('response') if 'error' in _result: ret['message'] = _result['error'] ret['res'] = False return ret ret['message'] = _result.get(response) return ret elif result.get('status', None) == salt.ext.six.moves.http_client.NO_CONTENT: return True else: log.debug(url) log.debug(query_params) log.debug(data) log.debug(result) _result = result['dict'] if 'error' in _result: ret['message'] = _result['error'] ret['res'] = False return ret ret['message'] = _result.get(response) return ret def _post_message(channel, message, username, as_user, api_key=None): ''' Send a message to a Slack room. :param channel: The room name. :param message: The message to send to the Slack room. :param username: Specify who the message is from. :param as_user: Sets the profile picture which have been added through Slack itself. :param api_key: The Slack api key, if not specified in the configuration. :param api_version: The Slack api version, if not specified in the configuration. :return: Boolean if message was sent successfully. ''' parameters = dict() parameters['channel'] = channel parameters['username'] = username parameters['as_user'] = as_user parameters['text'] = '```' + message + '```' # pre-formatted, fixed-width text # Slack wants the body on POST to be urlencoded. result = _query(function='message', api_key=api_key, method='POST', header_dict={'Content-Type': 'application/x-www-form-urlencoded'}, data=urllib.urlencode(parameters)) log.debug('result {0}'.format(result)) if result: return True else: return False def returner(ret): ''' Send an slack message with the data ''' _options = _get_options(ret) channel = _options.get('channel') username = _options.get('username') as_user = _options.get('as_user') api_key = _options.get('api_key') if not channel: log.error('slack_pulsar.channel not defined in salt config') return if not username: log.error('slack_pulsar.username not defined in salt config') return if not as_user: log.error('slack_pulsar.as_user not defined in salt config') return if not api_key: log.error('slack_pulsar.api_key not defined in salt config') return if ret and isinstance(ret, dict): message = ('id: {0}\r\n' 'return: {1}\r\n').format(__opts__['id'], pprint.pformat(ret.get('return'))) elif ret and isinstance(ret, list): message = 'id: {0}\r\n' for r in ret: message += pprint.pformat(r.get('return')) message += '\r\n' else: log.error('Data sent to slack_pulsar formatted incorrectly') return slack = _post_message(channel, message, username, as_user, api_key) return slack
#!/usr/bin/python """Script to implement a BTU meter that uses a pulse output flow meter and two thermistors to measure hydronic heat flow. Results are posted to the mini-monitor MQTT broker. This script should be started by a supervisor capable of restarting the script if an error occurs. This script must be run with sudo because it writes to the /var/local directory. """ import time import sys import os import argparse import shutil import RPi.GPIO as GPIO import input_change import mqtt_poster import thermistor # Import SPI library (for hardware SPI) and MCP3008 library. import Adafruit_GPIO.SPI as SPI import Adafruit_MCP3008 # GPIO Pins (BCM numbering) and ADC channels used by the BTU METER PIN_PULSE_IN = 13 # the pulse input pin PIN_CALIBRATE = 4 # the calibrate push button is connected here PIN_LED = 16 # the calibrate LED is on this pin PIN_DEBUG = 5 # a pin used to output a debug signal ADC_CH_THOT = 0 # the MCP3008 ADC channel used for the hot thermistor ADC_CH_TCOLD = 1 # the MCP3008 ADC channel used for the cold thermistor # Eliminate GPIO warnings GPIO.setwarnings(False) # Make the LED pin an output GPIO.setmode(GPIO.BCM) GPIO.setup(PIN_LED, GPIO.OUT) # Count at which pulse counter rolls to zero PULSE_ROLLOVER = 1000000 # Value at which the heat count rolls over. This is a sum of the delta-Ts # that are present when pulses occur. HEAT_ROLLOVER = 1000000.0 # Number of A/D readings to average together to get the # current temperature reading. BUF_LEN_TEMP = 100 # Path to temperature calibration file PATH_CALIBRATE = '/var/local/btu_calibration' # process command line arguments parser = argparse.ArgumentParser(description='BTU Meter Script.') parser.add_argument("-d", "--debug", help="Set Debug mode", action="store_true") args = parser.parse_args() # set the debug pin if requested debug_pin = PIN_DEBUG if args.debug else None # Access some settings in the Mini-Monitor settings file # The settings file is installed in the FAT boot partition of the Pi SD card, # so that it can be easily configured from the PC that creates the SD card. # Include that directory in the Path so the settings file can be found. sys.path.insert(0, '/boot/pi_logger') import settings # make a base sensor id base_sensor_id = '%s_%2d_btu' % (settings.LOGGER_ID, PIN_PULSE_IN) # get logging interval in seconds log_interval = getattr(settings, 'BTU_LOG_INTERVAL', 10 * 60) # get the minimum delta-T required to tally energy flow (deg F) min_delta_T = getattr(settings, 'BTU_MIN_DELTA_T', 0.2) # flag to determine if both transitions are counted count_both = getattr(settings, 'BTU_BOTH_EDGES', False) # start up the object that posts to the MQTT broker poster = mqtt_poster.MQTTposter() poster.start() # make a thermistor object to convert A/D readings into temperature. # Using a 4.99 K divider resistor and a 10-bit A/D converter with max # value of 1023. therm = thermistor.Thermistor('BAPI 10K-3', appliedV=1023.0, dividerR=4990.0) # Initialize pulse count and heat count pulse_count = 0 heat_count = 0.0 # Set up MCP3008 A/D converter. We are using the hardware SPI port # on the Raspberry Pi (to save CPU cycles). SPI_PORT = 0 SPI_DEVICE = 0 mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) # Initialize arrays to hold hot and cold thermistor A/D readings. # These arrays are used to calculate a current reading that is # an average of recent readings. The raw A/D counts are stored # in the array to elimnate the CPU time needed to convert each into # a temperature. Variation between the readings is small, so the # non-linearity of the count-->temperature function is not important. ad_hot = [mcp.read_adc(ADC_CH_THOT)] * BUF_LEN_TEMP ad_cold = [mcp.read_adc(ADC_CH_TCOLD)] * BUF_LEN_TEMP # read in the temperature calibration coefficients if the file exists if os.path.exists(PATH_CALIBRATE): with open(PATH_CALIBRATE, 'r') as fin: calibrate_hot = float(fin.readline()) calibrate_cold = float(fin.readline()) else: calibrate_hot = 0.0 calibrate_cold = 0.0 def current_temps(include_calibration=True): """Returns the current hot and cold temperatures, averaging the values in the reading buffer. If 'include_calibration' is True, apply the calibration values. """ thot = sum(ad_hot)/float(BUF_LEN_TEMP) thot = therm.TfromV(thot) if include_calibration: thot += calibrate_hot tcold = sum(ad_cold)/float(BUF_LEN_TEMP) tcold = therm.TfromV(tcold) if include_calibration: tcold += calibrate_cold return thot, tcold def chg_detected(pin_num, new_state): """This is called when any of watched input pins change state. """ global pulse_count, heat_count global calibrate_hot, calibrate_cold if pin_num == PIN_PULSE_IN: if new_state == False or count_both: # get current temperatures thot, tcold = current_temps() delta_T = thot - tcold # enforce minimum delta-T if abs(delta_T) < min_delta_T: delta_T = 0.0 pulse_count += 1 pulse_count = pulse_count % PULSE_ROLLOVER heat_count += delta_T heat_count = heat_count % HEAT_ROLLOVER elif pin_num == PIN_CALIBRATE: if new_state == False: # Calibrate button was pressed # Check a second later to see if it is still pressed. # Note that this interrupts pulse counting. time.sleep(1.0) if GPIO.input(PIN_CALIBRATE)==False: # blink LED to indicate that calibrate function will occur GPIO.output(PIN_LED, True) time.sleep(1.0) GPIO.output(PIN_LED, False) # calibrate process thot, tcold = current_temps(include_calibration=False) true_temp = (thot + tcold)/2.0 # deemed the true temp calibrate_hot = true_temp - thot calibrate_cold = true_temp - tcold # backup old calibration values and store new values shutil.copy(PATH_CALIBRATE, PATH_CALIBRATE + '.bak') with open(PATH_CALIBRATE, 'w') as fout: fout.write('%s\n' % calibrate_hot) fout.write('%s\n' % calibrate_cold) # Start up the Input Pin Change Detector # I have a 10 K pull-up on the board and a 0.01 uF cap to ground. chg_detect = input_change.InputChange([PIN_PULSE_IN, PIN_CALIBRATE], chg_detected, pull_up=False, debug_pin=debug_pin) chg_detect.start() # determine time to log count next_log_ts = time.time() + log_interval # index into temperature reading buffer arrays ix = 0 while True: if not chg_detect.isAlive() or not poster.isAlive(): # important thread is not running. Exit with an error. sys.exit(1) # Read temperatures and update buffer index ad_hot[ix] = mcp.read_adc(ADC_CH_THOT) ad_cold[ix] = mcp.read_adc(ADC_CH_TCOLD) ix = (ix + 1) % BUF_LEN_TEMP # Check to see if it is time to log ts = time.time() if ts > next_log_ts: post_str = '' ts = int(ts) thot, tcold = current_temps() for id, val in (('heat', heat_count), ('pulse', pulse_count), ('thot', thot), ('tcold', tcold)): post_str += '%s\t%s_%s\t%s\n' % (ts, base_sensor_id, id, val) poster.publish('readings/final/btu_meter', post_str) if args.debug: print pulse_count, heat_count, current_temps() next_log_ts += log_interval time.sleep(0.05)
# coding: utf-8 """ CMS-related job helpers. """ __all__ = ["CMSJobDashboard"] import time import socket import threading import six import law from law.job.base import BaseJobManager from law.job.dashboard import BaseJobDashboard class CMSJobDashboard(BaseJobDashboard): """ This CMS job dashboard interface requires ``apmon`` to be installed on your system. See http://monalisa.caltech.edu/monalisa__Documentation__ApMon_User_Guide__apmon_ug_py.html and https://twiki.cern.ch/twiki/bin/view/ArdaGrid/CMSJobMonitoringCollector. """ PENDING = "pending" RUNNING = "running" CANCELLED = "cancelled" POSTPROC = "postproc" SUCCESS = "success" FAILED = "failed" tracking_url = "http://dashb-cms-job.cern.ch/dashboard/templates/task-analysis/#" + \ "table=Jobs&p=1&activemenu=2&refresh=60&tid={dashboard_task_id}" persistent_attributes = ["task_id", "cms_user", "voms_user", "init_timestamp"] def __init__(self, task, cms_user, voms_user, apmon_config=None, log_level="WARNING", max_rate=20, task_type="analysis", site=None, executable="law", application=None, application_version=None, submission_tool="law", submission_type="direct", submission_ui=None, init_timestamp=None): super(CMSJobDashboard, self).__init__(max_rate=max_rate) # setup the apmon thread try: self.apmon = Apmon(apmon_config, self.max_rate, log_level) except ImportError as e: e.message += " (required for {})".format(self.__class__.__name__) e.args = (e.message,) + e.args[1:] raise e # get the task family for use as default application name task_family = task.get_task_family() if isinstance(task, law.Task) else task # mandatory (persistent) attributes self.task_id = task.task_id if isinstance(task, law.Task) else task self.cms_user = cms_user self.voms_user = voms_user self.init_timestamp = init_timestamp or self.create_timestamp() # optional attributes self.task_type = task_type self.site = site self.executable = executable self.application = application or task_family self.application_version = application_version or self.task_id.rsplit("_", 1)[1] self.submission_tool = submission_tool self.submission_type = submission_type self.submission_ui = submission_ui or socket.gethostname() # start the apmon thread self.apmon.daemon = True self.apmon.start() def __del__(self): if getattr(self, "apmon", None) and self.apmon.is_alive(): self.apmon.stop() self.apmon.join() @classmethod def create_timestamp(cls): return time.strftime("%y%m%d_%H%M%S") @classmethod def create_dashboard_task_id(cls, task_id, cms_user, timestamp=None): if not timestamp: timestamp = cls.create_timestamp() return "{}:{}_{}".format(timestamp, cms_user, task_id) @classmethod def create_dashboard_job_id(cls, job_num, job_id, attempt=0): return "{}_{}_{}".format(job_num, job_id, attempt) @classmethod def params_from_status(cls, dashboard_status, fail_code=1): if dashboard_status == cls.PENDING: return {"StatusValue": "pending", "SyncCE": None} elif dashboard_status == cls.RUNNING: return {"StatusValue": "running"} elif dashboard_status == cls.CANCELLED: return {"StatusValue": "cancelled", "SyncCE": None} elif dashboard_status == cls.POSTPROC: return {"StatusValue": "running", "JobExitCode": 0} elif dashboard_status == cls.SUCCESS: return {"StatusValue": "success", "JobExitCode": 0} elif dashboard_status == cls.FAILED: return {"StatusValue": "failed", "JobExitCode": fail_code} else: raise ValueError("invalid dashboard status '{}'".format(dashboard_status)) @classmethod def map_status(cls, job_status, event): # when starting with "status.", event must end with the job status if event.startswith("status.") and event.split(".", 1)[-1] != job_status: raise ValueError("event '{}' does not match job status '{}'".format(event, job_status)) status = lambda attr: "status.{}".format(getattr(BaseJobManager, attr)) return { "action.submit": cls.PENDING, "action.cancel": cls.CANCELLED, "custom.running": cls.RUNNING, "custom.postproc": cls.POSTPROC, "custom.failed": cls.FAILED, status("FINISHED"): cls.SUCCESS, }.get(event) def remote_hook_file(self): return law.util.rel_path(__file__, "scripts", "cmsdashb_hooks.sh") def remote_hook_data(self, job_num, attempt): data = [ "task_id='{}'".format(self.task_id), "cms_user='{}'".format(self.cms_user), "voms_user='{}'".format(self.voms_user), "init_timestamp='{}'".format(self.init_timestamp), "job_num={}".format(job_num), "attempt={}".format(attempt), ] if self.site: data.append("site='{}'".format(self.site)) return data def create_tracking_url(self): dashboard_task_id = self.create_dashboard_task_id(self.task_id, self.cms_user, self.init_timestamp) return self.tracking_url.format(dashboard_task_id=dashboard_task_id) def create_message(self, job_data, event, job_num, attempt=0, custom_params=None, **kwargs): # we need the voms user, which must start with "/CN=" voms_user = self.voms_user if not voms_user: return if not voms_user.startswith("/CN="): voms_user = "/CN=" + voms_user # map to job status to a valid dashboard status dashboard_status = self.map_status(job_data.get("status"), event) if not dashboard_status: return # build the dashboard task id dashboard_task_id = self.create_dashboard_task_id(self.task_id, self.cms_user, self.init_timestamp) # build the id of the particular job dashboard_job_id = self.create_dashboard_job_id(job_num, job_data["job_id"], attempt=attempt) # build the parameters to send params = { "TaskId": dashboard_task_id, "JobId": dashboard_job_id, "GridJobId": job_data["job_id"], "CMSUser": self.cms_user, "GridName": voms_user, "JSToolUI": kwargs.get("submission_ui", self.submission_ui), } # add optional params params.update({ "TaskType": kwargs.get("task_type", self.task_type), "SyncCE": kwargs.get("site", self.site), "Executable": kwargs.get("executable", self.executable), "Application": kwargs.get("application", self.application), "ApplicationVersion": kwargs.get("application_version", self.application_version), "JSTool": kwargs.get("submission_tool", self.submission_tool), "SubmissionType": kwargs.get("submission_type", self.submission_type), }) # add status params params.update(self.params_from_status(dashboard_status, fail_code=job_data.get("code", 1))) # add custom params if custom_params: params.update(custom_params) # finally filter None's and convert everything to strings params = {key: str(value) for key, value in six.iteritems(params) if value is not None} return (dashboard_task_id, dashboard_job_id, params) @BaseJobDashboard.cache_by_status def publish(self, *args, **kwargs): message = self.create_message(*args, **kwargs) if message: self.apmon.send(*message) apmon_lock = threading.Lock() class Apmon(threading.Thread): default_config = { "cms-jobmon.cern.ch:8884": { "sys_monitoring": 0, "general_info": 0, "job_monitoring": 0, }, } def __init__(self, config=None, max_rate=20, log_level="INFO"): super(Apmon, self).__init__() import apmon log_level = getattr(apmon.Logger, log_level.upper()) self._apmon = apmon.ApMon(config or self.default_config, log_level) self._apmon.maxMsgRate = int(max_rate * 1.5) # hotfix of a bug occurring in apmon for too large pids for key, value in self._apmon.senderRef.items(): value["INSTANCE_ID"] = value["INSTANCE_ID"] & 0x7fffffff self._max_rate = max_rate self._queue = six.moves.queue.Queue() self._stop_event = threading.Event() def send(self, *args, **kwargs): self._queue.put((args, kwargs)) def _send(self, *args, **kwargs): self._apmon.sendParameters(*args, **kwargs) def stop(self): self._stop_event.set() def run(self): while True: # handling stopping self._stop_event.wait(0.5) if self._stop_event.is_set(): break if self._queue.empty(): continue with apmon_lock: while not self._queue.empty(): args, kwargs = self._queue.get() self._send(*args, **kwargs) time.sleep(1. / self._max_rate)
from __future__ import unicode_literals import re from .mtv import MTVServicesInfoExtractor from ..compat import ( compat_str, compat_urllib_parse, ) from ..utils import ( ExtractorError, float_or_none, unified_strdate, ) class ComedyCentralIE(MTVServicesInfoExtractor): _VALID_URL = r'''(?x)https?://(?:www\.)?cc\.com/ (video-clips|episodes|cc-studios|video-collections|full-episodes) /(?P<title>.*)''' _FEED_URL = 'http://comedycentral.com/feeds/mrss/' _TEST = { 'url': 'http://www.cc.com/video-clips/kllhuv/stand-up-greg-fitzsimmons--uncensored---too-good-of-a-mother', 'md5': 'c4f48e9eda1b16dd10add0744344b6d8', 'info_dict': { 'id': 'cef0cbb3-e776-4bc9-b62e-8016deccb354', 'ext': 'mp4', 'title': 'CC:Stand-Up|Greg Fitzsimmons: Life on Stage|Uncensored - Too Good of a Mother', 'description': 'After a certain point, breastfeeding becomes c**kblocking.', }, } class ComedyCentralShowsIE(MTVServicesInfoExtractor): IE_DESC = 'The Daily Show / The Colbert Report' # urls can be abbreviations like :thedailyshow or :colbert # urls for episodes like: # or urls for clips like: http://www.thedailyshow.com/watch/mon-december-10-2012/any-given-gun-day # or: http://www.colbertnation.com/the-colbert-report-videos/421667/november-29-2012/moon-shattering-news # or: http://www.colbertnation.com/the-colbert-report-collections/422008/festival-of-lights/79524 _VALID_URL = r'''(?x)^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport) |https?://(:www\.)? (?P<showname>thedailyshow|thecolbertreport)\.(?:cc\.)?com/ ((?:full-)?episodes/(?:[0-9a-z]{6}/)?(?P<episode>.*)| (?P<clip> (?:(?:guests/[^/]+|videos|video-playlists|special-editions|news-team/[^/]+)/[^/]+/(?P<videotitle>[^/?#]+)) |(the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?)) |(watch/(?P<date>[^/]*)/(?P<tdstitle>.*)) )| (?P<interview> extended-interviews/(?P<interID>[0-9a-z]+)/(?:playlist_tds_extended_)?(?P<interview_title>.*?)(/.*?)?))) ''' _TESTS = [{ 'url': 'http://thedailyshow.cc.com/watch/thu-december-13-2012/kristen-stewart', 'md5': '4e2f5cb088a83cd8cdb7756132f9739d', 'info_dict': { 'id': 'ab9ab3e7-5a98-4dbe-8b21-551dc0523d55', 'ext': 'mp4', 'upload_date': '20121213', 'description': 'Kristen Stewart learns to let loose in "On the Road."', 'uploader': 'thedailyshow', 'title': 'thedailyshow kristen-stewart part 1', } }, { 'url': 'http://thedailyshow.cc.com/extended-interviews/xm3fnq/andrew-napolitano-extended-interview', 'only_matching': True, }, { 'url': 'http://thecolbertreport.cc.com/videos/29w6fx/-realhumanpraise-for-fox-news', 'only_matching': True, }, { 'url': 'http://thecolbertreport.cc.com/videos/gh6urb/neil-degrasse-tyson-pt--1?xrs=eml_col_031114', 'only_matching': True, }, { 'url': 'http://thedailyshow.cc.com/guests/michael-lewis/3efna8/exclusive---michael-lewis-extended-interview-pt--3', 'only_matching': True, }, { 'url': 'http://thedailyshow.cc.com/episodes/sy7yv0/april-8--2014---denis-leary', 'only_matching': True, }, { 'url': 'http://thecolbertreport.cc.com/episodes/8ase07/april-8--2014---jane-goodall', 'only_matching': True, }, { 'url': 'http://thedailyshow.cc.com/video-playlists/npde3s/the-daily-show-19088-highlights', 'only_matching': True, }, { 'url': 'http://thedailyshow.cc.com/video-playlists/t6d9sg/the-daily-show-20038-highlights/be3cwo', 'only_matching': True, }, { 'url': 'http://thedailyshow.cc.com/special-editions/2l8fdb/special-edition---a-look-back-at-food', 'only_matching': True, }, { 'url': 'http://thedailyshow.cc.com/news-team/michael-che/7wnfel/we-need-to-talk-about-israel', 'only_matching': True, }] _available_formats = ['3500', '2200', '1700', '1200', '750', '400'] _video_extensions = { '3500': 'mp4', '2200': 'mp4', '1700': 'mp4', '1200': 'mp4', '750': 'mp4', '400': 'mp4', } _video_dimensions = { '3500': (1280, 720), '2200': (960, 540), '1700': (768, 432), '1200': (640, 360), '750': (512, 288), '400': (384, 216), } def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) if mobj.group('shortname'): if mobj.group('shortname') in ('tds', 'thedailyshow'): url = 'http://thedailyshow.cc.com/full-episodes/' else: url = 'http://thecolbertreport.cc.com/full-episodes/' mobj = re.match(self._VALID_URL, url, re.VERBOSE) assert mobj is not None if mobj.group('clip'): if mobj.group('videotitle'): epTitle = mobj.group('videotitle') elif mobj.group('showname') == 'thedailyshow': epTitle = mobj.group('tdstitle') else: epTitle = mobj.group('cntitle') dlNewest = False elif mobj.group('interview'): epTitle = mobj.group('interview_title') dlNewest = False else: dlNewest = not mobj.group('episode') if dlNewest: epTitle = mobj.group('showname') else: epTitle = mobj.group('episode') show_name = mobj.group('showname') webpage, htmlHandle = self._download_webpage_handle(url, epTitle) if dlNewest: url = htmlHandle.geturl() mobj = re.match(self._VALID_URL, url, re.VERBOSE) if mobj is None: raise ExtractorError('Invalid redirected URL: ' + url) if mobj.group('episode') == '': raise ExtractorError('Redirected URL is still not specific: ' + url) epTitle = (mobj.group('episode') or mobj.group('videotitle')).rpartition('/')[-1] mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage) if len(mMovieParams) == 0: # The Colbert Report embeds the information in a without # a URL prefix; so extract the alternate reference # and then add the URL prefix manually. altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video|playlist).*?:.*?)"', webpage) if len(altMovieParams) == 0: raise ExtractorError('unable to find Flash URL in webpage ' + url) else: mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])] uri = mMovieParams[0][1] # Correct cc.com in uri uri = re.sub(r'(episode:[^.]+)(\.cc)?\.com', r'\1.cc.com', uri) index_url = 'http://%s.cc.com/feeds/mrss?%s' % (show_name, compat_urllib_parse.urlencode({'uri': uri})) idoc = self._download_xml( index_url, epTitle, 'Downloading show index', 'Unable to download episode index') title = idoc.find('./channel/title').text description = idoc.find('./channel/description').text entries = [] item_els = idoc.findall('.//item') for part_num, itemEl in enumerate(item_els): upload_date = unified_strdate(itemEl.findall('./pubDate')[0].text) thumbnail = itemEl.find('.//{http://search.yahoo.com/mrss/}thumbnail').attrib.get('url') content = itemEl.find('.//{http://search.yahoo.com/mrss/}content') duration = float_or_none(content.attrib.get('duration')) mediagen_url = content.attrib['url'] guid = itemEl.find('./guid').text.rpartition(':')[-1] cdoc = self._download_xml( mediagen_url, epTitle, 'Downloading configuration for segment %d / %d' % (part_num + 1, len(item_els))) turls = [] for rendition in cdoc.findall('.//rendition'): finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text) turls.append(finfo) formats = [] for format, rtmp_video_url in turls: w, h = self._video_dimensions.get(format, (None, None)) formats.append({ 'format_id': 'vhttp-%s' % format, 'url': self._transform_rtmp_url(rtmp_video_url), 'ext': self._video_extensions.get(format, 'mp4'), 'height': h, 'width': w, }) formats.append({ 'format_id': 'rtmp-%s' % format, 'url': rtmp_video_url.replace('viacomccstrm', 'viacommtvstrm'), 'ext': self._video_extensions.get(format, 'mp4'), 'height': h, 'width': w, }) self._sort_formats(formats) virtual_id = show_name + ' ' + epTitle + ' part ' + compat_str(part_num + 1) entries.append({ 'id': guid, 'title': virtual_id, 'formats': formats, 'uploader': show_name, 'upload_date': upload_date, 'duration': duration, 'thumbnail': thumbnail, 'description': description, }) return { '_type': 'playlist', 'entries': entries, 'title': show_name + ' ' + title, 'description': description, }
#!/usr/bin/env python # Copyright 2013 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. import logging import os import shutil import subprocess import sys import tempfile import time import unittest THIS_DIR = os.path.dirname(os.path.abspath(__file__)) # Small hack to make it work on Windows even without symlink support. if os.path.isfile(os.path.join(THIS_DIR, 'utils')): sys.path.insert(0, os.path.join(THIS_DIR, '..', '..', '..', 'client')) # Import them first before manipulating sys.path to ensure they can load fine. import bot_main import logging_utils import os_utilities import xsrf_client from utils import net from utils import zip_package THIS_FILE = os.path.abspath(__file__) BASE_DIR = os.path.dirname(THIS_FILE) ROOT_DIR = os.path.dirname(BASE_DIR) sys.path.insert(0, ROOT_DIR) import test_env test_env.setup_test_env() CLIENT_TESTS = os.path.join(ROOT_DIR, '..', '..', 'client', 'tests') sys.path.insert(0, CLIENT_TESTS) import bot import bot_config # Creates a server mock for functions in net.py. import net_utils # Access to a protected member XX of a client class - pylint: disable=W0212 class TestBotMain(net_utils.TestCase): def setUp(self): super(TestBotMain, self).setUp() os.environ.pop('SWARMING_LOAD_TEST', None) self.root_dir = tempfile.mkdtemp(prefix='bot_main') self.old_cwd = os.getcwd() os.chdir(self.root_dir) self.server = xsrf_client.XsrfRemote('https://localhost:1/') self.attributes = { 'dimensions': { 'foo': ['bar'], 'id': ['localhost'], }, 'state': { 'cost_usd_hour': 3600., }, 'version': '123', } self.mock(zip_package, 'generate_version', lambda: '123') self.bot = bot.Bot( self.server, self.attributes, 'version1', self.root_dir, self.fail) self.mock(self.bot, 'post_error', self.fail) self.mock(self.bot, 'restart', self.fail) self.mock(subprocess, 'call', self.fail) self.mock(time, 'time', lambda: 100.) def tearDown(self): os.environ.pop('SWARMING_BOT_ID', None) os.chdir(self.old_cwd) shutil.rmtree(self.root_dir) super(TestBotMain, self).tearDown() def test_get_dimensions(self): dimensions = set(bot_main.get_dimensions()) dimensions.discard('hidpi') expected = {'cores', 'cpu', 'gpu', 'id', 'machine_type', 'os'} self.assertEqual(expected, dimensions) def test_get_dimensions_load_test(self): os.environ['SWARMING_LOAD_TEST'] = '1' self.assertEqual(['id', 'load_test'], sorted(bot_main.get_dimensions())) def test_generate_version(self): self.assertEqual('123', bot_main.generate_version()) def test_get_state(self): self.mock(time, 'time', lambda: 126.0) expected = os_utilities.get_state() expected['sleep_streak'] = 12 self.assertEqual(expected, bot_main.get_state(12)) def test_setup_bot(self): self.mock(bot_main, 'get_remote', lambda: self.server) setup_bots = [] def setup_bot(_bot): setup_bots.append(1) return False self.mock(bot_config, 'setup_bot', setup_bot) restarts = [] post_event = [] self.mock( os_utilities, 'restart', lambda *a, **kw: restarts.append((a, kw))) self.mock( bot.Bot, 'post_event', lambda *a, **kw: post_event.append((a, kw))) self.expected_requests([]) bot_main.setup_bot(False) self.assertEqual( [(('Starting new swarming bot: %s' % THIS_FILE,), {'timeout': 900})], restarts) self.assertEqual([1], setup_bots) expected = [ 'Starting new swarming bot: %s' % THIS_FILE, 'Bot is stuck restarting for: Starting new swarming bot: %s' % THIS_FILE, ] self.assertEqual(expected, [i[0][2] for i in post_event]) def test_post_error_task(self): self.mock(time, 'time', lambda: 126.0) self.mock(logging, 'error', lambda *_: None) self.mock(bot_main, 'get_remote', lambda: self.server) expected_attribs = bot_main.get_attributes() self.expected_requests( [ ( 'https://localhost:1/auth/api/v1/accounts/self/xsrf_token', { 'data': expected_attribs, 'headers': {'X-XSRF-Token-Request': '1'}, }, {'xsrf_token': 'token'}, ), ( 'https://localhost:1/swarming/api/v1/bot/task_error/23', { 'data': { 'id': expected_attribs['dimensions']['id'][0], 'message': 'error', 'task_id': 23, }, 'headers': {'X-XSRF-Token': 'token'}, }, {}, ), ]) botobj = bot_main.get_bot() bot_main.post_error_task(botobj, 'error', 23) def test_run_bot(self): # Test the run_bot() loop. Does not use self.bot. self.mock(time, 'time', lambda: 126.0) class Foo(Exception): pass def poll_server(botobj): sleep_streak = botobj.state['sleep_streak'] self.assertEqual(botobj.remote, self.server) if sleep_streak == 5: raise Exception('Jumping out of the loop') return False self.mock(bot_main, 'poll_server', poll_server) def post_error(botobj, e): self.assertEqual(self.server, botobj._remote) lines = e.splitlines() self.assertEqual('Jumping out of the loop', lines[0]) self.assertEqual('Traceback (most recent call last):', lines[1]) raise Foo('Necessary to get out of the loop') self.mock(bot.Bot, 'post_error', post_error) self.mock(bot_main, 'get_remote', lambda: self.server) self.expected_requests( [ ( 'https://localhost:1/swarming/api/v1/bot/server_ping', {}, 'foo', None, ), ]) with self.assertRaises(Foo): bot_main.run_bot(None) self.assertEqual( os_utilities.get_hostname_short(), os.environ['SWARMING_BOT_ID']) def test_poll_server_sleep(self): slept = [] self.mock(time, 'sleep', slept.append) self.mock(bot_main, 'run_manifest', self.fail) self.mock(bot_main, 'update_bot', self.fail) self.expected_requests( [ ( 'https://localhost:1/auth/api/v1/accounts/self/xsrf_token', {'data': {}, 'headers': {'X-XSRF-Token-Request': '1'}}, {'xsrf_token': 'token'}, ), ( 'https://localhost:1/swarming/api/v1/bot/poll', { 'data': self.attributes, 'headers': {'X-XSRF-Token': 'token'}, }, { 'cmd': 'sleep', 'duration': 1.24, }, ), ]) self.assertFalse(bot_main.poll_server(self.bot)) self.assertEqual([1.24], slept) def test_poll_server_run(self): manifest = [] self.mock(time, 'sleep', self.fail) self.mock(bot_main, 'run_manifest', lambda *args: manifest.append(args)) self.mock(bot_main, 'update_bot', self.fail) self.expected_requests( [ ( 'https://localhost:1/auth/api/v1/accounts/self/xsrf_token', {'data': {}, 'headers': {'X-XSRF-Token-Request': '1'}}, {'xsrf_token': 'token'}, ), ( 'https://localhost:1/swarming/api/v1/bot/poll', { 'data': self.bot._attributes, 'headers': {'X-XSRF-Token': 'token'}, }, { 'cmd': 'run', 'manifest': {'foo': 'bar'}, }, ), ]) self.assertTrue(bot_main.poll_server(self.bot)) expected = [(self.bot, {'foo': 'bar'}, time.time())] self.assertEqual(expected, manifest) def test_poll_server_update(self): update = [] self.mock(time, 'sleep', self.fail) self.mock(bot_main, 'run_manifest', self.fail) self.mock(bot_main, 'update_bot', lambda *args: update.append(args)) self.expected_requests( [ ( 'https://localhost:1/auth/api/v1/accounts/self/xsrf_token', {'data': {}, 'headers': {'X-XSRF-Token-Request': '1'}}, {'xsrf_token': 'token'}, ), ( 'https://localhost:1/swarming/api/v1/bot/poll', { 'data': self.attributes, 'headers': {'X-XSRF-Token': 'token'}, }, { 'cmd': 'update', 'version': '123', }, ), ]) self.assertTrue(bot_main.poll_server(self.bot)) self.assertEqual([(self.bot, '123')], update) def test_poll_server_restart(self): restart = [] self.mock(time, 'sleep', self.fail) self.mock(bot_main, 'run_manifest', self.fail) self.mock(bot_main, 'update_bot', self.fail) self.mock(self.bot, 'restart', lambda *args: restart.append(args)) self.expected_requests( [ ( 'https://localhost:1/auth/api/v1/accounts/self/xsrf_token', {'data': {}, 'headers': {'X-XSRF-Token-Request': '1'}}, {'xsrf_token': 'token'}, ), ( 'https://localhost:1/swarming/api/v1/bot/poll', { 'data': self.attributes, 'headers': {'X-XSRF-Token': 'token'}, }, { 'cmd': 'restart', 'message': 'Please die now', }, ), ]) self.assertTrue(bot_main.poll_server(self.bot)) self.assertEqual([('Please die now',)], restart) def test_poll_server_restart_load_test(self): os.environ['SWARMING_LOAD_TEST'] = '1' self.mock(time, 'sleep', self.fail) self.mock(bot_main, 'run_manifest', self.fail) self.mock(bot_main, 'update_bot', self.fail) self.mock(self.bot, 'restart', self.fail) self.expected_requests( [ ( 'https://localhost:1/auth/api/v1/accounts/self/xsrf_token', {'data': {}, 'headers': {'X-XSRF-Token-Request': '1'}}, {'xsrf_token': 'token'}, ), ( 'https://localhost:1/swarming/api/v1/bot/poll', { 'data': self.attributes, 'headers': {'X-XSRF-Token': 'token'}, }, { 'cmd': 'restart', 'message': 'Please die now', }, ), ]) self.assertTrue(bot_main.poll_server(self.bot)) def _mock_popen(self, returncode, url='https://localhost:1'): # Method should have "self" as first argument - pylint: disable=E0213 class Popen(object): def __init__(self2, cmd, cwd, env): self2.returncode = None expected = [ sys.executable, THIS_FILE, 'task_runner', '--swarming-server', url, '--file', os.path.join(self.root_dir, 'work', 'test_run.json'), '--cost-usd-hour', '3600.0', '--start', '100.0', ] self.assertEqual(expected, cmd) self.assertEqual(bot_main.ROOT_DIR, cwd) self.assertEqual('24', env['SWARMING_TASK_ID']) def poll(self2): self2.returncode = returncode return returncode def communicate(self2): self2.returncode = returncode return 'foo', None self.mock(subprocess, 'Popen', Popen) def test_run_manifest(self): self.mock(bot_main, 'post_error_task', lambda *args: self.fail(args)) def call_hook(botobj, name, *args): if name == 'on_after_task': failure, internal_failure = args self.assertEqual(self.attributes['dimensions'], botobj.dimensions) self.assertEqual(False, failure) self.assertEqual(False, internal_failure) self.mock(bot_main, 'call_hook', call_hook) self._mock_popen(0, url='https://localhost:3') manifest = { 'hard_timeout': 60, 'host': 'https://localhost:3', 'task_id': '24', } bot_main.run_manifest(self.bot, manifest, time.time()) def test_run_manifest_task_failure(self): self.mock(bot_main, 'post_error_task', self.fail) def call_hook(_botobj, name, *args): if name == 'on_after_task': failure, internal_failure = args self.assertEqual(True, failure) self.assertEqual(False, internal_failure) self.mock(bot_main, 'call_hook', call_hook) self._mock_popen(bot_main.TASK_FAILED) manifest = {'hard_timeout': 60, 'task_id': '24'} bot_main.run_manifest(self.bot, manifest, time.time()) def test_run_manifest_internal_failure(self): posted = [] self.mock(bot_main, 'post_error_task', lambda *args: posted.append(args)) def call_hook(_botobj, name, *args): if name == 'on_after_task': failure, internal_failure = args self.assertEqual(False, failure) self.assertEqual(True, internal_failure) self.mock(bot_main, 'call_hook', call_hook) self._mock_popen(1) manifest = {'hard_timeout': 60, 'task_id': '24'} bot_main.run_manifest(self.bot, manifest, time.time()) expected = [(self.bot, 'Execution failed, internal error.', '24')] self.assertEqual(expected, posted) def test_run_manifest_exception(self): posted = [] def post_error_task(botobj, msg, task_id): posted.append((botobj, msg.splitlines()[0], task_id)) self.mock(bot_main, 'post_error_task', post_error_task) def call_hook(_botobj, name, *args): if name == 'on_after_task': failure, internal_failure = args self.assertEqual(False, failure) self.assertEqual(True, internal_failure) self.mock(bot_main, 'call_hook', call_hook) def raiseOSError(*_a, **_k): raise OSError('Dang') self.mock(subprocess, 'Popen', raiseOSError) manifest = {'hard_timeout': 60, 'task_id': '24'} bot_main.run_manifest(self.bot, manifest, time.time()) expected = [(self.bot, 'Internal exception occured: Dang', '24')] self.assertEqual(expected, posted) def test_update_bot_linux(self): self.mock(sys, 'platform', 'linux2') # In a real case 'update_bot' never exits and doesn't call 'post_error'. # Under the test however forever-blocking calls finish, and post_error is # called. self.mock(self.bot, 'post_error', lambda *_: None) self.mock(bot_main, 'THIS_FILE', 'swarming_bot.1.zip') self.mock(net, 'url_retrieve', lambda *_: True) calls = [] cmd = [sys.executable, 'swarming_bot.2.zip', 'start_slave', '--survive'] self.mock(subprocess, 'Popen', self.fail) self.mock(os, 'execv', lambda *args: calls.append(args)) bot_main.update_bot(self.bot, '123') self.assertEqual([(sys.executable, cmd)], calls) def test_update_bot_win(self): self.mock(sys, 'platform', 'win32') # In a real case 'update_bot' never exists and doesn't call 'post_error'. # Under the test forever blocking calls self.mock(self.bot, 'post_error', lambda *_: None) self.mock(bot_main, 'THIS_FILE', 'swarming_bot.1.zip') self.mock(net, 'url_retrieve', lambda *_: True) calls = [] cmd = [sys.executable, 'swarming_bot.2.zip', 'start_slave', '--survive'] self.mock(subprocess, 'Popen', lambda *args: calls.append(args)) self.mock(os, 'execv', self.fail) with self.assertRaises(SystemExit): bot_main.update_bot(self.bot, '123') self.assertEqual([(cmd,)], calls) def test_get_config(self): expected = { u'server': u'http://localhost:8080', u'server_version': u'version1', } self.assertEqual(expected, bot_main.get_config()) def test_main(self): def check(x): self.assertEqual(logging.WARNING, x) self.mock(logging_utils, 'set_console_level', check) def run_bot(error): self.assertEqual(None, error) return 0 self.mock(bot_main, 'run_bot', run_bot) self.assertEqual(0, bot_main.main([])) if __name__ == '__main__': if '-v' in sys.argv: unittest.TestCase.maxDiff = None logging.basicConfig( level=logging.DEBUG if '-v' in sys.argv else logging.CRITICAL) unittest.main()
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'FileBlob.storage_options' db.delete_column(u'sentry_fileblob', 'storage_options') # Deleting field 'FileBlob.storage' db.delete_column(u'sentry_fileblob', 'storage') # Deleting field 'File.storage_options' db.delete_column(u'sentry_file', 'storage_options') # Deleting field 'File.storage' db.delete_column(u'sentry_file', 'storage') def backwards(self, orm): raise RuntimeError("Cannot reverse this migration. 'FileBlob.storage' and its values cannot be restored.") models = { 'sentry.activity': { 'Meta': {'object_name': 'Activity'}, 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {'null': 'True'}), 'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'event': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Event']", 'null': 'True'}), 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']", 'null': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'ident': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'type': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}), 'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'null': 'True'}) }, 'sentry.apikey': { 'Meta': {'object_name': 'ApiKey'}, 'allowed_origins': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32'}), 'label': ('django.db.models.fields.CharField', [], {'default': "'Default'", 'max_length': '64', 'blank': 'True'}), 'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'key_set'", 'to': "orm['sentry.Organization']"}), 'scopes': ('django.db.models.fields.BigIntegerField', [], {'default': 'None'}), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'db_index': 'True'}) }, 'sentry.auditlogentry': { 'Meta': {'object_name': 'AuditLogEntry'}, 'actor': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'blank': 'True', 'related_name': "'audit_actors'", 'null': 'True', 'to': "orm['sentry.User']"}), 'actor_key': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.ApiKey']", 'null': 'True', 'blank': 'True'}), 'actor_label': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}), 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}), 'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'event': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'ip_address': ('django.db.models.fields.GenericIPAddressField', [], {'max_length': '39', 'null': 'True'}), 'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Organization']"}), 'target_object': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'null': 'True'}), 'target_user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'blank': 'True', 'related_name': "'audit_targets'", 'null': 'True', 'to': "orm['sentry.User']"}) }, 'sentry.authidentity': { 'Meta': {'unique_together': "(('auth_provider', 'ident'), ('auth_provider', 'user'))", 'object_name': 'AuthIdentity'}, 'auth_provider': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.AuthProvider']"}), 'data': ('jsonfield.fields.JSONField', [], {'default': '{}'}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'ident': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'last_synced': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_verified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']"}) }, 'sentry.authprovider': { 'Meta': {'object_name': 'AuthProvider'}, 'config': ('jsonfield.fields.JSONField', [], {'default': '{}'}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'default_global_access': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'default_role': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '50'}), 'default_teams': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['sentry.Team']", 'symmetrical': 'False', 'blank': 'True'}), 'flags': ('django.db.models.fields.BigIntegerField', [], {'default': '0'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'last_sync': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Organization']", 'unique': 'True'}), 'provider': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'sync_time': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'null': 'True'}) }, 'sentry.broadcast': { 'Meta': {'object_name': 'Broadcast'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'date_expires': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2015, 12, 9, 0, 0)', 'null': 'True', 'blank': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}), 'link': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'message': ('django.db.models.fields.CharField', [], {'max_length': '256'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'upstream_id': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}) }, 'sentry.broadcastseen': { 'Meta': {'unique_together': "(('broadcast', 'user'),)", 'object_name': 'BroadcastSeen'}, 'broadcast': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Broadcast']"}), 'date_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']"}) }, 'sentry.event': { 'Meta': {'unique_together': "(('project', 'event_id'),)", 'object_name': 'Event', 'db_table': "'sentry_message'", 'index_together': "(('group', 'datetime'),)"}, 'data': ('sentry.db.models.fields.node.NodeField', [], {'null': 'True', 'blank': 'True'}), 'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}), 'event_id': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'db_column': "'message_id'"}), 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'blank': 'True', 'related_name': "'event_set'", 'null': 'True', 'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'message': ('django.db.models.fields.TextField', [], {}), 'num_comments': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'null': 'True'}), 'platform': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}), 'time_spent': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], {'null': 'True'}) }, 'sentry.eventmapping': { 'Meta': {'unique_together': "(('project', 'event_id'),)", 'object_name': 'EventMapping'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'event_id': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}) }, 'sentry.eventuser': { 'Meta': {'unique_together': "(('project', 'ident'), ('project', 'hash'))", 'object_name': 'EventUser', 'index_together': "(('project', 'email'), ('project', 'username'), ('project', 'ip_address'))"}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True'}), 'hash': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'ident': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True'}), 'ip_address': ('django.db.models.fields.GenericIPAddressField', [], {'max_length': '39', 'null': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'username': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True'}) }, 'sentry.file': { 'Meta': {'object_name': 'File'}, 'blob': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.FileBlob']", 'null': 'True'}), 'checksum': ('django.db.models.fields.CharField', [], {'max_length': '40', 'null': 'True'}), 'headers': ('jsonfield.fields.JSONField', [], {'default': '{}'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'path': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'size': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'null': 'True'}), 'timestamp': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}), 'type': ('django.db.models.fields.CharField', [], {'max_length': '64'}) }, 'sentry.fileblob': { 'Meta': {'object_name': 'FileBlob'}, 'checksum': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '40'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'path': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'size': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'null': 'True'}), 'timestamp': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}) }, 'sentry.group': { 'Meta': {'object_name': 'Group', 'db_table': "'sentry_groupedmessage'", 'index_together': "(('project', 'first_release'),)"}, 'active_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}), 'culprit': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'db_column': "'view'", 'blank': 'True'}), 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {'null': 'True', 'blank': 'True'}), 'first_release': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Release']", 'null': 'True'}), 'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'is_public': ('django.db.models.fields.NullBooleanField', [], {'default': 'False', 'null': 'True', 'blank': 'True'}), 'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}), 'level': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '40', 'db_index': 'True', 'blank': 'True'}), 'logger': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '64', 'db_index': 'True', 'blank': 'True'}), 'message': ('django.db.models.fields.TextField', [], {}), 'num_comments': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'null': 'True'}), 'platform': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}), 'resolved_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}), 'score': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], {'default': '0'}), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'db_index': 'True'}), 'time_spent_count': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], {'default': '0'}), 'time_spent_total': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], {'default': '0'}), 'times_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '1', 'db_index': 'True'}) }, 'sentry.groupassignee': { 'Meta': {'object_name': 'GroupAssignee', 'db_table': "'sentry_groupasignee'"}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'assignee_set'", 'unique': 'True', 'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'assignee_set'", 'to': "orm['sentry.Project']"}), 'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'sentry_assignee_set'", 'to': "orm['sentry.User']"}) }, 'sentry.groupbookmark': { 'Meta': {'unique_together': "(('project', 'user', 'group'),)", 'object_name': 'GroupBookmark'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True'}), 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'bookmark_set'", 'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'bookmark_set'", 'to': "orm['sentry.Project']"}), 'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'sentry_bookmark_set'", 'to': "orm['sentry.User']"}) }, 'sentry.groupemailthread': { 'Meta': {'unique_together': "(('email', 'group'), ('email', 'msgid'))", 'object_name': 'GroupEmailThread'}, 'date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'groupemail_set'", 'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'msgid': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'groupemail_set'", 'to': "orm['sentry.Project']"}) }, 'sentry.grouphash': { 'Meta': {'unique_together': "(('project', 'hash'),)", 'object_name': 'GroupHash'}, 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']", 'null': 'True'}), 'hash': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}) }, 'sentry.groupmeta': { 'Meta': {'unique_together': "(('group', 'key'),)", 'object_name': 'GroupMeta'}, 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'value': ('django.db.models.fields.TextField', [], {}) }, 'sentry.groupresolution': { 'Meta': {'object_name': 'GroupResolution'}, 'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}), 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']", 'unique': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'release': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Release']"}), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}) }, 'sentry.grouprulestatus': { 'Meta': {'unique_together': "(('rule', 'group'),)", 'object_name': 'GroupRuleStatus'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'last_active': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'rule': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Rule']"}), 'status': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}) }, 'sentry.groupseen': { 'Meta': {'unique_together': "(('user', 'group'),)", 'object_name': 'GroupSeen'}, 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'db_index': 'False'}) }, 'sentry.groupsnooze': { 'Meta': {'object_name': 'GroupSnooze'}, 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']", 'unique': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'until': ('django.db.models.fields.DateTimeField', [], {}) }, 'sentry.grouptagkey': { 'Meta': {'unique_together': "(('project', 'group', 'key'),)", 'object_name': 'GroupTagKey'}, 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}), 'values_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}) }, 'sentry.grouptagvalue': { 'Meta': {'unique_together': "(('project', 'key', 'value', 'group'),)", 'object_name': 'GroupTagValue', 'db_table': "'sentry_messagefiltervalue'"}, 'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}), 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'grouptag'", 'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'grouptag'", 'null': 'True', 'to': "orm['sentry.Project']"}), 'times_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'sentry.helppage': { 'Meta': {'object_name': 'HelpPage'}, 'content': ('django.db.models.fields.TextField', [], {}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'is_visible': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '64', 'unique': 'True', 'null': 'True'}), 'priority': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '50'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '64'}) }, 'sentry.lostpasswordhash': { 'Meta': {'object_name': 'LostPasswordHash'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'hash': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'unique': 'True'}) }, 'sentry.option': { 'Meta': {'object_name': 'Option'}, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '64'}), 'last_updated': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) }, 'sentry.organization': { 'Meta': {'object_name': 'Organization'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'default_role': ('django.db.models.fields.CharField', [], {'default': "'member'", 'max_length': '32'}), 'flags': ('django.db.models.fields.BigIntegerField', [], {'default': '1'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'members': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'org_memberships'", 'symmetrical': 'False', 'through': "orm['sentry.OrganizationMember']", 'to': "orm['sentry.User']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}) }, 'sentry.organizationaccessrequest': { 'Meta': {'unique_together': "(('team', 'member'),)", 'object_name': 'OrganizationAccessRequest'}, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'member': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.OrganizationMember']"}), 'team': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Team']"}) }, 'sentry.organizationmember': { 'Meta': {'unique_together': "(('organization', 'user'), ('organization', 'email'))", 'object_name': 'OrganizationMember'}, 'counter': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'flags': ('django.db.models.fields.BigIntegerField', [], {'default': '0'}), 'has_global_access': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'member_set'", 'to': "orm['sentry.Organization']"}), 'role': ('django.db.models.fields.CharField', [], {'default': "'member'", 'max_length': '32'}), 'teams': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['sentry.Team']", 'symmetrical': 'False', 'through': "orm['sentry.OrganizationMemberTeam']", 'blank': 'True'}), 'type': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '50', 'blank': 'True'}), 'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'blank': 'True', 'related_name': "'sentry_orgmember_set'", 'null': 'True', 'to': "orm['sentry.User']"}) }, 'sentry.organizationmemberteam': { 'Meta': {'unique_together': "(('team', 'organizationmember'),)", 'object_name': 'OrganizationMemberTeam', 'db_table': "'sentry_organizationmember_teams'"}, 'id': ('sentry.db.models.fields.bounded.BoundedAutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'organizationmember': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.OrganizationMember']"}), 'team': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Team']"}) }, 'sentry.organizationoption': { 'Meta': {'unique_together': "(('organization', 'key'),)", 'object_name': 'OrganizationOption', 'db_table': "'sentry_organizationoptions'"}, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Organization']"}), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) }, 'sentry.project': { 'Meta': {'unique_together': "(('team', 'slug'), ('organization', 'slug'))", 'object_name': 'Project'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'first_event': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Organization']"}), 'public': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'null': 'True'}), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'db_index': 'True'}), 'team': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Team']"}) }, 'sentry.projectkey': { 'Meta': {'object_name': 'ProjectKey'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'key_set'", 'to': "orm['sentry.Project']"}), 'public_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'unique': 'True', 'null': 'True'}), 'roles': ('django.db.models.fields.BigIntegerField', [], {'default': '1'}), 'secret_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'unique': 'True', 'null': 'True'}), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'db_index': 'True'}) }, 'sentry.projectoption': { 'Meta': {'unique_together': "(('project', 'key'),)", 'object_name': 'ProjectOption', 'db_table': "'sentry_projectoptions'"}, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) }, 'sentry.release': { 'Meta': {'unique_together': "(('project', 'version'),)", 'object_name': 'Release'}, 'data': ('jsonfield.fields.JSONField', [], {'default': '{}'}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'date_released': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'date_started': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'new_groups': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}), 'owner': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'null': 'True', 'blank': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'ref': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'version': ('django.db.models.fields.CharField', [], {'max_length': '64'}) }, 'sentry.releasefile': { 'Meta': {'unique_together': "(('release', 'ident'),)", 'object_name': 'ReleaseFile'}, 'file': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.File']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'ident': ('django.db.models.fields.CharField', [], {'max_length': '40'}), 'name': ('django.db.models.fields.TextField', [], {}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'release': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Release']"}) }, 'sentry.rule': { 'Meta': {'object_name': 'Rule'}, 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}) }, 'sentry.savedsearch': { 'Meta': {'unique_together': "(('project', 'name'),)", 'object_name': 'SavedSearch'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'query': ('django.db.models.fields.TextField', [], {}) }, 'sentry.tagkey': { 'Meta': {'unique_together': "(('project', 'key'),)", 'object_name': 'TagKey', 'db_table': "'sentry_filterkey'"}, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}), 'values_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}) }, 'sentry.tagvalue': { 'Meta': {'unique_together': "(('project', 'key', 'value'),)", 'object_name': 'TagValue', 'db_table': "'sentry_filtervalue'"}, 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {'null': 'True', 'blank': 'True'}), 'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}), 'times_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'sentry.team': { 'Meta': {'unique_together': "(('organization', 'slug'),)", 'object_name': 'Team'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Organization']"}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}) }, 'sentry.user': { 'Meta': {'object_name': 'User', 'db_table': "'auth_user'"}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedAutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_managed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128'}) }, 'sentry.useroption': { 'Meta': {'unique_together': "(('user', 'project', 'key'),)", 'object_name': 'UserOption'}, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}), 'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']"}), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) }, 'sentry.userreport': { 'Meta': {'object_name': 'UserReport', 'index_together': "(('project', 'event_id'),)"}, 'comments': ('django.db.models.fields.TextField', [], {}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'event_id': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']", 'null': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}) } } complete_apps = ['sentry']
# 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 socket import tempfile import json import paramiko from Crypto.PublicKey import RSA import novaclient.exceptions as novaexception from heat.common import exception from heat.openstack.common import log as logging from heat.openstack.common.gettextutils import _ from heat.engine import properties from heat.engine import scheduler from heat.engine.resources import instance from heat.engine.resources import nova_utils from heat.db.sqlalchemy import api as db_api try: import pyrax # noqa except ImportError: def resource_mapping(): return {} else: def resource_mapping(): return {'Rackspace::Cloud::Server': CloudServer} logger = logging.getLogger(__name__) class CloudServer(instance.Instance): """Resource for Rackspace Cloud Servers.""" PROPERTIES = ( FLAVOR, IMAGE, USER_DATA, KEY_NAME, VOLUMES, NAME, ) = ( 'flavor', 'image', 'user_data', 'key_name', 'Volumes', 'name', ) properties_schema = { FLAVOR: properties.Schema( properties.Schema.STRING, required=True, update_allowed=True ), IMAGE: properties.Schema( properties.Schema.STRING, required=True ), USER_DATA: properties.Schema( properties.Schema.STRING ), KEY_NAME: properties.Schema( properties.Schema.STRING ), VOLUMES: properties.Schema( properties.Schema.LIST, default=[] ), NAME: properties.Schema( properties.Schema.STRING ), } attributes_schema = {'PrivateDnsName': ('Private DNS name of the specified' ' instance.'), 'PublicDnsName': ('Public DNS name of the specified ' 'instance.'), 'PrivateIp': ('Private IP address of the specified ' 'instance.'), 'PublicIp': ('Public IP address of the specified ' 'instance.')} base_script = """#!/bin/bash # Install cloud-init and heat-cfntools %s # Create data source for cloud-init mkdir -p /var/lib/cloud/seed/nocloud-net mv /tmp/userdata /var/lib/cloud/seed/nocloud-net/user-data touch /var/lib/cloud/seed/nocloud-net/meta-data chmod 600 /var/lib/cloud/seed/nocloud-net/* # Run cloud-init & cfn-init cloud-init start || cloud-init init bash -x /var/lib/cloud/data/cfn-userdata > /root/cfn-userdata.log 2>&1 || exit 42 """ # - Ubuntu 12.04: Verified working ubuntu_script = base_script % """\ apt-get update export DEBIAN_FRONTEND=noninteractive apt-get install -y -o Dpkg::Options::="--force-confdef" -o \ Dpkg::Options::="--force-confold" cloud-init python-boto python-pip gcc \ python-dev pip install heat-cfntools cfn-create-aws-symlinks --source /usr/local/bin """ # - Fedora 17: Verified working # - Fedora 18: Not working. selinux needs to be in "Permissive" # mode for cloud-init to work. It's disabled by default in the # Rackspace Cloud Servers image. To enable selinux, a reboot is # required. # - Fedora 19: Verified working fedora_script = base_script % """\ yum install -y cloud-init python-boto python-pip gcc python-devel pip-python install heat-cfntools cfn-create-aws-symlinks """ # - Centos 6.4: Verified working centos_script = base_script % """\ if ! (yum repolist 2> /dev/null | egrep -q "^[\!\*]?epel "); then rpm -ivh http://mirror.rackspace.com/epel/6/i386/epel-release-6-8.noarch.rpm fi yum install -y cloud-init python-boto python-pip gcc python-devel \ python-argparse pip-python install heat-cfntools """ # - RHEL 6.4: Verified working rhel_script = base_script % """\ if ! (yum repolist 2> /dev/null | egrep -q "^[\!\*]?epel "); then rpm -ivh http://mirror.rackspace.com/epel/6/i386/epel-release-6-8.noarch.rpm fi # The RPM DB stays locked for a few secs while fuser /var/lib/rpm/*; do sleep 1; done yum install -y cloud-init python-boto python-pip gcc python-devel \ python-argparse pip-python install heat-cfntools cfn-create-aws-symlinks """ debian_script = base_script % """\ echo "deb http://mirror.rackspace.com/debian wheezy-backports main" >> \ /etc/apt/sources.list apt-get update apt-get -t wheezy-backports install -y cloud-init export DEBIAN_FRONTEND=noninteractive apt-get install -y -o Dpkg::Options::="--force-confdef" -o \ Dpkg::Options::="--force-confold" python-pip gcc python-dev pip install heat-cfntools """ # - Arch 2013.6: Not working (deps not in default package repos) # TODO(jason): Install cloud-init & other deps from third-party repos arch_script = base_script % """\ pacman -S --noconfirm python-pip gcc """ # - Gentoo 13.2: Not working (deps not in default package repos) # TODO(jason): Install cloud-init & other deps from third-party repos gentoo_script = base_script % """\ emerge cloud-init python-boto python-pip gcc python-devel """ # - OpenSUSE 12.3: Not working (deps not in default package repos) # TODO(jason): Install cloud-init & other deps from third-party repos opensuse_script = base_script % """\ zypper --non-interactive rm patterns-openSUSE-minimal_base-conflicts zypper --non-interactive in cloud-init python-boto python-pip gcc python-devel """ # List of supported Linux distros and their corresponding config scripts image_scripts = {'arch': None, 'centos': centos_script, 'debian': None, 'fedora': fedora_script, 'gentoo': None, 'opensuse': None, 'rhel': rhel_script, 'ubuntu': ubuntu_script} script_error_msg = (_("The %(path)s script exited with a non-zero exit " "status. To see the error message, log into the " "server and view %(log)s")) # Template keys supported for handle_update. Properties not # listed here trigger an UpdateReplace update_allowed_keys = ('Metadata', 'Properties') def __init__(self, name, json_snippet, stack): super(CloudServer, self).__init__(name, json_snippet, stack) self.stack = stack self._private_key = None self._server = None self._distro = None self._public_ip = None self._private_ip = None self._flavor = None self._image = None @property def server(self): """Get the Cloud Server object.""" if not self._server: logger.debug(_("Calling nova().servers.get()")) self._server = self.nova().servers.get(self.resource_id) return self._server @property def distro(self): """Get the Linux distribution for this server.""" if not self._distro: logger.debug(_("Calling nova().images.get()")) image_data = self.nova().images.get(self.image) self._distro = image_data.metadata['os_distro'] return self._distro @property def script(self): """Get the config script for the Cloud Server image.""" return self.image_scripts[self.distro] @property def flavor(self): """Get the flavors from the API.""" if not self._flavor: flavor = self.properties[self.FLAVOR] self._flavor = nova_utils.get_flavor_id(self.nova(), flavor) return self._flavor @property def image(self): if not self._image: self._image = nova_utils.get_image_id(self.nova(), self.properties[self.IMAGE]) return self._image @property def private_key(self): """Return the private SSH key for the resource.""" if self._private_key: return self._private_key if self.id is not None: private_key = db_api.resource_data_get(self, 'private_key') if not private_key: return None self._private_key = private_key return private_key @private_key.setter def private_key(self, private_key): """Save the resource's private SSH key to the database.""" self._private_key = private_key if self.id is not None: db_api.resource_data_set(self, 'private_key', private_key, True) def _get_ip(self, ip_type): """Return the IP of the Cloud Server.""" if ip_type in self.server.addresses: for ip in self.server.addresses[ip_type]: if ip['version'] == 4: return ip['addr'] raise exception.Error(_("Could not determine the %(ip)s IP of " "%(image)s.") % {'ip': ip_type, 'image': self.properties[self.IMAGE]}) @property def public_ip(self): """Return the public IP of the Cloud Server.""" if not self._public_ip: self._public_ip = self._get_ip('public') return self._public_ip @property def private_ip(self): """Return the private IP of the Cloud Server.""" if not self._private_ip: self._private_ip = self._get_ip('private') return self._private_ip @property def has_userdata(self): if self.properties[self.USER_DATA] or self.metadata != {}: return True else: return False def validate(self): """Validate user parameters.""" self.flavor self.image # It's okay if there's no script, as long as user_data and # metadata are empty if not self.script and self.has_userdata: return {'Error': "user_data/metadata are not supported for image" " %s." % self.properties[self.IMAGE]} def _run_ssh_command(self, command): """Run a shell command on the Cloud Server via SSH.""" with tempfile.NamedTemporaryFile() as private_key_file: private_key_file.write(self.private_key) private_key_file.seek(0) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy()) ssh.connect(self.public_ip, username="root", key_filename=private_key_file.name) chan = ssh.get_transport().open_session() chan.settimeout(self.stack.timeout_mins * 60.0) chan.exec_command(command) try: # The channel timeout only works for read/write operations chan.recv(1024) except socket.timeout: raise exception.Error("SSH command timed out after %s minutes" % self.stack.timeout_mins) else: return chan.recv_exit_status() finally: ssh.close() chan.close() def _sftp_files(self, files): """Transfer files to the Cloud Server via SFTP.""" with tempfile.NamedTemporaryFile() as private_key_file: private_key_file.write(self.private_key) private_key_file.seek(0) pkey = paramiko.RSAKey.from_private_key_file(private_key_file.name) transport = paramiko.Transport((self.public_ip, 22)) transport.connect(hostkey=None, username="root", pkey=pkey) sftp = paramiko.SFTPClient.from_transport(transport) try: for remote_file in files: sftp_file = sftp.open(remote_file['path'], 'w') sftp_file.write(remote_file['data']) sftp_file.close() except: raise finally: sftp.close() transport.close() def handle_create(self): """Create a Rackspace Cloud Servers container. Rackspace Cloud Servers does not have the metadata service running, so we have to transfer the user-data file to the server and then trigger cloud-init. """ # Generate SSH public/private keypair if self._private_key is not None: rsa = RSA.importKey(self._private_key) else: rsa = RSA.generate(1024) self.private_key = rsa.exportKey() public_keys = [rsa.publickey().exportKey('OpenSSH')] if self.properties.get(self.KEY_NAME): key_name = self.properties[self.KEY_NAME] public_keys.append(nova_utils.get_keypair(self.nova(), key_name).public_key) personality_files = { "/root/.ssh/authorized_keys": '\n'.join(public_keys)} # Create server client = self.nova().servers logger.debug(_("Calling nova().servers.create()")) server = client.create(self.physical_resource_name(), self.image, self.flavor, files=personality_files) # Save resource ID to db self.resource_id_set(server.id) return server, scheduler.TaskRunner(self._attach_volumes_task()) def _attach_volumes_task(self): tasks = (scheduler.TaskRunner(self._attach_volume, volume_id, device) for volume_id, device in self.volumes()) return scheduler.PollingTaskGroup(tasks) def _attach_volume(self, volume_id, device): logger.debug(_("Calling nova().volumes.create_server_volume()")) self.nova().volumes.create_server_volume(self.server.id, volume_id, device or None) yield volume = self.cinder().get(volume_id) while volume.status in ('available', 'attaching'): yield volume.get() if volume.status != 'in-use': raise exception.Error(volume.status) def _detach_volumes_task(self): tasks = (scheduler.TaskRunner(self._detach_volume, volume_id) for volume_id, device in self.volumes()) return scheduler.PollingTaskGroup(tasks) def _detach_volume(self, volume_id): volume = self.cinder().get(volume_id) volume.detach() yield while volume.status in ('in-use', 'detaching'): yield volume.get() if volume.status != 'available': raise exception.Error(volume.status) def check_create_complete(self, cookie): """Check if server creation is complete and handle server configs.""" if not super(CloudServer, self).check_create_complete(cookie): return False server = cookie[0] server.get() if 'rack_connect' in self.context.roles: # Account has RackConnect if 'rackconnect_automation_status' not in server.metadata: logger.debug(_("RackConnect server does not have the " "rackconnect_automation_status metadata tag " "yet")) return False rc_status = server.metadata['rackconnect_automation_status'] logger.debug(_("RackConnect automation status: ") + rc_status) if rc_status == 'DEPLOYING': return False elif rc_status == 'DEPLOYED': self._public_ip = None # The public IP changed, forget old one elif rc_status == 'FAILED': raise exception.Error(_("RackConnect automation FAILED")) elif rc_status == 'UNPROCESSABLE': reason = server.metadata.get( "rackconnect_unprocessable_reason", None) if reason is not None: logger.warning(_("RackConnect unprocessable reason: ") + reason) # UNPROCESSABLE means the RackConnect automation was # not attempted (eg. Cloud Server in a different DC # than dedicated gear, so RackConnect does not apply). # It is okay if we do not raise an exception. else: raise exception.Error(_("Unknown RackConnect automation " "status: ") + rc_status) if 'rax_managed' in self.context.roles: # Managed Cloud account if 'rax_service_level_automation' not in server.metadata: logger.debug(_("Managed Cloud server does not have the " "rax_service_level_automation metadata tag yet")) return False mc_status = server.metadata['rax_service_level_automation'] logger.debug(_("Managed Cloud automation status: ") + mc_status) if mc_status == 'In Progress': return False elif mc_status == 'Complete': pass elif mc_status == 'Build Error': raise exception.Error(_("Managed Cloud automation failed")) else: raise exception.Error(_("Unknown Managed Cloud automation " "status: ") + mc_status) if self.has_userdata: # Create heat-script and userdata files on server raw_userdata = self.properties[self.USER_DATA] or '' userdata = nova_utils.build_userdata(self, raw_userdata) files = [{'path': "/tmp/userdata", 'data': userdata}, {'path': "/root/heat-script.sh", 'data': self.script}] self._sftp_files(files) # Connect via SSH and run script cmd = "bash -ex /root/heat-script.sh > /root/heat-script.log 2>&1" exit_code = self._run_ssh_command(cmd) if exit_code == 42: raise exception.Error(self.script_error_msg % {'path': "cfn-userdata", 'log': "/root/cfn-userdata.log"}) elif exit_code != 0: raise exception.Error(self.script_error_msg % {'path': "heat-script.sh", 'log': "/root/heat-script.log"}) return True # TODO(jason): Make this consistent with Instance and inherit def _delete_server(self, server): """Return a coroutine that deletes the Cloud Server.""" server.delete() while True: yield try: server.get() if server.status == "DELETED": break elif server.status == "ERROR": raise exception.Error(_("Deletion of server %s failed.") % server.name) except novaexception.NotFound: break def handle_update(self, json_snippet, tmpl_diff, prop_diff): """Try to update a Cloud Server's parameters. If the Cloud Server's Metadata or flavor changed, update the Cloud Server. If any other parameters changed, re-create the Cloud Server with the new parameters. """ if 'Metadata' in tmpl_diff: self.metadata = json_snippet['Metadata'] metadata_string = json.dumps(self.metadata) files = [{'path': "/var/cache/heat-cfntools/last_metadata", 'data': metadata_string}] self._sftp_files(files) command = "bash -x /var/lib/cloud/data/cfn-userdata > " + \ "/root/cfn-userdata.log 2>&1" exit_code = self._run_ssh_command(command) if exit_code != 0: raise exception.Error(self.script_error_msg % {'path': "cfn-userdata", 'log': "/root/cfn-userdata.log"}) if self.FLAVOR in prop_diff: flav = json_snippet['Properties'][self.FLAVOR] new_flavor = nova_utils.get_flavor_id(self.nova(), flav) self.server.resize(new_flavor) resize = scheduler.TaskRunner(nova_utils.check_resize, self.server, flav) resize.start() return resize def _resolve_attribute(self, key): """Return the method that provides a given template attribute.""" attribute_function = {'PublicIp': self.public_ip, 'PrivateIp': self.private_ip, 'PublicDnsName': self.public_ip, 'PrivateDnsName': self.public_ip} if key not in attribute_function: raise exception.InvalidTemplateAttribute(resource=self.name, key=key) function = attribute_function[key] logger.info('%s._resolve_attribute(%s) == %s' % (self.name, key, function)) return unicode(function)
import collections import logging import os import subprocess import tempfile class TrackCompositor(object): def __init__(self, dataHub, title=None): # def __init__(self, width, title=None): self.dataHub = dataHub self.sections = collections.OrderedDict() self.width = 1200 self.title = title self.descriptions = [] self.marginTopBottom = 20 self.sectionLabelHeight = 32 self.betweenSectionHeight = 30 self.trackLabelHeight = 20 self._fromDataHub() def _fromDataHub(self): if self.title is None: self.title = str(self.dataHub.variant) for longAlleleName in ["Alternate Allele", "Reference Allele"]: allele = longAlleleName[:3].lower() sampleNames = self.dataHub.samples.keys() tracks = [sample.tracks[allele] for sample in self.dataHub] self.addTracks(longAlleleName, sampleNames, tracks, allele) def getBounds(self, tracks, allele): """ calculate left and right bounds for the allele; this is based on the variant segments as well as the positions of the reads (we want to be able to see all the breakpoints as well as all the reads) """ scale = tracks[0].scale # bail if there are multiple sections; could do this more nicely if len(self.dataHub.variant.chromParts(allele).parts) > 1: return 0, scale.pixelWidth segments = list(self.dataHub.variant.chromParts(allele))[0].segments alleleLength = len(list(self.dataHub.variant.chromParts(allele))[0]) if self.dataHub.args.context>0: begin = scale.topixels(len(segments[0])-self.dataHub.args.context) width = scale.topixels(sum(len(s) for s in segments[:-1])+self.dataHub.args.context) - begin return begin, width axisMin = max(0, scale.topixels(len(segments[0])-100)) axisMax = scale.topixels(min(alleleLength-len(segments[-1])+100, alleleLength)) for track in tracks: track.render() xmin = [track.xmin for track in tracks if track.xmin is not None] xmin = min(xmin) if len(xmin) > 0 else 0 xmin = min(axisMin, xmin) xmax = [track.xmax for track in tracks if track.xmax is not None] xmax = max(xmax) if len(xmax) > 0 else 500 xmax = max(axisMax, xmax) width = 500 if xmin is not None: width = xmax - xmin xmin -= width * 0.05 xmin = max(0, xmin) width *= 1.1 width = min(width, xmin+scale.topixels(alleleLength)) return xmin, width def addTracks(self, section, names, tracks, allele): alleleTracks = self.dataHub.alleleTracks[allele] for track in tracks: track.render() xmin, width = self.getBounds(tracks, allele) hasTrackWithReads = False for track, name in zip(tracks, names): if len(track.alignmentSets) == 0: height = 20 viewbox = '0 0 {width} {height}" preserveAspectRatio="xMinYMin'.format(width=track.width, height=track.height) else: hasTrackWithReads = True # this is for proportional scaling # height = float(track.height+40) * self.width / width # preserveAspectRatio="xMinYMin" height = float(track.height+40)/2.0 preserveAspectRatio="none" viewbox = '{xmin} -20 {width} {height}" preserveAspectRatio="{par}'.format(xmin=xmin, width=width, height=track.height+40, par=preserveAspectRatio) self.addTrackSVG(section, name, track.svg.asString("export"), height=height, viewbox=viewbox) # if hasTrackWithReads: if True: scaleFactor = float(width) / self.width size = 1.0 if self.dataHub.args.thicker_lines: size *= 2.0 for name, track in alleleTracks.iteritems(): # this is awkward: baseHeight() and imageHeight are used # for Axis tracks but not Annotation tracks imageHeight = width * (track.baseHeight()/float(self.width)) track.render(scaleFactor=scaleFactor, height=imageHeight, thickerLines=self.dataHub.args.thicker_lines) height = track.height/scaleFactor viewbox = '{xmin} 0 {width} {height}" preserveAspectRatio="{par}'.format(xmin=xmin, width=width, height=track.height, par="none") svg = track.svg.asString("export") self.addTrackSVG(section, name, svg, height=track.baseHeight(),#height, viewbox=viewbox) def addTrackSVG(self, section, name, tracksvg, viewbox=None, height=100): if not section in self.sections: self.sections[section] = collections.OrderedDict() self.sections[section][name] = {"svg":tracksvg, "viewbox":viewbox, "height": height } def _svgText(self, x, y, text, height, bold=False, anchor=None): extras = "" if bold: extras += ' font-weight="bold"' if anchor: extras += ' anchor="{}"'.format(anchor) svg = '<svg x="{x}" y="{y}"><text x="0" y="{padded}" font-size="{textHeight}" font-family="Helvetica" {extras}>{text}</text></svg>'.format(x=x, y=y, padded=height, textHeight=(height-2), text=text, extras=extras) return svg def renderCountsTable(self, modTracks, ystart, fontsize=18): charWidth = fontsize/2 ystart += 5 counts = self.dataHub.getCounts() columns = ["Sample", "Alt", "Ref", "Amb"] columnWidths = [] longestRowHeader = max(max(counts, key=lambda x: len(x)), len(columns[0])) columnWidths.append(len(longestRowHeader)*charWidth) columnWidths.extend([7*charWidth]*3) rows = [columns] for sample, curcounts in counts.iteritems(): rows.append([sample, curcounts["alt"], curcounts["ref"], curcounts["amb"]]) for i, row in enumerate(rows): xstart = 10 for j, value in enumerate(row): width = columnWidths[j] if j == 0: # row header modTracks.append(self._svgText(xstart, ystart, value, fontsize, bold=True, anchor="start")) xstart += width else: xstart += width modTracks.append(self._svgText(xstart, ystart, value, fontsize, bold=i==0, anchor="end")) ystart += fontsize * 1.25 return ystart + 10 # self.descriptions.append("{}: {} {} {}".format(name, curcounts["alt"], curcounts["ref"], curcounts["amb"])) def render(self): modTracks = [] curX = 0 curY = self.marginTopBottom if self.title is not None: header = self._svgText(curX+10, curY, self.title, self.sectionLabelHeight+5, bold=True) modTracks.append(header) curY += self.sectionLabelHeight+10 curY = self.renderCountsTable(modTracks, curY) # for description in self.descriptions: # header = self._svgText(curX+20, curY, description, self.trackLabelHeight) # modTracks.append(header) # curY += self.trackLabelHeight+5 for i, sectionName in enumerate(self.sections): section = self.sections[sectionName] if i > 0: curY += self.betweenSectionHeight label = self._svgText(curX+10, curY, sectionName, self.sectionLabelHeight) modTracks.append(label) curY += self.sectionLabelHeight for trackName in section: trackInfo = section[trackName] if trackName != "axis": label = self._svgText(curX+10, curY, trackName, self.trackLabelHeight) modTracks.append(label) curY += self.sectionLabelHeight extra = 'svg x="{}" y="{}" width="{}" height="{}"'.format(curX, curY, self.width, trackInfo["height"]) if trackInfo["viewbox"] is not None: extra += ' viewBox="{}"'.format(trackInfo["viewbox"]) mod = trackInfo["svg"].replace("svg", extra, 1) modTracks.append(mod) curY += trackInfo["height"] curY += self.marginTopBottom composite = ['<?xml version="1.0" encoding="utf-8" ?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="{}" height="{}">'.format(self.width, curY)] \ + modTracks + ["</svg>"] return "\n".join(composite) def canConvertSVGToPDF(): try: subprocess.check_call("webkitToPDF", stderr=subprocess.PIPE, shell=True) return True except subprocess.CalledProcessError: try: subprocess.check_call("rsvg-convert -v", stdout=subprocess.PIPE, shell=True) except subprocess.CalledProcessError: return False else: return True def convertSVG(insvg, outformat="pdf"): if not canConvertSVGToPDF(): logging.error("Can't find rsvg-convert; make sure you have librsvg installed") return None outdir = tempfile.mkdtemp() inpath = "{}/original.svg".format(outdir) infile = open(inpath, "w") infile.write(insvg) infile.flush() infile.close() outpath = "{}/converted.{}".format(outdir, outformat) exportData = _convertSVG_webkitToPDF(inpath, outpath, outformat) if exportData is not None: print "used webkitToPDF to export to PDF" return exportData else: exportData = _convertSVG_rsvg_convert(inpath, outpath, outformat) print "used rsvg-convert to export to PDF" return exportData def _convertSVG_webkitToPDF(inpath, outpath, outformat): if outformat.lower() != "pdf": return None try: cmd = "webkitToPDF {} {}".format(inpath, outpath) subprocess.check_call(cmd, shell=True)#, stderr=subprocess.PIPE) except subprocess.CalledProcessError: return None return open(outpath).read() def _convertSVG_rsvg_convert(inpath, outpath, outformat): options = "" outformat = outformat.lower() if outformat == "png": options = "-a -w 5000 --background-color white" try: subprocess.check_call("rsvg-convert -f {} {} -o {} {}".format(outformat, options, outpath, inpath), shell=True) except subprocess.CalledProcessError, e: print "EXPORT ERROR:", str(e) return open(outpath).read() def test(): base = """ <svg><rect x="10" y="10" height="100" width="100" style="stroke:#ffff00; stroke-width:3; fill: #0000ff"/><text x="25" y="25" fill="blue">{}</text></svg>""" svgs = [base.format("track {}".format(i)) for i in range(5)] tc = TrackCompositor(200, 600) for i, svg in enumerate(svgs): tc.addTrack(svg, i, viewbox="0 0 110 110") outf = open("temp.svg", "w") outf.write(tc.render()) outf.flush() outf.close() pdfPath = convertSVGToPDF("temp.svg") subprocess.check_call("open {}".format(pdfPath), shell=True) if __name__ == '__main__': test() import sys print >>sys.stderr, canConvertSVGToPDF()
import six from locust.core import HttpLocust, Locust, TaskSet, task, events from locust import ResponseError, InterruptTaskSet from locust.exception import CatchResponseError, RescheduleTask, RescheduleTaskImmediately, LocustError from .testcases import LocustTestCase, WebserverTestCase class TestTaskSet(LocustTestCase): def setUp(self): super(TestTaskSet, self).setUp() class User(Locust): host = "127.0.0.1" self.locust = User() def test_task_ratio(self): t1 = lambda l: None t2 = lambda l: None class MyTasks(TaskSet): tasks = {t1:5, t2:2} l = MyTasks(self.locust) t1_count = len([t for t in l.tasks if t == t1]) t2_count = len([t for t in l.tasks if t == t2]) self.assertEqual(t1_count, 5) self.assertEqual(t2_count, 2) def test_task_decorator_ratio(self): t1 = lambda l: None t2 = lambda l: None class MyTasks(TaskSet): tasks = {t1:5, t2:2} host = "" @task(3) def t3(self): pass @task(13) def t4(self): pass l = MyTasks(self.locust) t1_count = len([t for t in l.tasks if t == t1]) t2_count = len([t for t in l.tasks if t == t2]) t3_count = len([t for t in l.tasks if t.__name__ == MyTasks.t3.__name__]) t4_count = len([t for t in l.tasks if t.__name__ == MyTasks.t4.__name__]) self.assertEqual(t1_count, 5) self.assertEqual(t2_count, 2) self.assertEqual(t3_count, 3) self.assertEqual(t4_count, 13) def test_on_start(self): class MyTasks(TaskSet): t1_executed = False t2_executed = False def on_start(self): self.t1() def t1(self): self.t1_executed = True @task def t2(self): self.t2_executed = True raise InterruptTaskSet(reschedule=False) l = MyTasks(self.locust) self.assertRaises(RescheduleTask, lambda: l.run()) self.assertTrue(l.t1_executed) self.assertTrue(l.t2_executed) def test_schedule_task(self): self.t1_executed = False self.t2_arg = None def t1(l): self.t1_executed = True def t2(l, arg): self.t2_arg = arg class MyTasks(TaskSet): tasks = [t1, t2] taskset = MyTasks(self.locust) taskset.schedule_task(t1) taskset.execute_next_task() self.assertTrue(self.t1_executed) taskset.schedule_task(t2, args=["argument to t2"]) taskset.execute_next_task() self.assertEqual("argument to t2", self.t2_arg) def test_schedule_task_with_kwargs(self): class MyTasks(TaskSet): @task def t1(self): self.t1_executed = True @task def t2(self, *args, **kwargs): self.t2_args = args self.t2_kwargs = kwargs loc = MyTasks(self.locust) loc.schedule_task(loc.t2, [42], {"test_kw":"hello"}) loc.execute_next_task() self.assertEqual((42, ), loc.t2_args) self.assertEqual({"test_kw":"hello"}, loc.t2_kwargs) loc.schedule_task(loc.t2, args=[10, 4], kwargs={"arg1":1, "arg2":2}) loc.execute_next_task() self.assertEqual((10, 4), loc.t2_args) self.assertEqual({"arg1":1, "arg2":2}, loc.t2_kwargs) def test_schedule_task_bound_method(self): class MyTasks(TaskSet): host = "" @task() def t1(self): self.t1_executed = True self.schedule_task(self.t2) def t2(self): self.t2_executed = True taskset = MyTasks(self.locust) taskset.schedule_task(taskset.get_next_task()) taskset.execute_next_task() self.assertTrue(taskset.t1_executed) taskset.execute_next_task() self.assertTrue(taskset.t2_executed) def test_taskset_inheritance(self): def t1(l): pass class MyBaseTaskSet(TaskSet): tasks = [t1] host = "" class MySubTaskSet(MyBaseTaskSet): @task def t2(self): pass l = MySubTaskSet(self.locust) self.assertEqual(2, len(l.tasks)) self.assertEqual([t1, six.get_unbound_function(MySubTaskSet.t2)], l.tasks) def test_task_decorator_with_or_without_argument(self): class MyTaskSet(TaskSet): @task def t1(self): pass taskset = MyTaskSet(self.locust) self.assertEqual(len(taskset.tasks), 1) class MyTaskSet2(TaskSet): @task() def t1(self): pass taskset = MyTaskSet2(self.locust) self.assertEqual(len(taskset.tasks), 1) class MyTaskSet3(TaskSet): @task(3) def t1(self): pass taskset = MyTaskSet3(self.locust) self.assertEqual(len(taskset.tasks), 3) def test_sub_taskset(self): class MySubTaskSet(TaskSet): min_wait = 1 max_wait = 1 @task() def a_task(self): self.locust.sub_locust_task_executed = True self.interrupt() class MyTaskSet(TaskSet): tasks = [MySubTaskSet] self.sub_locust_task_executed = False loc = MyTaskSet(self.locust) loc.schedule_task(loc.get_next_task()) self.assertRaises(RescheduleTaskImmediately, lambda: loc.execute_next_task()) self.assertTrue(self.locust.sub_locust_task_executed) def test_sub_taskset_tasks_decorator(self): class MyTaskSet(TaskSet): @task class MySubTaskSet(TaskSet): min_wait = 1 max_wait = 1 @task() def a_task(self): self.locust.sub_locust_task_executed = True self.interrupt() self.sub_locust_task_executed = False loc = MyTaskSet(self.locust) loc.schedule_task(loc.get_next_task()) self.assertRaises(RescheduleTaskImmediately, lambda: loc.execute_next_task()) self.assertTrue(self.locust.sub_locust_task_executed) def test_sub_taskset_arguments(self): class MySubTaskSet(TaskSet): min_wait = 1 max_wait = 1 @task() def a_task(self): self.locust.sub_taskset_args = self.args self.locust.sub_taskset_kwargs = self.kwargs self.interrupt() class MyTaskSet(TaskSet): sub_locust_args = None sub_locust_kwargs = None tasks = [MySubTaskSet] self.locust.sub_taskset_args = None self.locust.sub_taskset_kwargs = None loc = MyTaskSet(self.locust) loc.schedule_task(MySubTaskSet, args=[1,2,3], kwargs={"hello":"world"}) self.assertRaises(RescheduleTaskImmediately, lambda: loc.execute_next_task()) self.assertEqual((1,2,3), self.locust.sub_taskset_args) self.assertEqual({"hello":"world"}, self.locust.sub_taskset_kwargs) def test_interrupt_taskset_in_main_taskset(self): class MyTaskSet(TaskSet): @task def interrupted_task(self): raise InterruptTaskSet(reschedule=False) class MyLocust(Locust): host = "http://127.0.0.1" task_set = MyTaskSet class MyTaskSet2(TaskSet): @task def interrupted_task(self): self.interrupt() class MyLocust2(Locust): host = "http://127.0.0.1" task_set = MyTaskSet2 l = MyLocust() l2 = MyLocust2() self.assertRaises(LocustError, lambda: l.run()) self.assertRaises(LocustError, lambda: l2.run()) try: l.run() except LocustError as e: self.assertTrue("MyLocust" in e.args[0], "MyLocust should have been referred to in the exception message") self.assertTrue("MyTaskSet" in e.args[0], "MyTaskSet should have been referred to in the exception message") except: raise try: l2.run() except LocustError as e: self.assertTrue("MyLocust2" in e.args[0], "MyLocust2 should have been referred to in the exception message") self.assertTrue("MyTaskSet2" in e.args[0], "MyTaskSet2 should have been referred to in the exception message") except: raise def test_on_start_interrupt(self): class SubTaskSet(TaskSet): def on_start(self): if self.kwargs["reschedule"]: self.interrupt(reschedule=True) else: self.interrupt(reschedule=False) class MyLocust(Locust): host = "" task_set = SubTaskSet l = MyLocust() task_set = SubTaskSet(l) self.assertRaises(RescheduleTaskImmediately, lambda: task_set.run(reschedule=True)) self.assertRaises(RescheduleTask, lambda: task_set.run(reschedule=False)) def test_parent_attribute(self): from locust.exception import StopLocust parents = {} class SubTaskSet(TaskSet): def on_start(self): parents["sub"] = self.parent @task class SubSubTaskSet(TaskSet): def on_start(self): parents["subsub"] = self.parent @task def stop(self): raise StopLocust() class RootTaskSet(TaskSet): tasks = [SubTaskSet] class MyLocust(Locust): host = "" task_set = RootTaskSet l = MyLocust() l.run() self.assertTrue(isinstance(parents["sub"], RootTaskSet)) self.assertTrue(isinstance(parents["subsub"], SubTaskSet)) class TestWebLocustClass(WebserverTestCase): def test_get_request(self): self.response = "" def t1(l): self.response = l.client.get("/ultra_fast") class MyLocust(HttpLocust): tasks = [t1] host = "http://127.0.0.1:%i" % self.port my_locust = MyLocust() t1(my_locust) self.assertEqual(self.response.text, "This is an ultra fast response") def test_client_request_headers(self): class MyLocust(HttpLocust): host = "http://127.0.0.1:%i" % self.port locust = MyLocust() self.assertEqual("hello", locust.client.get("/request_header_test", headers={"X-Header-Test":"hello"}).text) def test_client_get(self): class MyLocust(HttpLocust): host = "http://127.0.0.1:%i" % self.port locust = MyLocust() self.assertEqual("GET", locust.client.get("/request_method").text) def test_client_get_absolute_url(self): class MyLocust(HttpLocust): host = "http://127.0.0.1:%i" % self.port locust = MyLocust() self.assertEqual("GET", locust.client.get("http://127.0.0.1:%i/request_method" % self.port).text) def test_client_post(self): class MyLocust(HttpLocust): host = "http://127.0.0.1:%i" % self.port locust = MyLocust() self.assertEqual("POST", locust.client.post("/request_method", {"arg":"hello world"}).text) self.assertEqual("hello world", locust.client.post("/post", {"arg":"hello world"}).text) def test_client_put(self): class MyLocust(HttpLocust): host = "http://127.0.0.1:%i" % self.port locust = MyLocust() self.assertEqual("PUT", locust.client.put("/request_method", {"arg":"hello world"}).text) self.assertEqual("hello world", locust.client.put("/put", {"arg":"hello world"}).text) def test_client_delete(self): class MyLocust(HttpLocust): host = "http://127.0.0.1:%i" % self.port locust = MyLocust() self.assertEqual("DELETE", locust.client.delete("/request_method").text) self.assertEqual(200, locust.client.delete("/request_method").status_code) def test_client_head(self): class MyLocust(HttpLocust): host = "http://127.0.0.1:%i" % self.port locust = MyLocust() self.assertEqual(200, locust.client.head("/request_method").status_code) def test_client_basic_auth(self): class MyLocust(HttpLocust): host = "http://127.0.0.1:%i" % self.port class MyAuthorizedLocust(HttpLocust): host = "http://locust:menace@127.0.0.1:%i" % self.port class MyUnauthorizedLocust(HttpLocust): host = "http://locust:wrong@127.0.0.1:%i" % self.port locust = MyLocust() unauthorized = MyUnauthorizedLocust() authorized = MyAuthorizedLocust() response = authorized.client.get("/basic_auth") self.assertEqual(200, response.status_code) self.assertEqual("Authorized", response.text) self.assertEqual(401, locust.client.get("/basic_auth").status_code) self.assertEqual(401, unauthorized.client.get("/basic_auth").status_code) def test_log_request_name_argument(self): from locust.stats import global_stats self.response = "" class MyLocust(HttpLocust): tasks = [] host = "http://127.0.0.1:%i" % self.port @task() def t1(l): self.response = l.client.get("/ultra_fast", name="new name!") my_locust = MyLocust() my_locust.t1() self.assertEqual(1, global_stats.get("new name!", "GET").num_requests) self.assertEqual(0, global_stats.get("/ultra_fast", "GET").num_requests) def test_locust_client_error(self): class MyTaskSet(TaskSet): @task def t1(self): self.client.get("/") self.interrupt() class MyLocust(Locust): host = "http://127.0.0.1:%i" % self.port task_set = MyTaskSet my_locust = MyLocust() self.assertRaises(LocustError, lambda: my_locust.client.get("/")) my_taskset = MyTaskSet(my_locust) self.assertRaises(LocustError, lambda: my_taskset.client.get("/")) def test_redirect_url_original_path_as_name(self): class MyLocust(HttpLocust): host = "http://127.0.0.1:%i" % self.port l = MyLocust() l.client.get("/redirect") from locust.stats import global_stats self.assertEqual(1, len(global_stats.entries)) self.assertEqual(1, global_stats.get("/redirect", "GET").num_requests) self.assertEqual(0, global_stats.get("/ultra_fast", "GET").num_requests) class TestCatchResponse(WebserverTestCase): def setUp(self): super(TestCatchResponse, self).setUp() class MyLocust(HttpLocust): host = "http://127.0.0.1:%i" % self.port self.locust = MyLocust() self.num_failures = 0 self.num_success = 0 def on_failure(request_type, name, response_time, exception): self.num_failures += 1 self.last_failure_exception = exception def on_success(**kwargs): self.num_success += 1 events.request_failure += on_failure events.request_success += on_success def test_catch_response(self): self.assertEqual(500, self.locust.client.get("/fail").status_code) self.assertEqual(1, self.num_failures) self.assertEqual(0, self.num_success) with self.locust.client.get("/ultra_fast", catch_response=True) as response: pass self.assertEqual(1, self.num_failures) self.assertEqual(1, self.num_success) with self.locust.client.get("/ultra_fast", catch_response=True) as response: raise ResponseError("Not working") self.assertEqual(2, self.num_failures) self.assertEqual(1, self.num_success) def test_catch_response_http_fail(self): with self.locust.client.get("/fail", catch_response=True) as response: pass self.assertEqual(1, self.num_failures) self.assertEqual(0, self.num_success) def test_catch_response_http_manual_fail(self): with self.locust.client.get("/ultra_fast", catch_response=True) as response: response.failure("Haha!") self.assertEqual(1, self.num_failures) self.assertEqual(0, self.num_success) self.assertTrue( isinstance(self.last_failure_exception, CatchResponseError), "Failure event handler should have been passed a CatchResponseError instance" ) def test_catch_response_http_manual_success(self): with self.locust.client.get("/fail", catch_response=True) as response: response.success() self.assertEqual(0, self.num_failures) self.assertEqual(1, self.num_success) def test_catch_response_allow_404(self): with self.locust.client.get("/does/not/exist", catch_response=True) as response: self.assertEqual(404, response.status_code) if response.status_code == 404: response.success() self.assertEqual(0, self.num_failures) self.assertEqual(1, self.num_success) def test_interrupt_taskset_with_catch_response(self): class MyTaskSet(TaskSet): @task def interrupted_task(self): with self.client.get("/ultra_fast", catch_response=True) as r: raise InterruptTaskSet() class MyLocust(HttpLocust): host = "http://127.0.0.1:%i" % self.port task_set = MyTaskSet l = MyLocust() ts = MyTaskSet(l) self.assertRaises(InterruptTaskSet, lambda: ts.interrupted_task()) self.assertEqual(0, self.num_failures) self.assertEqual(0, self.num_success) def test_catch_response_connection_error_success(self): class MyLocust(HttpLocust): host = "http://127.0.0.1:1" l = MyLocust() with l.client.get("/", catch_response=True) as r: self.assertEqual(r.status_code, 0) self.assertEqual(None, r.content) r.success() self.assertEqual(1, self.num_success) self.assertEqual(0, self.num_failures) def test_catch_response_connection_error_fail(self): class MyLocust(HttpLocust): host = "http://127.0.0.1:1" l = MyLocust() with l.client.get("/", catch_response=True) as r: self.assertEqual(r.status_code, 0) self.assertEqual(None, r.content) r.success() self.assertEqual(1, self.num_success) self.assertEqual(0, self.num_failures)
""" Common narrative logging functions. To log an event with proper metadata and formatting use 'log_event': You can also do free-form logs, but these will be ignored by most upstream consumers. """ __author__ = 'Dan Gunter <dkgunter@lbl.gov>' __date__ = '2014-07-31' import collections import logging from logging import handlers import os import threading import time # Local from .util import kbase_env from . import log_proxy from .log_common import format_event ## Constants KBASE_TMP_DIR = "/tmp" KBASE_TMP_LOGFILE = os.path.join(KBASE_TMP_DIR, "kbase-narrative.log") # env var with location of proxy config file KBASE_PROXY_ENV = 'KBASE_PROXY_CONFIG' ## Internal logging _log = logging.getLogger("tornado.application") # WTF is going on logging #def _logdbg(m): # open("/tmp/wtf", "a").write(m + "\n") ## External functions def get_logger(name="", init=False): """Get a given KBase log obj. :param name: name (a.b.c) of the logging namespace, which may be relative or absolute (starting with 'biokbase.'), or empty in which case the 'biokbase' logger is returned :param init: If true, re-initialize the file/socket log handlers :return: Log object :rtype: LogAdapter """ if init: reset_handlers() return logging.getLogger(_kbase_log_name(name)) def log_event(log, event, mapping): """Log an event and a mapping. For example:: log_event(_log, "collision", {"who":"unstoppable force", "with":"immovable object", "where":"kbase"}) """ msg = format_event(event, mapping) log.info(msg) ## Internal functions and classes def _kbase_log_name(name): """Smarter name of KBase logger.""" # no name => root if not name: return "biokbase" # absolute name if name.startswith("biokbase."): return name # relative name return "biokbase." + name def _has_handler_type(log, type_): return any(map(lambda h: isinstance(h, type_), log.handlers)) ## Custom handlers class BufferedSocketHandler(handlers.SocketHandler): """Buffer up messages to a socket, sending them asynchronously. Starts a separate thread to pull messages off and send them. Ignores any messages that did not come from `log_event()`, above. """ def __init__(self, *args): handlers.SocketHandler.__init__(self, *args) self._dbg = _log.isEnabledFor(logging.DEBUG) if self._dbg: _log.debug("Created SocketHandler with args = {}".format(args)) self.buf = collections.deque([], 100) self.buf_lock = threading.Lock() # start thread to send data from buffer self.thr = threading.Thread(target=self.emitter) self.thr.daemon = True self._stop = False self.extra = {} self.thr.start() def close(self): if self.thr: self._stop = True self.thr.join() self.thr = None handlers.SocketHandler.close(self) def emitter(self): while not self._stop: try: self.buf_lock.acquire() item = self.buf.popleft() if not self._emit(item): self.buf.appendleft(item) self.buf_lock.release() time.sleep(0.1) else: self.buf_lock.release() except IndexError: self.buf_lock.release() time.sleep(0.1) def emit(self, record): if self._skip(record): return # stuff 'extra' from environment into record #_logdbg("@@ stuffing into record: {}".format(kbase_env)) record.__dict__.update(kbase_env) if 'auth_token' in record.__dict__: del record.__dict__['auth_token'] self.buf_lock.acquire() try: self.buf.append(record) finally: self.buf_lock.release() def _skip(self, record): """Return True if this record should not go to a socket""" # Do not forward records that didn't get logged through # kblogging.log_event if record.funcName != 'log_event': if self._dbg: _log.debug("Skip: funcName {} != log_event" .format(record.funcName)) return def _emit(self, record): """Re-implement to return a success code.""" success = False try: s = self.makePickle(record) self.send(s) success = True except (KeyboardInterrupt, SystemExit): raise except Exception as err: _log.debug("Emit record to socket failed: {}".format(err)) self.handleError(record) if success and _log.isEnabledFor(logging.DEBUG): _log.debug("Record sent to socket") return success def init_handlers(): """Initialize and add the log handlers. We only allow one FileHandler and one SocketHandler to exist, no matter how many times this is called. """ # Turn on debugging by setting environment variable KBASE_DEBUG. if os.environ.get("KBASE_DEBUG", None): g_log.setLevel(logging.DEBUG) else: g_log.setLevel(logging.INFO) if not _has_handler_type(g_log, logging.FileHandler): hndlr = logging.FileHandler(KBASE_TMP_LOGFILE) fmtr = logging.Formatter("%(levelname)s %(asctime)s %(name)s %(message)s") hndlr.setFormatter(fmtr) g_log.addHandler(hndlr) if not _has_handler_type(g_log, handlers.SocketHandler): cfg = get_proxy_config() g_log.debug("Opening socket to proxy at {}:{}".format( cfg.host, cfg.port)) sock_handler = BufferedSocketHandler(cfg.host, cfg.port) g_log.addHandler(sock_handler) def get_proxy_config(): config_file = os.environ.get(KBASE_PROXY_ENV, None) if config_file: _log.info("Configuring KBase logging from file '{}'".format(config_file)) else: _log.warn("Configuring KBase logging from defaults ({} is empty, or not found)" .format(KBASE_PROXY_ENV)) # return log_proxy.ProxyConfiguration(config_file) return log_proxy.ProxyConfigurationWrapper(config_file) def reset_handlers(): """Remove & re-add all handlers.""" while g_log.handlers: g_log.removeHandler(g_log.handlers.pop()) init_handlers() ## Run the rest of this on import # Get root log obj. g_log = get_logger() # If no handlers, initialize them if not g_log.handlers: init_handlers() class NarrativeUIError(object): """Created by Narrative UI javascript on an error. """ ui_log = get_logger("narrative_ui") def __init__(self, is_fatal, where="unknown location", what="unknown condition"): info = {"function": where, "msg": what} msg = format_event("ui.error", info) log_method = (self.ui_log.error, self.ui_log.critical)[is_fatal] log_method(msg)
# Copyright 2011 VMware, 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. import weakref from oslo.config import cfg from neutron.common import utils from neutron.openstack.common import importutils from neutron.openstack.common import log as logging from neutron.openstack.common import periodic_task from neutron.plugins.common import constants from stevedore import driver LOG = logging.getLogger(__name__) class Manager(periodic_task.PeriodicTasks): # Set RPC API version to 1.0 by default. RPC_API_VERSION = '1.0' def __init__(self, host=None): if not host: host = cfg.CONF.host self.host = host super(Manager, self).__init__() def periodic_tasks(self, context, raise_on_error=False): self.run_periodic_tasks(context, raise_on_error=raise_on_error) def init_host(self): """Handle initialization if this is a standalone service. Child classes should override this method. """ pass def after_start(self): """Handler post initialization stuff. Child classes can override this method. """ pass def validate_post_plugin_load(): """Checks if the configuration variables are valid. If the configuration is invalid then the method will return an error message. If all is OK then it will return None. """ if ('dhcp_agents_per_network' in cfg.CONF and cfg.CONF.dhcp_agents_per_network <= 0): msg = _("dhcp_agents_per_network must be >= 1. '%s' " "is invalid.") % cfg.CONF.dhcp_agents_per_network return msg def validate_pre_plugin_load(): """Checks if the configuration variables are valid. If the configuration is invalid then the method will return an error message. If all is OK then it will return None. """ if cfg.CONF.core_plugin is None: msg = _('Neutron core_plugin not configured!') return msg class NeutronManager(object): """Neutron's Manager class. Neutron's Manager class is responsible for parsing a config file and instantiating the correct plugin that concretely implements neutron_plugin_base class. The caller should make sure that NeutronManager is a singleton. """ _instance = None def __init__(self, options=None, config_file=None): # If no options have been provided, create an empty dict if not options: options = {} msg = validate_pre_plugin_load() if msg: LOG.critical(msg) raise Exception(msg) # NOTE(jkoelker) Testing for the subclass with the __subclasshook__ # breaks tach monitoring. It has been removed # intentionally to allow v2 plugins to be monitored # for performance metrics. plugin_provider = cfg.CONF.core_plugin LOG.info(_("Loading core plugin: %s"), plugin_provider) self.plugin = self._get_plugin_instance('neutron.core_plugins', plugin_provider) msg = validate_post_plugin_load() if msg: LOG.critical(msg) raise Exception(msg) # core plugin as a part of plugin collection simplifies # checking extensions # TODO(enikanorov): make core plugin the same as # the rest of service plugins self.service_plugins = {constants.CORE: self.plugin} self._load_service_plugins() def _get_plugin_instance(self, namespace, plugin_provider): try: # Try to resolve plugin by name mgr = driver.DriverManager(namespace, plugin_provider) plugin_class = mgr.driver except RuntimeError as e1: # fallback to class name try: plugin_class = importutils.import_class(plugin_provider) except ImportError as e2: LOG.exception(_("Error loading plugin by name, %s"), e1) LOG.exception(_("Error loading plugin by class, %s"), e2) raise ImportError(_("Plugin not found.")) return plugin_class() def _load_services_from_core_plugin(self): """Puts core plugin in service_plugins for supported services.""" LOG.debug(_("Loading services supported by the core plugin")) # supported service types are derived from supported extensions for ext_alias in getattr(self.plugin, "supported_extension_aliases", []): if ext_alias in constants.EXT_TO_SERVICE_MAPPING: service_type = constants.EXT_TO_SERVICE_MAPPING[ext_alias] self.service_plugins[service_type] = self.plugin LOG.info(_("Service %s is supported by the core plugin"), service_type) def _load_service_plugins(self): """Loads service plugins. Starts from the core plugin and checks if it supports advanced services then loads classes provided in configuration. """ # load services from the core plugin first self._load_services_from_core_plugin() plugin_providers = cfg.CONF.service_plugins LOG.debug(_("Loading service plugins: %s"), plugin_providers) for provider in plugin_providers: if provider == '': continue LOG.info(_("Loading Plugin: %s"), provider) plugin_inst = self._get_plugin_instance('neutron.service_plugins', provider) # only one implementation of svc_type allowed # specifying more than one plugin # for the same type is a fatal exception if plugin_inst.get_plugin_type() in self.service_plugins: raise ValueError(_("Multiple plugins for service " "%s were configured"), plugin_inst.get_plugin_type()) self.service_plugins[plugin_inst.get_plugin_type()] = plugin_inst # search for possible agent notifiers declared in service plugin # (needed by agent management extension) if (hasattr(self.plugin, 'agent_notifiers') and hasattr(plugin_inst, 'agent_notifiers')): self.plugin.agent_notifiers.update(plugin_inst.agent_notifiers) LOG.debug(_("Successfully loaded %(type)s plugin. " "Description: %(desc)s"), {"type": plugin_inst.get_plugin_type(), "desc": plugin_inst.get_plugin_description()}) @classmethod @utils.synchronized("manager") def _create_instance(cls): if not cls.has_instance(): cls._instance = cls() @classmethod def has_instance(cls): return cls._instance is not None @classmethod def clear_instance(cls): cls._instance = None @classmethod def get_instance(cls): # double checked locking if not cls.has_instance(): cls._create_instance() return cls._instance @classmethod def get_plugin(cls): # Return a weakref to minimize gc-preventing references. return weakref.proxy(cls.get_instance().plugin) @classmethod def get_service_plugins(cls): # Return weakrefs to minimize gc-preventing references. return dict((x, weakref.proxy(y)) for x, y in cls.get_instance().service_plugins.iteritems())
# 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 functools import inspect from abc import abstractmethod from collections import defaultdict import six from pants.base.build_file_target_factory import BuildFileTargetFactory from pants.base.deprecated import deprecated from pants.base.target import Target from pants.util.memo import memoized_property class TargetMacro(object): """A specialized context aware object factory responsible for instantiating a set of target types. The macro acts to expand arguments to its alias in a BUILD file into one or more target addressable instances. This is primarily useful for hiding true target type constructors from BUILD file authors and providing an extra layer of control over core target parameters like `name` and `dependencies`. """ class Factory(BuildFileTargetFactory): """Creates new target macros specialized for a particular BUILD file parse context.""" @classmethod def wrap(cls, context_aware_object_factory, *target_types): """Wraps an existing context aware object factory into a target macro factory. :param context_aware_object_factory: The existing context aware object factory. :param *target_types: One or more target types the context aware object factory creates. :returns: A new target macro factory. :rtype: :class:`TargetMacro.Factory` """ if not target_types: raise ValueError('The given `context_aware_object_factory` {} must expand at least 1 ' 'produced type; none were registered'.format(context_aware_object_factory)) class Factory(cls): @property def target_types(self): return target_types def macro(self, parse_context): class Macro(TargetMacro): def expand(self, *args, **kwargs): context_aware_object_factory(parse_context, *args, **kwargs) return Macro() return Factory() @abstractmethod def macro(self, parse_context): """Returns a new target macro that can create targets in the given parse context. :param parse_context: The parse context the target macro will expand targets in. :type parse_context: :class:`pants.base.parse_context.ParseContext` :rtype: :class:`TargetMacro` """ def target_macro(self, parse_context): """Returns a new target macro that can create targets in the given parse context. The target macro will also act as a build file target factory and report the target types it creates. :param parse_context: The parse context the target macro will expand targets in. :type parse_context: :class:`pants.base.parse_context.ParseContext` :rtype: :class:`BuildFileTargetFactory` & :class:`TargetMacro` """ macro = self.macro(parse_context) class BuildFileTargetFactoryMacro(BuildFileTargetFactory, TargetMacro): @property def target_types(_): return self.target_types expand = macro.expand return BuildFileTargetFactoryMacro() def __call__(self, *args, **kwargs): self.expand(*args, **kwargs) @abstractmethod def expand(self, *args, **kwargs): """Expands the given BUILD file arguments in to one or more target addressable instances.""" class BuildFileAliases(object): """A structure containing sets of symbols to be exposed in BUILD files. There are three types of symbols that can be directly exposed: - targets: These are Target subclasses or TargetMacro.Factory instances. - objects: These are any python object, from constants to types. - context_aware_object_factories: These are object factories that are passed a ParseContext and produce one or more objects that use data from the context to enable some feature or utility; you might call them a BUILD file "macro" since they expand parameters to some final, "real" BUILD file object. Common uses include creating objects that must be aware of the current BUILD file path or functions that need to be able to create targets or objects from within the BUILD file parse. """ @classmethod @deprecated(removal_version='0.0.50', hint_message='Use the BuildFileAliases constructor instead.') def create(cls, targets=None, objects=None, context_aware_object_factories=None): """A convenience constructor that can accept zero to all alias types.""" return cls(targets=targets, objects=objects, context_aware_object_factories=context_aware_object_factories) @classmethod def curry_context(cls, wrappee): """Curry a function with a build file context. Given a function foo(ctx, bar) that you want to expose in BUILD files as foo(bar), use:: context_aware_object_factories={ 'foo': BuildFileAliases.curry_context(foo), } """ # You might wonder: why not just use lambda and functools.partial? # That loses the __doc__, thus messing up the BUILD dictionary. wrapper = lambda ctx: functools.partial(wrappee, ctx) wrapper.__doc__ = wrappee.__doc__ wrapper.__name__ = str(".".join(["curry_context", wrappee.__module__, wrappee.__name__])) return wrapper @staticmethod def _is_target_type(obj): return inspect.isclass(obj) and issubclass(obj, Target) @staticmethod def _is_target_macro_factory(obj): return isinstance(obj, TargetMacro.Factory) @classmethod def _validate_alias(cls, category, alias, obj): if not isinstance(alias, six.string_types): raise TypeError('Aliases must be strings, given {category} entry {alias!r} of type {typ} as ' 'the alias of {obj}' .format(category=category, alias=alias, typ=type(alias).__name__, obj=obj)) @classmethod def _validate_not_targets(cls, category, alias, obj): if cls._is_target_type(obj): raise TypeError('The {category} entry {alias!r} is a Target subclasss - these should be ' 'registered via the `targets` parameter' .format(category=category, alias=alias)) if cls._is_target_macro_factory(obj): raise TypeError('The {category} entry {alias!r} is a TargetMacro.Factory instance - these ' 'should be registered via the `targets` parameter' .format(category=category, alias=alias)) @classmethod def _validate_targets(cls, targets): if not targets: return {}, {} target_types = {} target_macro_factories = {} for alias, obj in targets.items(): cls._validate_alias('targets', alias, obj) if cls._is_target_type(obj): target_types[alias] = obj elif cls._is_target_macro_factory(obj): target_macro_factories[alias] = obj else: raise TypeError('Only Target types and TargetMacro.Factory instances can be registered ' 'via the `targets` parameter, given item {alias!r} with value {value} of ' 'type {typ}'.format(alias=alias, value=obj, typ=type(obj).__name__)) return target_types, target_macro_factories @classmethod def _validate_objects(cls, objects): if not objects: return {} for alias, obj in objects.items(): cls._validate_alias('objects', alias, obj) cls._validate_not_targets('objects', alias, obj) return objects.copy() @classmethod def _validate_context_aware_object_factories(cls, context_aware_object_factories): if not context_aware_object_factories: return {} for alias, obj in context_aware_object_factories.items(): cls._validate_alias('context_aware_object_factories', alias, obj) cls._validate_not_targets('context_aware_object_factories', alias, obj) if not callable(obj): raise TypeError('The given context aware object factory {alias!r} must be a callable.' .format(alias=alias)) return context_aware_object_factories.copy() def __init__(self, targets=None, objects=None, context_aware_object_factories=None): """ :param dict targets: A mapping from string aliases to Target subclasses or TargetMacro.Factory instances :param dict objects: A mapping from string aliases to arbitrary objects. :param dict context_aware_object_factories: A mapping from string aliases to context aware object factory callables. """ self._target_types, self._target_macro_factories = self._validate_targets(targets) self._objects = self._validate_objects(objects) self._context_aware_object_factories = self._validate_context_aware_object_factories( context_aware_object_factories) @property def target_types(self): """Returns a mapping from string aliases to Target subclasses. :rtype: dict """ return self._target_types @property def target_macro_factories(self): """Returns a mapping from string aliases to TargetMacro.Factory instances. :rtype: dict """ return self._target_macro_factories @property def objects(self): """Returns a mapping from string aliases arbitrary objects. :rtype: dict """ return self._objects @property def context_aware_object_factories(self): """Returns a mapping from string aliases to context aware object factory callables. :rtype: dict """ return self._context_aware_object_factories @memoized_property def target_types_by_alias(self): """Returns a mapping from target alias to the target types produced for that alias. Normally there is 1 target type per alias, but macros can expand a single alias to several target types. :rtype: dict """ target_types_by_alias = defaultdict(set) for alias, target_type in self.target_types.items(): target_types_by_alias[alias].add(target_type) for alias, target_macro_factory in self.target_macro_factories.items(): target_types_by_alias[alias].update(target_macro_factory.target_types) return dict(target_types_by_alias) def merge(self, other): """Merges a set of build file aliases and returns a new set of aliases containing both. Any duplicate aliases from `other` will trump. :param other: The BuildFileAliases to merge in. :type other: :class:`BuildFileAliases` :returns: A new BuildFileAliases containing `other`'s aliases merged into ours. :rtype: :class:`BuildFileAliases` """ if not isinstance(other, BuildFileAliases): raise TypeError('Can only merge other BuildFileAliases, given {0}'.format(other)) def merge(*items): merged = {} for item in items: merged.update(item) return merged targets = merge(self.target_types, self.target_macro_factories, other.target_types, other.target_macro_factories) objects = merge(self.objects, other.objects) context_aware_object_factories=merge(self.context_aware_object_factories, other.context_aware_object_factories) return BuildFileAliases(targets=targets, objects=objects, context_aware_object_factories=context_aware_object_factories) def _tuple(self): tuplize = lambda d: tuple(sorted(d.items())) return (tuplize(self._target_types), tuplize(self._target_macro_factories), tuplize(self._objects), tuplize(self._context_aware_object_factories)) def __eq__(self, other): return isinstance(other, BuildFileAliases) and self._tuple() == other._tuple() def __ne__(self, other): return not self == other def __hash__(self): return hash(self._tuple())
import unittest from mongoengine import * from mongoengine.queryset import Q, transform __all__ = ("TransformTest",) class TransformTest(unittest.TestCase): def setUp(self): connect(db='mongoenginetest') def test_transform_query(self): """Ensure that the _transform_query function operates correctly. """ self.assertEqual(transform.query(name='test', age=30), {'name': 'test', 'age': 30}) self.assertEqual(transform.query(age__lt=30), {'age': {'$lt': 30}}) self.assertEqual(transform.query(age__gt=20, age__lt=50), {'age': {'$gt': 20, '$lt': 50}}) self.assertEqual(transform.query(age=20, age__gt=50), {'$and': [{'age': {'$gt': 50}}, {'age': 20}]}) self.assertEqual(transform.query(friend__age__gte=30), {'friend.age': {'$gte': 30}}) self.assertEqual(transform.query(name__exists=True), {'name': {'$exists': True}}) def test_transform_update(self): class DicDoc(Document): dictField = DictField() class Doc(Document): pass DicDoc.drop_collection() Doc.drop_collection() DicDoc().save() doc = Doc().save() for k, v in (("set", "$set"), ("set_on_insert", "$setOnInsert"), ("push", "$push")): update = transform.update(DicDoc, **{"%s__dictField__test" % k: doc}) self.assertTrue(isinstance(update[v]["dictField.test"], dict)) # Update special cases update = transform.update(DicDoc, unset__dictField__test=doc) self.assertEqual(update["$unset"]["dictField.test"], 1) update = transform.update(DicDoc, pull__dictField__test=doc) self.assertTrue(isinstance(update["$pull"]["dictField"]["test"], dict)) def test_query_field_name(self): """Ensure that the correct field name is used when querying. """ class Comment(EmbeddedDocument): content = StringField(db_field='commentContent') class BlogPost(Document): title = StringField(db_field='postTitle') comments = ListField(EmbeddedDocumentField(Comment), db_field='postComments') BlogPost.drop_collection() data = {'title': 'Post 1', 'comments': [Comment(content='test')]} post = BlogPost(**data) post.save() self.assertTrue('postTitle' in BlogPost.objects(title=data['title'])._query) self.assertFalse('title' in BlogPost.objects(title=data['title'])._query) self.assertEqual(BlogPost.objects(title=data['title']).count(), 1) self.assertTrue('_id' in BlogPost.objects(pk=post.id)._query) self.assertEqual(BlogPost.objects(pk=post.id).count(), 1) self.assertTrue('postComments.commentContent' in BlogPost.objects(comments__content='test')._query) self.assertEqual(BlogPost.objects(comments__content='test').count(), 1) BlogPost.drop_collection() def test_query_pk_field_name(self): """Ensure that the correct "primary key" field name is used when querying """ class BlogPost(Document): title = StringField(primary_key=True, db_field='postTitle') BlogPost.drop_collection() data = {'title': 'Post 1'} post = BlogPost(**data) post.save() self.assertTrue('_id' in BlogPost.objects(pk=data['title'])._query) self.assertTrue('_id' in BlogPost.objects(title=data['title'])._query) self.assertEqual(BlogPost.objects(pk=data['title']).count(), 1) BlogPost.drop_collection() def test_chaining(self): class A(Document): pass class B(Document): a = ReferenceField(A) A.drop_collection() B.drop_collection() a1 = A().save() a2 = A().save() B(a=a1).save() # Works q1 = B.objects.filter(a__in=[a1, a2], a=a1)._query # Doesn't work q2 = B.objects.filter(a__in=[a1, a2]) q2 = q2.filter(a=a1)._query self.assertEqual(q1, q2) def test_raw_query_and_Q_objects(self): """ Test raw plays nicely """ class Foo(Document): name = StringField() a = StringField() b = StringField() c = StringField() meta = { 'allow_inheritance': False } query = Foo.objects(__raw__={'$nor': [{'name': 'bar'}]})._query self.assertEqual(query, {'$nor': [{'name': 'bar'}]}) q1 = {'$or': [{'a': 1}, {'b': 1}]} query = Foo.objects(Q(__raw__=q1) & Q(c=1))._query self.assertEqual(query, {'$or': [{'a': 1}, {'b': 1}], 'c': 1}) def test_raw_and_merging(self): class Doc(Document): meta = {'allow_inheritance': False} raw_query = Doc.objects(__raw__={ 'deleted': False, 'scraped': 'yes', '$nor': [ {'views.extracted': 'no'}, {'attachments.views.extracted': 'no'} ] })._query self.assertEqual(raw_query, { 'deleted': False, 'scraped': 'yes', '$nor': [ {'views.extracted': 'no'}, {'attachments.views.extracted': 'no'} ] }) def test_geojson_PointField(self): class Location(Document): loc = PointField() update = transform.update(Location, set__loc=[1, 2]) self.assertEqual(update, {'$set': {'loc': {"type": "Point", "coordinates": [1, 2]}}}) update = transform.update(Location, set__loc={"type": "Point", "coordinates": [1, 2]}) self.assertEqual(update, {'$set': {'loc': {"type": "Point", "coordinates": [1, 2]}}}) def test_geojson_LineStringField(self): class Location(Document): line = LineStringField() update = transform.update(Location, set__line=[[1, 2], [2, 2]]) self.assertEqual(update, {'$set': {'line': {"type": "LineString", "coordinates": [[1, 2], [2, 2]]}}}) update = transform.update(Location, set__line={"type": "LineString", "coordinates": [[1, 2], [2, 2]]}) self.assertEqual(update, {'$set': {'line': {"type": "LineString", "coordinates": [[1, 2], [2, 2]]}}}) def test_geojson_PolygonField(self): class Location(Document): poly = PolygonField() update = transform.update(Location, set__poly=[[[40, 5], [40, 6], [41, 6], [40, 5]]]) self.assertEqual(update, {'$set': {'poly': {"type": "Polygon", "coordinates": [[[40, 5], [40, 6], [41, 6], [40, 5]]]}}}) update = transform.update(Location, set__poly={"type": "Polygon", "coordinates": [[[40, 5], [40, 6], [41, 6], [40, 5]]]}) self.assertEqual(update, {'$set': {'poly': {"type": "Polygon", "coordinates": [[[40, 5], [40, 6], [41, 6], [40, 5]]]}}}) def test_type(self): class Doc(Document): df = DynamicField() Doc(df=True).save() Doc(df=7).save() Doc(df="df").save() self.assertEqual(Doc.objects(df__type=1).count(), 0) # double self.assertEqual(Doc.objects(df__type=8).count(), 1) # bool self.assertEqual(Doc.objects(df__type=2).count(), 1) # str self.assertEqual(Doc.objects(df__type=16).count(), 1) # int def test_last_field_name_like_operator(self): class EmbeddedItem(EmbeddedDocument): type = StringField() name = StringField() class Doc(Document): item = EmbeddedDocumentField(EmbeddedItem) Doc.drop_collection() doc = Doc(item=EmbeddedItem(type="axe", name="Heroic axe")) doc.save() self.assertEqual(1, Doc.objects(item__type__="axe").count()) self.assertEqual(1, Doc.objects(item__name__="Heroic axe").count()) Doc.objects(id=doc.id).update(set__item__type__='sword') self.assertEqual(1, Doc.objects(item__type__="sword").count()) self.assertEqual(0, Doc.objects(item__type__="axe").count()) def test_understandable_error_raised(self): class Event(Document): title = StringField() location = GeoPointField() box = [(35.0, -125.0), (40.0, -100.0)] # I *meant* to execute location__within_box=box events = Event.objects(location__within=box) with self.assertRaises(InvalidQueryError): events.count() if __name__ == '__main__': unittest.main()
from __future__ import division, unicode_literals from future.builtins import str, super from future.utils import with_metaclass from decimal import Decimal from functools import reduce from operator import iand, ior from django.core.urlresolvers import reverse from django.db import models, connection from django.db.models.signals import m2m_changed from django.db.models import CharField, Q from django.db.models.base import ModelBase from django.dispatch import receiver from django.utils.timezone import now from django.utils.translation import (ugettext, ugettext_lazy as _, pgettext_lazy as __) try: from django.utils.encoding import force_text except ImportError: # Backward compatibility for Py2 and Django < 1.5 from django.utils.encoding import force_unicode as force_text from mezzanine.conf import settings from mezzanine.core.fields import FileField from mezzanine.core.managers import DisplayableManager from mezzanine.core.models import Displayable, RichText, Orderable, SiteRelated from mezzanine.generic.fields import RatingField from mezzanine.pages.models import Page from mezzanine.utils.models import AdminThumbMixin, upload_to from cartridge.shop import fields, managers from cartridge.shop.utils import clear_session class F(models.F): """ Django 1.4's F objects don't support true division, which we need for Python 3.x. This should be removed when we drop support for Django 1.4. """ def __truediv__(self, other): return self._combine(other, self.DIV, False) class Priced(models.Model): """ Abstract model with unit and sale price fields. Inherited by ``Product`` and ``ProductVariation`` models. """ unit_price = fields.MoneyField(_("Unit price")) sale_id = models.IntegerField(null=True) sale_price = fields.MoneyField(_("Sale price")) sale_from = models.DateTimeField(_("Sale start"), blank=True, null=True) sale_to = models.DateTimeField(_("Sale end"), blank=True, null=True) sku = fields.SKUField(unique=True, blank=True, null=True) num_in_stock = models.IntegerField(_("Number in stock"), blank=True, null=True) class Meta: abstract = True def on_sale(self): """ Returns True if the sale price is applicable. """ n = now() valid_from = self.sale_from is None or self.sale_from < n valid_to = self.sale_to is None or self.sale_to > n return self.sale_price is not None and valid_from and valid_to def has_price(self): """ Returns True if there is a valid price. """ return self.on_sale() or self.unit_price is not None def price(self): """ Returns the actual price - sale price if applicable otherwise the unit price. """ if self.on_sale(): return self.sale_price elif self.has_price(): return self.unit_price return Decimal("0") def copy_price_fields_to(self, obj_to): """ Copies each of the fields for the ``Priced`` model from one instance to another. Used for synchronising the denormalised fields on ``Product`` instances with their default variation. """ for field in Priced._meta.fields: if not isinstance(field, models.AutoField): setattr(obj_to, field.name, getattr(self, field.name)) obj_to.save() class Product(Displayable, Priced, RichText, AdminThumbMixin): """ Container model for a product that stores information common to all of its variations such as the product's title and description. """ available = models.BooleanField(_("Available for purchase"), default=False) image = CharField(_("Image"), max_length=100, blank=True, null=True) categories = models.ManyToManyField("Category", blank=True, verbose_name=_("Product categories")) date_added = models.DateTimeField(_("Date added"), auto_now_add=True, null=True) related_products = models.ManyToManyField("self", verbose_name=_("Related products"), blank=True) upsell_products = models.ManyToManyField("self", verbose_name=_("Upsell products"), blank=True) rating = RatingField(verbose_name=_("Rating")) objects = DisplayableManager() admin_thumb_field = "image" search_fields = {"variations__sku": 100} class Meta: verbose_name = _("Product") verbose_name_plural = _("Products") def save(self, *args, **kwargs): """ Copies the price fields to the default variation when ``SHOP_USE_VARIATIONS`` is False, and the product is updated via the admin change list. """ updating = self.id is not None super(Product, self).save(*args, **kwargs) if updating and not settings.SHOP_USE_VARIATIONS: default = self.variations.get(default=True) self.copy_price_fields_to(default) @models.permalink def get_absolute_url(self): return ("shop_product", (), {"slug": self.slug}) def copy_default_variation(self): """ Copies the price and image fields from the default variation when the product is updated via the change view. """ default = self.variations.get(default=True) default.copy_price_fields_to(self) if default.image: self.image = default.image.file.name self.save() class ProductImage(Orderable): """ An image for a product - a relationship is also defined with the product's variations so that each variation can potentially have it own image, while the relationship between the ``Product`` and ``ProductImage`` models ensures there is a single set of images for the product. """ file = models.ImageField(_("Image"), upload_to=upload_to("shop.ProductImage.file", "product")) description = CharField(_("Description"), blank=True, max_length=100) product = models.ForeignKey("Product", related_name="images") class Meta: verbose_name = _("Image") verbose_name_plural = _("Images") order_with_respect_to = "product" def __unicode__(self): value = self.description if not value: value = self.file.name if not value: value = "" return value class ProductOption(models.Model): """ A selectable option for a product such as size or colour. """ type = models.IntegerField(_("Type"), choices=settings.SHOP_OPTION_TYPE_CHOICES) name = fields.OptionField(_("Name")) objects = managers.ProductOptionManager() def __unicode__(self): return "%s: %s" % (self.get_type_display(), self.name) class Meta: verbose_name = _("Product option") verbose_name_plural = _("Product options") class ProductVariationMetaclass(ModelBase): """ Metaclass for the ``ProductVariation`` model that dynamcally assigns an ``fields.OptionField`` for each option in the ``SHOP_PRODUCT_OPTIONS`` setting. """ def __new__(cls, name, bases, attrs): # Only assign new attrs if not a proxy model. if not ("Meta" in attrs and getattr(attrs["Meta"], "proxy", False)): for option in settings.SHOP_OPTION_TYPE_CHOICES: attrs["option%s" % option[0]] = fields.OptionField(option[1]) args = (cls, name, bases, attrs) return super(ProductVariationMetaclass, cls).__new__(*args) class ProductVariation(with_metaclass(ProductVariationMetaclass, Priced)): """ A combination of selected options from ``SHOP_OPTION_TYPE_CHOICES`` for a ``Product`` instance. """ product = models.ForeignKey("Product", related_name="variations") default = models.BooleanField(_("Default"), default=False) image = models.ForeignKey("ProductImage", verbose_name=_("Image"), null=True, blank=True) objects = managers.ProductVariationManager() class Meta: ordering = ("-default",) def __unicode__(self): """ Display the option names and values for the variation. """ options = [] for field in self.option_fields(): name = getattr(self, field.name) if name is not None: option = u"%s: %s" % (field.verbose_name, name) options.append(option) result = u"%s %s" % (str(self.product), u", ".join(options)) return result.strip() def save(self, *args, **kwargs): """ Use the variation's ID as the SKU when the variation is first created. """ super(ProductVariation, self).save(*args, **kwargs) if not self.sku: self.sku = self.id self.save() def get_absolute_url(self): return self.product.get_absolute_url() @classmethod def option_fields(cls): """ Returns each of the model fields that are dynamically created from ``SHOP_OPTION_TYPE_CHOICES`` in ``ProductVariationMetaclass``. """ all_fields = cls._meta.fields return [f for f in all_fields if isinstance(f, fields.OptionField)] def options(self): """ Returns the field values of each of the model fields that are dynamically created from ``SHOP_OPTION_TYPE_CHOICES`` in ``ProductVariationMetaclass``. """ return [getattr(self, field.name) for field in self.option_fields()] def live_num_in_stock(self): """ Returns the live number in stock, which is ``self.num_in_stock - num in carts``. Also caches the value for subsequent lookups. """ if self.num_in_stock is None: return None if not hasattr(self, "_cached_num_in_stock"): num_in_stock = self.num_in_stock carts = Cart.objects.current() items = CartItem.objects.filter(sku=self.sku, cart__in=carts) aggregate = items.aggregate(quantity_sum=models.Sum("quantity")) num_in_carts = aggregate["quantity_sum"] if num_in_carts is not None: num_in_stock = num_in_stock - num_in_carts self._cached_num_in_stock = num_in_stock return self._cached_num_in_stock def has_stock(self, quantity=1): """ Returns ``True`` if the given quantity is in stock, by checking against ``live_num_in_stock``. ``True`` is returned when ``num_in_stock`` is ``None`` which is how stock control is disabled. """ live = self.live_num_in_stock() return live is None or quantity == 0 or live >= quantity def update_stock(self, quantity): """ Update the stock amount - called when an order is complete. Also update the denormalised stock amount of the product if this is the default variation. """ if self.num_in_stock is not None: self.num_in_stock += quantity self.save() if self.default: self.product.num_in_stock = self.num_in_stock self.product.save() class Category(Page, RichText): """ A category of products on the website. """ featured_image = FileField(verbose_name=_("Featured Image"), upload_to=upload_to("shop.Category.featured_image", "shop"), format="Image", max_length=255, null=True, blank=True) products = models.ManyToManyField("Product", blank=True, verbose_name=_("Products"), through=Product.categories.through) options = models.ManyToManyField("ProductOption", blank=True, verbose_name=_("Product options"), related_name="product_options") sale = models.ForeignKey("Sale", verbose_name=_("Sale"), blank=True, null=True) price_min = fields.MoneyField(_("Minimum price"), blank=True, null=True) price_max = fields.MoneyField(_("Maximum price"), blank=True, null=True) combined = models.BooleanField(_("Combined"), default=True, help_text=_("If checked, " "products must match all specified filters, otherwise products " "can match any specified filter.")) class Meta: verbose_name = _("Product category") verbose_name_plural = _("Product categories") def filters(self): """ Returns product filters as a Q object for the category. """ # Build a list of Q objects to filter variations by. filters = [] # Build a lookup dict of selected options for variations. options = self.options.as_fields() if options: lookup = dict([("%s__in" % k, v) for k, v in options.items()]) filters.append(Q(**lookup)) # Q objects used against variations to ensure sale date is # valid when filtering by sale, or sale price. n = now() valid_sale_from = Q(sale_from__isnull=True) | Q(sale_from__lte=n) valid_sale_to = Q(sale_to__isnull=True) | Q(sale_to__gte=n) valid_sale_date = valid_sale_from & valid_sale_to # Filter by variations with the selected sale if the sale date # is valid. if self.sale_id: filters.append(Q(sale_id=self.sale_id) & valid_sale_date) # If a price range is specified, use either the unit price or # a sale price if the sale date is valid. if self.price_min or self.price_max: prices = [] if self.price_min: sale = Q(sale_price__gte=self.price_min) & valid_sale_date prices.append(Q(unit_price__gte=self.price_min) | sale) if self.price_max: sale = Q(sale_price__lte=self.price_max) & valid_sale_date prices.append(Q(unit_price__lte=self.price_max) | sale) filters.append(reduce(iand, prices)) # Turn the variation filters into a product filter. operator = iand if self.combined else ior products = Q(id__in=self.products.only("id")) if filters: filters = reduce(operator, filters) variations = ProductVariation.objects.filter(filters) filters = [Q(variations__in=variations)] # If filters exist, checking that products have been # selected is neccessary as combining the variations # with an empty ID list lookup and ``AND`` will always # result in an empty result. if self.products.count() > 0: filters.append(products) return reduce(operator, filters) return products class Order(SiteRelated): billing_detail_first_name = CharField(_("First name"), max_length=100) billing_detail_last_name = CharField(_("Last name"), max_length=100) billing_detail_street = CharField(_("Street"), max_length=100) billing_detail_city = CharField(_("City/Suburb"), max_length=100) billing_detail_state = CharField(_("State/Region"), max_length=100) billing_detail_postcode = CharField(_("Zip/Postcode"), max_length=10) billing_detail_country = CharField(_("Country"), max_length=100) billing_detail_phone = CharField(_("Phone"), max_length=20) billing_detail_email = models.EmailField(_("Email")) shipping_detail_first_name = CharField(_("First name"), max_length=100) shipping_detail_last_name = CharField(_("Last name"), max_length=100) shipping_detail_street = CharField(_("Street"), max_length=100) shipping_detail_city = CharField(_("City/Suburb"), max_length=100) shipping_detail_state = CharField(_("State/Region"), max_length=100) shipping_detail_postcode = CharField(_("Zip/Postcode"), max_length=10) shipping_detail_country = CharField(_("Country"), max_length=100) shipping_detail_phone = CharField(_("Phone"), max_length=20) additional_instructions = models.TextField(_("Additional instructions"), blank=True) time = models.DateTimeField(_("Time"), auto_now_add=True, null=True) key = CharField(max_length=40) user_id = models.IntegerField(blank=True, null=True) shipping_type = CharField(_("Shipping type"), max_length=50, blank=True) shipping_total = fields.MoneyField(_("Shipping total")) tax_type = CharField(_("Tax type"), max_length=50, blank=True) tax_total = fields.MoneyField(_("Tax total")) item_total = fields.MoneyField(_("Item total")) discount_code = fields.DiscountCodeField(_("Discount code"), blank=True) discount_total = fields.MoneyField(_("Discount total")) total = fields.MoneyField(_("Order total")) transaction_id = CharField(_("Transaction ID"), max_length=255, null=True, blank=True) status = models.IntegerField(_("Status"), choices=settings.SHOP_ORDER_STATUS_CHOICES, default=settings.SHOP_ORDER_STATUS_CHOICES[0][0]) objects = managers.OrderManager() # These are fields that are stored in the session. They're copied to # the order in setup() and removed from the session in complete(). session_fields = ("shipping_type", "shipping_total", "discount_total", "discount_code", "tax_type", "tax_total") class Meta: verbose_name = __("commercial meaning", "Order") verbose_name_plural = __("commercial meaning", "Orders") ordering = ("-id",) def __unicode__(self): return "#%s %s %s" % (self.id, self.billing_name(), self.time) def billing_name(self): return "%s %s" % (self.billing_detail_first_name, self.billing_detail_last_name) def setup(self, request): """ Set order fields that are stored in the session, item_total and total based on the given cart, and copy the cart items to the order. Called in the final step of the checkout process prior to the payment handler being called. """ self.key = request.session.session_key self.user_id = request.user.id for field in self.session_fields: if field in request.session: setattr(self, field, request.session[field]) self.total = self.item_total = request.cart.total_price() if self.shipping_total is not None: self.shipping_total = Decimal(str(self.shipping_total)) self.total += self.shipping_total if self.discount_total is not None: self.total -= Decimal(self.discount_total) if self.tax_total is not None: self.total += Decimal(self.tax_total) self.save() # We need an ID before we can add related items. for item in request.cart: product_fields = [f.name for f in SelectedProduct._meta.fields] item = dict([(f, getattr(item, f)) for f in product_fields]) self.items.create(**item) def complete(self, request): """ Remove order fields that are stored in the session, reduce the stock level for the items in the order, decrement the uses remaining count for discount code (if applicable) and then delete the cart. """ self.save() # Save the transaction ID. discount_code = request.session.get('discount_code') clear_session(request, "order", *self.session_fields) for item in request.cart: try: variation = ProductVariation.objects.get(sku=item.sku) except ProductVariation.DoesNotExist: pass else: variation.update_stock(item.quantity * -1) variation.product.actions.purchased() if discount_code: DiscountCode.objects.active().filter(code=discount_code).update( uses_remaining=models.F('uses_remaining') - 1) request.cart.delete() def details_as_dict(self): """ Returns the billing_detail_* and shipping_detail_* fields as two name/value pairs of fields in a dict for each type. Used in template contexts for rendering each type as groups of names/values. """ context = {} for fieldset in ("billing_detail", "shipping_detail"): fields = [(f.verbose_name, getattr(self, f.name)) for f in self._meta.fields if f.name.startswith(fieldset)] context["order_%s_fields" % fieldset] = fields return context def invoice(self): """ Returns the HTML for a link to the PDF invoice for use in the order listing view of the admin. """ url = reverse("shop_invoice", args=(self.id,)) text = ugettext("Download PDF invoice") return "<a href='%s?format=pdf'>%s</a>" % (url, text) invoice.allow_tags = True invoice.short_description = "" class Cart(models.Model): last_updated = models.DateTimeField(_("Last updated"), null=True) objects = managers.CartManager() def __iter__(self): """ Allow the cart to be iterated giving access to the cart's items, ensuring the items are only retrieved once and cached. """ if not hasattr(self, "_cached_items"): self._cached_items = self.items.all() return iter(self._cached_items) def add_item(self, variation, quantity): """ Increase quantity of existing item if SKU matches, otherwise create new. """ kwargs = {"sku": variation.sku, "unit_price": variation.price()} item, created = self.items.get_or_create(**kwargs) if created: item.description = force_text(variation) item.unit_price = variation.price() item.url = variation.product.get_absolute_url() image = variation.image if image is not None: item.image = force_text(image.file) variation.product.actions.added_to_cart() item.quantity += quantity item.save() def has_items(self): """ Template helper function - does the cart have items? """ return len(list(self)) > 0 def total_quantity(self): """ Template helper function - sum of all item quantities. """ return sum([item.quantity for item in self]) def total_price(self): """ Template helper function - sum of all costs of item quantities. """ return sum([item.total_price for item in self]) def skus(self): """ Returns a list of skus for items in the cart. Used by ``upsell_products`` and ``calculate_discount``. """ return [item.sku for item in self] def upsell_products(self): """ Returns the upsell products for each of the items in the cart. """ if not settings.SHOP_USE_UPSELL_PRODUCTS: return [] cart = Product.objects.filter(variations__sku__in=self.skus()) published_products = Product.objects.published() for_cart = published_products.filter(upsell_products__in=cart) with_cart_excluded = for_cart.exclude(variations__sku__in=self.skus()) return list(with_cart_excluded.distinct()) def calculate_discount(self, discount): """ Calculates the discount based on the items in a cart, some might have the discount, others might not. """ # Discount applies to cart total if not product specific. products = discount.all_products() if products.count() == 0: return discount.calculate(self.total_price()) total = Decimal("0") # Create a list of skus in the cart that are applicable to # the discount, and total the discount for appllicable items. lookup = {"product__in": products, "sku__in": self.skus()} discount_variations = ProductVariation.objects.filter(**lookup) discount_skus = discount_variations.values_list("sku", flat=True) for item in self: if item.sku in discount_skus: total += discount.calculate(item.unit_price) * item.quantity return total class SelectedProduct(models.Model): """ Abstract model representing a "selected" product in a cart or order. """ sku = fields.SKUField() description = CharField(_("Description"), max_length=2000) quantity = models.IntegerField(_("Quantity"), default=0) unit_price = fields.MoneyField(_("Unit price"), default=Decimal("0")) total_price = fields.MoneyField(_("Total price"), default=Decimal("0")) class Meta: abstract = True def __unicode__(self): return "" def save(self, *args, **kwargs): """ Set the total price based on the given quantity. If the quantity is zero, which may occur via the cart page, just delete it. """ if not self.id or self.quantity > 0: self.total_price = self.unit_price * self.quantity super(SelectedProduct, self).save(*args, **kwargs) else: self.delete() class CartItem(SelectedProduct): cart = models.ForeignKey("Cart", related_name="items") url = CharField(max_length=2000) image = CharField(max_length=200, null=True) def get_absolute_url(self): return self.url class OrderItem(SelectedProduct): """ A selected product in a completed order. """ order = models.ForeignKey("Order", related_name="items") class ProductAction(models.Model): """ Records an incremental value for an action against a product such as adding to cart or purchasing, for sales reporting and calculating popularity. Not yet used but will be used for product popularity and sales reporting. """ product = models.ForeignKey("Product", related_name="actions") timestamp = models.IntegerField() total_cart = models.IntegerField(default=0) total_purchase = models.IntegerField(default=0) objects = managers.ProductActionManager() class Meta: unique_together = ("product", "timestamp") class Discount(models.Model): """ Abstract model representing one of several types of monetary reductions, as well as a date range they're applicable for, and the products and products in categories that the reduction is applicable for. """ title = CharField(_("Title"), max_length=100) active = models.BooleanField(_("Active"), default=False) products = models.ManyToManyField("Product", blank=True, verbose_name=_("Products")) categories = models.ManyToManyField("Category", blank=True, related_name="%(class)s_related", verbose_name=_("Categories")) discount_deduct = fields.MoneyField(_("Reduce by amount")) discount_percent = fields.PercentageField(_("Reduce by percent"), max_digits=5, decimal_places=2, blank=True, null=True) discount_exact = fields.MoneyField(_("Reduce to amount")) valid_from = models.DateTimeField(_("Valid from"), blank=True, null=True) valid_to = models.DateTimeField(_("Valid to"), blank=True, null=True) class Meta: abstract = True def __unicode__(self): return self.title def all_products(self): """ Return the selected products as well as the products in the selected categories. """ filters = [category.filters() for category in self.categories.all()] filters = reduce(ior, filters + [Q(id__in=self.products.only("id"))]) return Product.objects.filter(filters).distinct() class Sale(Discount): """ Stores sales field values for price and date range which when saved are then applied across products and variations according to the selected categories and products for the sale. """ class Meta: verbose_name = _("Sale") verbose_name_plural = _("Sales") def save(self, *args, **kwargs): super(Sale, self).save(*args, **kwargs) self.update_products() def update_products(self): """ Apply sales field value to products and variations according to the selected categories and products for the sale. """ self._clear() if self.active: extra_filter = {} if self.discount_deduct is not None: # Don't apply to prices that would be negative # after deduction. extra_filter["unit_price__gt"] = self.discount_deduct sale_price = models.F("unit_price") - self.discount_deduct elif self.discount_percent is not None: sale_price = models.F("unit_price") - ( F("unit_price") / "100.0" * self.discount_percent) elif self.discount_exact is not None: # Don't apply to prices that are cheaper than the sale # amount. extra_filter["unit_price__gt"] = self.discount_exact sale_price = self.discount_exact else: return products = self.all_products() variations = ProductVariation.objects.filter(product__in=products) for priced_objects in (products, variations): update = {"sale_id": self.id, "sale_price": sale_price, "sale_to": self.valid_to, "sale_from": self.valid_from} using = priced_objects.db if "mysql" not in settings.DATABASES[using]["ENGINE"]: priced_objects.filter(**extra_filter).update(**update) else: # Work around for MySQL which does not allow update # to operate on subquery where the FROM clause would # have it operate on the same table, so we update # each instance individually: # http://dev.mysql.com/doc/refman/5.0/en/subquery-errors.html # Also MySQL may raise a 'Data truncated' warning here # when doing a calculation that exceeds the precision # of the price column. In this case it's safe to ignore # it and the calculation will still be applied, but # we need to massage transaction management in order # to continue successfully: # https://groups.google.com/forum/#!topic/django-developers/ACLQRF-71s8 for priced in priced_objects.filter(**extra_filter): for field, value in list(update.items()): setattr(priced, field, value) try: priced.save() except Warning: connection.set_rollback(False) def delete(self, *args, **kwargs): """ Clear this sale from products when deleting the sale. """ self._clear() super(Sale, self).delete(*args, **kwargs) def _clear(self): """ Clears previously applied sale field values from products prior to updating the sale, when deactivating it or deleting it. """ update = {"sale_id": None, "sale_price": None, "sale_from": None, "sale_to": None} for priced_model in (Product, ProductVariation): priced_model.objects.filter(sale_id=self.id).update(**update) @receiver(m2m_changed, sender=Sale.products.through) def sale_update_products(sender, instance, action, *args, **kwargs): """ Signal for updating products for the sale - needed since the products won't be assigned to the sale when it is first saved. """ if action == "post_add": instance.update_products() class DiscountCode(Discount): """ A code that can be entered at the checkout process to have a discount applied to the total purchase amount. """ code = fields.DiscountCodeField(_("Code"), unique=True) min_purchase = fields.MoneyField(_("Minimum total purchase")) free_shipping = models.BooleanField(_("Free shipping"), default=False) uses_remaining = models.IntegerField(_("Uses remaining"), blank=True, null=True, help_text=_("If you wish to limit the number of times a " "code may be used, set this value. It will be decremented upon " "each use.")) objects = managers.DiscountCodeManager() def calculate(self, amount): """ Calculates the discount for the given amount. """ if self.discount_deduct is not None: # Don't apply to amounts that would be negative after # deduction. if self.discount_deduct <= amount: return self.discount_deduct elif self.discount_percent is not None: return amount / Decimal("100") * self.discount_percent return 0 class Meta: verbose_name = _("Discount code") verbose_name_plural = _("Discount codes")
"""The tests for the utility_meter sensor platform.""" from contextlib import contextmanager from datetime import timedelta from unittest.mock import patch from homeassistant.components.sensor import ( ATTR_STATE_CLASS, STATE_CLASS_TOTAL, STATE_CLASS_TOTAL_INCREASING, ) from homeassistant.components.utility_meter.const import ( ATTR_TARIFF, ATTR_VALUE, DAILY, DOMAIN, HOURLY, QUARTER_HOURLY, SERVICE_CALIBRATE_METER, SERVICE_SELECT_TARIFF, ) from homeassistant.components.utility_meter.sensor import ( ATTR_LAST_RESET, ATTR_STATUS, COLLECTING, PAUSED, ) from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_ENTITY_ID, ATTR_UNIT_OF_MEASUREMENT, ENERGY_KILO_WATT_HOUR, EVENT_HOMEASSISTANT_START, STATE_UNAVAILABLE, ) from homeassistant.core import State from homeassistant.setup import async_setup_component import homeassistant.util.dt as dt_util from tests.common import async_fire_time_changed, mock_restore_cache @contextmanager def alter_time(retval): """Manage multiple time mocks.""" patch1 = patch("homeassistant.util.dt.utcnow", return_value=retval) patch2 = patch("homeassistant.util.dt.now", return_value=retval) with patch1, patch2: yield async def test_state(hass): """Test utility sensor state.""" config = { "utility_meter": { "energy_bill": { "source": "sensor.energy", "tariffs": ["onpeak", "midpeak", "offpeak"], } } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() hass.bus.async_fire(EVENT_HOMEASSISTANT_START) entity_id = config[DOMAIN]["energy_bill"]["source"] hass.states.async_set( entity_id, 2, {ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR} ) await hass.async_block_till_done() state = hass.states.get("sensor.energy_bill_onpeak") assert state is not None assert state.state == "0" assert state.attributes.get("status") == COLLECTING state = hass.states.get("sensor.energy_bill_midpeak") assert state is not None assert state.state == "0" assert state.attributes.get("status") == PAUSED state = hass.states.get("sensor.energy_bill_offpeak") assert state is not None assert state.state == "0" assert state.attributes.get("status") == PAUSED now = dt_util.utcnow() + timedelta(seconds=10) with patch("homeassistant.util.dt.utcnow", return_value=now): hass.states.async_set( entity_id, 3, {ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR}, force_update=True, ) await hass.async_block_till_done() state = hass.states.get("sensor.energy_bill_onpeak") assert state is not None assert state.state == "1" assert state.attributes.get("status") == COLLECTING state = hass.states.get("sensor.energy_bill_midpeak") assert state is not None assert state.state == "0" assert state.attributes.get("status") == PAUSED state = hass.states.get("sensor.energy_bill_offpeak") assert state is not None assert state.state == "0" assert state.attributes.get("status") == PAUSED await hass.services.async_call( DOMAIN, SERVICE_SELECT_TARIFF, {ATTR_ENTITY_ID: "utility_meter.energy_bill", ATTR_TARIFF: "offpeak"}, blocking=True, ) await hass.async_block_till_done() now = dt_util.utcnow() + timedelta(seconds=20) with patch("homeassistant.util.dt.utcnow", return_value=now): hass.states.async_set( entity_id, 6, {ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR}, force_update=True, ) await hass.async_block_till_done() state = hass.states.get("sensor.energy_bill_onpeak") assert state is not None assert state.state == "1" assert state.attributes.get("status") == PAUSED state = hass.states.get("sensor.energy_bill_midpeak") assert state is not None assert state.state == "0" assert state.attributes.get("status") == PAUSED state = hass.states.get("sensor.energy_bill_offpeak") assert state is not None assert state.state == "3" assert state.attributes.get("status") == COLLECTING await hass.services.async_call( DOMAIN, SERVICE_CALIBRATE_METER, {ATTR_ENTITY_ID: "sensor.energy_bill_midpeak", ATTR_VALUE: "100"}, blocking=True, ) await hass.async_block_till_done() state = hass.states.get("sensor.energy_bill_midpeak") assert state is not None assert state.state == "100" await hass.services.async_call( DOMAIN, SERVICE_CALIBRATE_METER, {ATTR_ENTITY_ID: "sensor.energy_bill_midpeak", ATTR_VALUE: "0.123"}, blocking=True, ) await hass.async_block_till_done() state = hass.states.get("sensor.energy_bill_midpeak") assert state is not None assert state.state == "0.123" # test invalid state entity_id = config[DOMAIN]["energy_bill"]["source"] hass.states.async_set( entity_id, "*", {ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR} ) await hass.async_block_till_done() state = hass.states.get("sensor.energy_bill_midpeak") assert state is not None assert state.state == "0.123" # test unavailable source entity_id = config[DOMAIN]["energy_bill"]["source"] hass.states.async_set( entity_id, STATE_UNAVAILABLE, {ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR} ) await hass.async_block_till_done() state = hass.states.get("sensor.energy_bill_midpeak") assert state is not None assert state.state == "0.123" async def test_device_class(hass): """Test utility device_class.""" config = { "utility_meter": { "energy_meter": { "source": "sensor.energy", "net_consumption": True, }, "gas_meter": { "source": "sensor.gas", }, } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() hass.bus.async_fire(EVENT_HOMEASSISTANT_START) entity_id_energy = config[DOMAIN]["energy_meter"]["source"] hass.states.async_set( entity_id_energy, 2, {ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR} ) entity_id_gas = config[DOMAIN]["gas_meter"]["source"] hass.states.async_set( entity_id_gas, 2, {ATTR_UNIT_OF_MEASUREMENT: "some_archaic_unit"} ) await hass.async_block_till_done() state = hass.states.get("sensor.energy_meter") assert state is not None assert state.state == "0" assert state.attributes.get(ATTR_DEVICE_CLASS) is None assert state.attributes.get(ATTR_STATE_CLASS) == STATE_CLASS_TOTAL assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) is None state = hass.states.get("sensor.gas_meter") assert state is not None assert state.state == "0" assert state.attributes.get(ATTR_DEVICE_CLASS) is None assert state.attributes.get(ATTR_STATE_CLASS) == STATE_CLASS_TOTAL_INCREASING assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) is None hass.states.async_set( entity_id_energy, 3, {ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR} ) hass.states.async_set( entity_id_gas, 3, {ATTR_UNIT_OF_MEASUREMENT: "some_archaic_unit"} ) await hass.async_block_till_done() state = hass.states.get("sensor.energy_meter") assert state is not None assert state.state == "1" assert state.attributes.get(ATTR_DEVICE_CLASS) == "energy" assert state.attributes.get(ATTR_STATE_CLASS) == STATE_CLASS_TOTAL assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == ENERGY_KILO_WATT_HOUR state = hass.states.get("sensor.gas_meter") assert state is not None assert state.state == "1" assert state.attributes.get(ATTR_DEVICE_CLASS) is None assert state.attributes.get(ATTR_STATE_CLASS) == STATE_CLASS_TOTAL_INCREASING assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == "some_archaic_unit" async def test_restore_state(hass): """Test utility sensor restore state.""" last_reset = "2020-12-21T00:00:00.013073+00:00" config = { "utility_meter": { "energy_bill": { "source": "sensor.energy", "tariffs": ["onpeak", "midpeak", "offpeak"], } } } mock_restore_cache( hass, [ State( "sensor.energy_bill_onpeak", "3", attributes={ ATTR_STATUS: PAUSED, ATTR_LAST_RESET: last_reset, }, ), State( "sensor.energy_bill_offpeak", "6", attributes={ ATTR_STATUS: COLLECTING, ATTR_LAST_RESET: last_reset, }, ), ], ) assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() # restore from cache state = hass.states.get("sensor.energy_bill_onpeak") assert state.state == "3" assert state.attributes.get("status") == PAUSED assert state.attributes.get("last_reset") == last_reset state = hass.states.get("sensor.energy_bill_offpeak") assert state.state == "6" assert state.attributes.get("status") == COLLECTING assert state.attributes.get("last_reset") == last_reset # utility_meter is loaded, now set sensors according to utility_meter: hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() state = hass.states.get("utility_meter.energy_bill") assert state.state == "onpeak" state = hass.states.get("sensor.energy_bill_onpeak") assert state.attributes.get("status") == COLLECTING state = hass.states.get("sensor.energy_bill_offpeak") assert state.attributes.get("status") == PAUSED async def test_net_consumption(hass): """Test utility sensor state.""" config = { "utility_meter": { "energy_bill": {"source": "sensor.energy", "net_consumption": True} } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() hass.bus.async_fire(EVENT_HOMEASSISTANT_START) entity_id = config[DOMAIN]["energy_bill"]["source"] hass.states.async_set( entity_id, 2, {ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR} ) await hass.async_block_till_done() now = dt_util.utcnow() + timedelta(seconds=10) with patch("homeassistant.util.dt.utcnow", return_value=now): hass.states.async_set( entity_id, 1, {ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR}, force_update=True, ) await hass.async_block_till_done() state = hass.states.get("sensor.energy_bill") assert state is not None assert state.state == "-1" async def test_non_net_consumption(hass): """Test utility sensor state.""" config = { "utility_meter": { "energy_bill": {"source": "sensor.energy", "net_consumption": False} } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() hass.bus.async_fire(EVENT_HOMEASSISTANT_START) entity_id = config[DOMAIN]["energy_bill"]["source"] hass.states.async_set( entity_id, 2, {ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR} ) await hass.async_block_till_done() now = dt_util.utcnow() + timedelta(seconds=10) with patch("homeassistant.util.dt.utcnow", return_value=now): hass.states.async_set( entity_id, 1, {ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR}, force_update=True, ) await hass.async_block_till_done() state = hass.states.get("sensor.energy_bill") assert state is not None assert state.state == "0" def gen_config(cycle, offset=None): """Generate configuration.""" config = { "utility_meter": {"energy_bill": {"source": "sensor.energy", "cycle": cycle}} } if offset: config["utility_meter"]["energy_bill"]["offset"] = { "days": offset.days, "seconds": offset.seconds, } return config async def _test_self_reset(hass, config, start_time, expect_reset=True): """Test energy sensor self reset.""" now = dt_util.parse_datetime(start_time) with alter_time(now): assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() hass.bus.async_fire(EVENT_HOMEASSISTANT_START) entity_id = config[DOMAIN]["energy_bill"]["source"] async_fire_time_changed(hass, now) hass.states.async_set( entity_id, 1, {ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR} ) await hass.async_block_till_done() now += timedelta(seconds=30) with alter_time(now): async_fire_time_changed(hass, now) hass.states.async_set( entity_id, 3, {ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR}, force_update=True, ) await hass.async_block_till_done() now += timedelta(seconds=30) with alter_time(now): async_fire_time_changed(hass, now) await hass.async_block_till_done() hass.states.async_set( entity_id, 6, {ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR}, force_update=True, ) await hass.async_block_till_done() state = hass.states.get("sensor.energy_bill") if expect_reset: assert state.attributes.get("last_period") == "2" assert state.attributes.get("last_reset") == now.isoformat() assert state.state == "3" else: assert state.attributes.get("last_period") == 0 assert state.state == "5" start_time_str = dt_util.parse_datetime(start_time).isoformat() assert state.attributes.get("last_reset") == start_time_str # Check next day when nothing should happen for weekly, monthly, bimonthly and yearly if config["utility_meter"]["energy_bill"].get("cycle") in [ QUARTER_HOURLY, HOURLY, DAILY, ]: now += timedelta(minutes=5) else: now += timedelta(days=5) with alter_time(now): async_fire_time_changed(hass, now) await hass.async_block_till_done() hass.states.async_set( entity_id, 10, {ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR}, force_update=True, ) await hass.async_block_till_done() state = hass.states.get("sensor.energy_bill") if expect_reset: assert state.attributes.get("last_period") == "2" assert state.state == "7" else: assert state.attributes.get("last_period") == 0 assert state.state == "9" async def test_self_reset_cron_pattern(hass, legacy_patchable_time): """Test cron pattern reset of meter.""" config = { "utility_meter": { "energy_bill": {"source": "sensor.energy", "cron": "0 0 1 * *"} } } await _test_self_reset(hass, config, "2017-01-31T23:59:00.000000+00:00") async def test_self_reset_quarter_hourly(hass, legacy_patchable_time): """Test quarter-hourly reset of meter.""" await _test_self_reset( hass, gen_config("quarter-hourly"), "2017-12-31T23:59:00.000000+00:00" ) async def test_self_reset_quarter_hourly_first_quarter(hass, legacy_patchable_time): """Test quarter-hourly reset of meter.""" await _test_self_reset( hass, gen_config("quarter-hourly"), "2017-12-31T23:14:00.000000+00:00" ) async def test_self_reset_quarter_hourly_second_quarter(hass, legacy_patchable_time): """Test quarter-hourly reset of meter.""" await _test_self_reset( hass, gen_config("quarter-hourly"), "2017-12-31T23:29:00.000000+00:00" ) async def test_self_reset_quarter_hourly_third_quarter(hass, legacy_patchable_time): """Test quarter-hourly reset of meter.""" await _test_self_reset( hass, gen_config("quarter-hourly"), "2017-12-31T23:44:00.000000+00:00" ) async def test_self_reset_hourly(hass, legacy_patchable_time): """Test hourly reset of meter.""" await _test_self_reset( hass, gen_config("hourly"), "2017-12-31T23:59:00.000000+00:00" ) async def test_self_reset_daily(hass, legacy_patchable_time): """Test daily reset of meter.""" await _test_self_reset( hass, gen_config("daily"), "2017-12-31T23:59:00.000000+00:00" ) async def test_self_reset_weekly(hass, legacy_patchable_time): """Test weekly reset of meter.""" await _test_self_reset( hass, gen_config("weekly"), "2017-12-31T23:59:00.000000+00:00" ) async def test_self_reset_monthly(hass, legacy_patchable_time): """Test monthly reset of meter.""" await _test_self_reset( hass, gen_config("monthly"), "2017-12-31T23:59:00.000000+00:00" ) async def test_self_reset_bimonthly(hass, legacy_patchable_time): """Test bimonthly reset of meter occurs on even months.""" await _test_self_reset( hass, gen_config("bimonthly"), "2017-12-31T23:59:00.000000+00:00" ) async def test_self_no_reset_bimonthly(hass, legacy_patchable_time): """Test bimonthly reset of meter does not occur on odd months.""" await _test_self_reset( hass, gen_config("bimonthly"), "2018-01-01T23:59:00.000000+00:00", expect_reset=False, ) async def test_self_reset_quarterly(hass, legacy_patchable_time): """Test quarterly reset of meter.""" await _test_self_reset( hass, gen_config("quarterly"), "2017-03-31T23:59:00.000000+00:00" ) async def test_self_reset_yearly(hass, legacy_patchable_time): """Test yearly reset of meter.""" await _test_self_reset( hass, gen_config("yearly"), "2017-12-31T23:59:00.000000+00:00" ) async def test_self_no_reset_yearly(hass, legacy_patchable_time): """Test yearly reset of meter does not occur after 1st January.""" await _test_self_reset( hass, gen_config("yearly"), "2018-01-01T23:59:00.000000+00:00", expect_reset=False, ) async def test_reset_yearly_offset(hass, legacy_patchable_time): """Test yearly reset of meter.""" await _test_self_reset( hass, gen_config("yearly", timedelta(days=1, minutes=10)), "2018-01-02T00:09:00.000000+00:00", ) async def test_no_reset_yearly_offset(hass, legacy_patchable_time): """Test yearly reset of meter.""" await _test_self_reset( hass, gen_config("yearly", timedelta(31)), "2018-01-30T23:59:00.000000+00:00", expect_reset=False, )
"""Base class for Checks. If you are writing your own checks you should subclass the AgentCheck class. The Check class is being deprecated so don't write new checks with it. """ # stdlib from collections import defaultdict import copy import logging import numbers import os import re import time import timeit import traceback from types import ListType, TupleType # 3p try: import psutil except ImportError: psutil = None import yaml # project from checks import check_status from util import get_hostname, get_next_id, LaconicFilter, yLoader from utils.platform import Platform from utils.profile import pretty_statistics if Platform.is_windows(): from utils.debug import run_check # noqa - windows debug purpose log = logging.getLogger(__name__) # Default methods run when collecting info about the agent in developer mode DEFAULT_PSUTIL_METHODS = ['memory_info', 'io_counters'] AGENT_METRICS_CHECK_NAME = 'agent_metrics' # Konstants class CheckException(Exception): pass class Infinity(CheckException): pass class NaN(CheckException): pass class UnknownValue(CheckException): pass #============================================================================== # DEPRECATED # ------------------------------ # If you are writing your own check, you should inherit from AgentCheck # and not this class. This class will be removed in a future version # of the agent. #============================================================================== class Check(object): """ (Abstract) class for all checks with the ability to: * store 1 (and only 1) sample for gauges per metric/tag combination * compute rates for counters * only log error messages once (instead of each time they occur) """ def __init__(self, logger): # where to store samples, indexed by metric_name # metric_name: {("sorted", "tags"): [(ts, value), (ts, value)], # tuple(tags) are stored as a key since lists are not hashable # None: [(ts, value), (ts, value)]} # untagged values are indexed by None self._sample_store = {} self._counters = {} # metric_name: bool self.logger = logger try: self.logger.addFilter(LaconicFilter()) except Exception: self.logger.exception("Trying to install laconic log filter and failed") def normalize(self, metric, prefix=None): """Turn a metric into a well-formed metric name prefix.b.c """ name = re.sub(r"[,\+\*\-/()\[\]{}\s]", "_", metric) # Eliminate multiple _ name = re.sub(r"__+", "_", name) # Don't start/end with _ name = re.sub(r"^_", "", name) name = re.sub(r"_$", "", name) # Drop ._ and _. name = re.sub(r"\._", ".", name) name = re.sub(r"_\.", ".", name) if prefix is not None: return prefix + "." + name else: return name def normalize_device_name(self, device_name): return device_name.strip().lower().replace(' ', '_') def counter(self, metric): """ Treats the metric as a counter, i.e. computes its per second derivative ACHTUNG: Resets previous values associated with this metric. """ self._counters[metric] = True self._sample_store[metric] = {} def is_counter(self, metric): "Is this metric a counter?" return metric in self._counters def gauge(self, metric): """ Treats the metric as a gauge, i.e. keep the data as is ACHTUNG: Resets previous values associated with this metric. """ self._sample_store[metric] = {} def is_metric(self, metric): return metric in self._sample_store def is_gauge(self, metric): return self.is_metric(metric) and \ not self.is_counter(metric) def get_metric_names(self): "Get all metric names" return self._sample_store.keys() def save_gauge(self, metric, value, timestamp=None, tags=None, hostname=None, device_name=None): """ Save a gauge value. """ if not self.is_gauge(metric): self.gauge(metric) self.save_sample(metric, value, timestamp, tags, hostname, device_name) def save_sample(self, metric, value, timestamp=None, tags=None, hostname=None, device_name=None): """Save a simple sample, evict old values if needed """ from util import cast_metric_val if timestamp is None: timestamp = time.time() if metric not in self._sample_store: raise CheckException("Saving a sample for an undefined metric: %s" % metric) try: value = cast_metric_val(value) except ValueError, ve: raise NaN(ve) # Sort and validate tags if tags is not None: if type(tags) not in [type([]), type(())]: raise CheckException("Tags must be a list or tuple of strings") else: tags = tuple(sorted(tags)) # Data eviction rules key = (tags, device_name) if self.is_gauge(metric): self._sample_store[metric][key] = ((timestamp, value, hostname, device_name), ) elif self.is_counter(metric): if self._sample_store[metric].get(key) is None: self._sample_store[metric][key] = [(timestamp, value, hostname, device_name)] else: self._sample_store[metric][key] = self._sample_store[metric][key][-1:] + [(timestamp, value, hostname, device_name)] else: raise CheckException("%s must be either gauge or counter, skipping sample at %s" % (metric, time.ctime(timestamp))) if self.is_gauge(metric): # store[metric][tags] = (ts, val) - only 1 value allowed assert len(self._sample_store[metric][key]) == 1, self._sample_store[metric] elif self.is_counter(metric): assert len(self._sample_store[metric][key]) in (1, 2), self._sample_store[metric] @classmethod def _rate(cls, sample1, sample2): "Simple rate" try: interval = sample2[0] - sample1[0] if interval == 0: raise Infinity() delta = sample2[1] - sample1[1] if delta < 0: raise UnknownValue() return (sample2[0], delta / interval, sample2[2], sample2[3]) except Infinity: raise except UnknownValue: raise except Exception, e: raise NaN(e) def get_sample_with_timestamp(self, metric, tags=None, device_name=None, expire=True): "Get (timestamp-epoch-style, value)" # Get the proper tags if tags is not None and isinstance(tags, ListType): tags.sort() tags = tuple(tags) key = (tags, device_name) # Never seen this metric if metric not in self._sample_store: raise UnknownValue() # Not enough value to compute rate elif self.is_counter(metric) and len(self._sample_store[metric][key]) < 2: raise UnknownValue() elif self.is_counter(metric) and len(self._sample_store[metric][key]) >= 2: res = self._rate(self._sample_store[metric][key][-2], self._sample_store[metric][key][-1]) if expire: del self._sample_store[metric][key][:-1] return res elif self.is_gauge(metric) and len(self._sample_store[metric][key]) >= 1: return self._sample_store[metric][key][-1] else: raise UnknownValue() def get_sample(self, metric, tags=None, device_name=None, expire=True): "Return the last value for that metric" x = self.get_sample_with_timestamp(metric, tags, device_name, expire) assert isinstance(x, TupleType) and len(x) == 4, x return x[1] def get_samples_with_timestamps(self, expire=True): "Return all values {metric: (ts, value)} for non-tagged metrics" values = {} for m in self._sample_store: try: values[m] = self.get_sample_with_timestamp(m, expire=expire) except Exception: pass return values def get_samples(self, expire=True): "Return all values {metric: value} for non-tagged metrics" values = {} for m in self._sample_store: try: # Discard the timestamp values[m] = self.get_sample_with_timestamp(m, expire=expire)[1] except Exception: pass return values def get_metrics(self, expire=True): """Get all metrics, including the ones that are tagged. This is the preferred method to retrieve metrics @return the list of samples @rtype [(metric_name, timestamp, value, {"tags": ["tag1", "tag2"]}), ...] """ metrics = [] for m in self._sample_store: try: for key in self._sample_store[m]: tags, device_name = key try: ts, val, hostname, device_name = self.get_sample_with_timestamp(m, tags, device_name, expire) except UnknownValue: continue attributes = {} if tags: attributes['tags'] = list(tags) if hostname: attributes['host_name'] = hostname if device_name: attributes['device_name'] = device_name metrics.append((m, int(ts), val, attributes)) except Exception: pass return metrics class AgentCheck(object): OK, WARNING, CRITICAL, UNKNOWN = (0, 1, 2, 3) SOURCE_TYPE_NAME = None DEFAULT_MIN_COLLECTION_INTERVAL = 0 _enabled_checks = [] @classmethod def is_check_enabled(cls, name): return name in cls._enabled_checks def __init__(self, name, init_config, agentConfig, instances=None): """ Initialize a new check. :param name: The name of the check :param init_config: The config for initializing the check :param agentConfig: The global configuration for the agent :param instances: A list of configuration objects for each instance. """ from aggregator import MetricsAggregator self._enabled_checks.append(name) self._enabled_checks = list(set(self._enabled_checks)) self.name = name self.init_config = init_config or {} self.agentConfig = agentConfig self.in_developer_mode = agentConfig.get('developer_mode') and psutil self._internal_profiling_stats = None self.hostname = agentConfig.get('checksd_hostname') or get_hostname(agentConfig) self.log = logging.getLogger('%s.%s' % (__name__, name)) self.aggregator = MetricsAggregator( self.hostname, formatter=agent_formatter, recent_point_threshold=agentConfig.get('recent_point_threshold', None), histogram_aggregates=agentConfig.get('histogram_aggregates'), histogram_percentiles=agentConfig.get('histogram_percentiles') ) self.events = [] self.service_checks = [] self.instances = instances or [] self.warnings = [] self.library_versions = None self.last_collection_time = defaultdict(int) self._instance_metadata = [] self.svc_metadata = [] self.historate_dict = {} def instance_count(self): """ Return the number of instances that are configured for this check. """ return len(self.instances) def gauge(self, metric, value, tags=None, hostname=None, device_name=None, timestamp=None): """ Record the value of a gauge, with optional tags, hostname and device name. :param metric: The name of the metric :param value: The value of the gauge :param tags: (optional) A list of tags for this metric :param hostname: (optional) A hostname for this metric. Defaults to the current hostname. :param device_name: (optional) The device name for this metric :param timestamp: (optional) The timestamp for this metric value """ self.aggregator.gauge(metric, value, tags, hostname, device_name, timestamp) def increment(self, metric, value=1, tags=None, hostname=None, device_name=None): """ Increment a counter with optional tags, hostname and device name. :param metric: The name of the metric :param value: The value to increment by :param tags: (optional) A list of tags for this metric :param hostname: (optional) A hostname for this metric. Defaults to the current hostname. :param device_name: (optional) The device name for this metric """ self.aggregator.increment(metric, value, tags, hostname, device_name) def decrement(self, metric, value=-1, tags=None, hostname=None, device_name=None): """ Increment a counter with optional tags, hostname and device name. :param metric: The name of the metric :param value: The value to decrement by :param tags: (optional) A list of tags for this metric :param hostname: (optional) A hostname for this metric. Defaults to the current hostname. :param device_name: (optional) The device name for this metric """ self.aggregator.decrement(metric, value, tags, hostname, device_name) def count(self, metric, value=0, tags=None, hostname=None, device_name=None): """ Submit a raw count with optional tags, hostname and device name :param metric: The name of the metric :param value: The value :param tags: (optional) A list of tags for this metric :param hostname: (optional) A hostname for this metric. Defaults to the current hostname. :param device_name: (optional) The device name for this metric """ self.aggregator.submit_count(metric, value, tags, hostname, device_name) def monotonic_count(self, metric, value=0, tags=None, hostname=None, device_name=None): """ Submits a raw count with optional tags, hostname and device name based on increasing counter values. E.g. 1, 3, 5, 7 will submit 6 on flush. Note that reset counters are skipped. :param metric: The name of the metric :param value: The value of the rate :param tags: (optional) A list of tags for this metric :param hostname: (optional) A hostname for this metric. Defaults to the current hostname. :param device_name: (optional) The device name for this metric """ self.aggregator.count_from_counter(metric, value, tags, hostname, device_name) def rate(self, metric, value, tags=None, hostname=None, device_name=None): """ Submit a point for a metric that will be calculated as a rate on flush. Values will persist across each call to `check` if there is not enough point to generate a rate on the flush. :param metric: The name of the metric :param value: The value of the rate :param tags: (optional) A list of tags for this metric :param hostname: (optional) A hostname for this metric. Defaults to the current hostname. :param device_name: (optional) The device name for this metric """ self.aggregator.rate(metric, value, tags, hostname, device_name) def histogram(self, metric, value, tags=None, hostname=None, device_name=None): """ Sample a histogram value, with optional tags, hostname and device name. :param metric: The name of the metric :param value: The value to sample for the histogram :param tags: (optional) A list of tags for this metric :param hostname: (optional) A hostname for this metric. Defaults to the current hostname. :param device_name: (optional) The device name for this metric """ self.aggregator.histogram(metric, value, tags, hostname, device_name) @classmethod def generate_historate_func(cls, excluding_tags): def fct(self, metric, value, tags=None, hostname=None, device_name=None): cls.historate(self, metric, value, excluding_tags, tags=tags, hostname=hostname, device_name=device_name) return fct @classmethod def generate_histogram_func(cls, excluding_tags): def fct(self, metric, value, tags=None, hostname=None, device_name=None): tags = list(tags) # Use a copy of the list to avoid removing tags from originial for tag in list(tags): for exc_tag in excluding_tags: if tag.startswith(exc_tag + ":"): tags.remove(tag) cls.histogram(self, metric, value, tags=tags, hostname=hostname, device_name=device_name) return fct def historate(self, metric, value, excluding_tags, tags=None, hostname=None, device_name=None): """ Function to create a histogram metric for "rate" like metrics. Warning this doesn't use the harmonic mean, beware of what it means when using it. :param metric: The name of the metric :param value: The value to sample for the histogram :param excluding_tags: A list of tags that will be removed when computing the histogram :param tags: (optional) A list of tags for this metric :param hostname: (optional) A hostname for this metric. Defaults to the current hostname. :param device_name: (optional) The device name for this metric """ tags = list(tags) # Use a copy of the list to avoid removing tags from originial context = [metric] if tags is not None: context.append("-".join(sorted(tags))) if hostname is not None: context.append("host:" + hostname) if device_name is not None: context.append("device:" + device_name) now = time.time() context = tuple(context) if context in self.historate_dict: if tags is not None: for tag in list(tags): for exc_tag in excluding_tags: if tag.startswith("{0}:".format(exc_tag)): tags.remove(tag) prev_value, prev_ts = self.historate_dict[context] rate = float(value - prev_value) / float(now - prev_ts) self.aggregator.histogram(metric, rate, tags, hostname, device_name) self.historate_dict[context] = (value, now) def set(self, metric, value, tags=None, hostname=None, device_name=None): """ Sample a set value, with optional tags, hostname and device name. :param metric: The name of the metric :param value: The value for the set :param tags: (optional) A list of tags for this metric :param hostname: (optional) A hostname for this metric. Defaults to the current hostname. :param device_name: (optional) The device name for this metric """ self.aggregator.set(metric, value, tags, hostname, device_name) def event(self, event): """ Save an event. :param event: The event payload as a dictionary. Has the following structure: { "timestamp": int, the epoch timestamp for the event, "event_type": string, the event time name, "api_key": string, the api key of the account to associate the event with, "msg_title": string, the title of the event, "msg_text": string, the text body of the event, "alert_type": (optional) string, one of ('error', 'warning', 'success', 'info'). Defaults to 'info'. "source_type_name": (optional) string, the source type name, "host": (optional) string, the name of the host, "tags": (optional) list, a list of tags to associate with this event } """ if event.get('api_key') is None: event['api_key'] = self.agentConfig['api_key'] self.events.append(event) def service_check(self, check_name, status, tags=None, timestamp=None, hostname=None, check_run_id=None, message=None): """ Save a service check. :param check_name: string, name of the service check :param status: int, describing the status. 0 for success, 1 for warning, 2 for failure :param tags: (optional) list of strings, a list of tags for this run :param timestamp: (optional) float, unix timestamp for when the run occurred :param hostname: (optional) str, host that generated the service check. Defaults to the host_name of the agent :param check_run_id: (optional) int, id used for logging and tracing purposes. Doesn't need to be unique. If not specified, one will be generated. """ if hostname is None: hostname = self.hostname if message is not None: message = unicode(message) # ascii converts to unicode but not viceversa self.service_checks.append( create_service_check(check_name, status, tags, timestamp, hostname, check_run_id, message) ) def service_metadata(self, meta_name, value): """ Save metadata. :param meta_name: metadata key name :type meta_name: string :param value: metadata value :type value: string """ self._instance_metadata.append((meta_name, unicode(value))) def has_events(self): """ Check whether the check has saved any events @return whether or not the check has saved any events @rtype boolean """ return len(self.events) > 0 def get_metrics(self): """ Get all metrics, including the ones that are tagged. @return the list of samples @rtype [(metric_name, timestamp, value, {"tags": ["tag1", "tag2"]}), ...] """ return self.aggregator.flush() def get_events(self): """ Return a list of the events saved by the check, if any @return the list of events saved by this check @rtype list of event dictionaries """ events = self.events self.events = [] return events def get_service_checks(self): """ Return a list of the service checks saved by the check, if any and clears them out of the instance's service_checks list @return the list of service checks saved by this check @rtype list of service check dicts """ service_checks = self.service_checks self.service_checks = [] return service_checks def _roll_up_instance_metadata(self): """ Concatenate and flush instance metadata. """ self.svc_metadata.append(dict((k, v) for (k, v) in self._instance_metadata)) self._instance_metadata = [] def get_service_metadata(self): """ Return a list of the metadata dictionaries saved by the check -if any- and clears them out of the instance's service_checks list @return the list of metadata saved by this check @rtype list of metadata dicts """ if self._instance_metadata: self._roll_up_instance_metadata() service_metadata = self.svc_metadata self.svc_metadata = [] return service_metadata def has_warnings(self): """ Check whether the instance run created any warnings """ return len(self.warnings) > 0 def warning(self, warning_message): """ Add a warning message that will be printed in the info page :param warning_message: String. Warning message to be displayed """ warning_message = str(warning_message) self.log.warning(warning_message) self.warnings.append(warning_message) def get_library_info(self): if self.library_versions is not None: return self.library_versions try: self.library_versions = self.get_library_versions() except NotImplementedError: pass def get_library_versions(self): """ Should return a string that shows which version of the needed libraries are used """ raise NotImplementedError def get_warnings(self): """ Return the list of warnings messages to be displayed in the info page """ warnings = self.warnings self.warnings = [] return warnings @staticmethod def _get_statistic_name_from_method(method_name): return method_name[4:] if method_name.startswith('get_') else method_name @staticmethod def _collect_internal_stats(methods=None): current_process = psutil.Process(os.getpid()) methods = methods or DEFAULT_PSUTIL_METHODS filtered_methods = [m for m in methods if hasattr(current_process, m)] stats = {} for method in filtered_methods: # Go from `get_memory_info` -> `memory_info` stat_name = AgentCheck._get_statistic_name_from_method(method) try: raw_stats = getattr(current_process, method)() try: stats[stat_name] = raw_stats._asdict() except AttributeError: if isinstance(raw_stats, numbers.Number): stats[stat_name] = raw_stats else: log.warn("Could not serialize output of {0} to dict".format(method)) except psutil.AccessDenied: log.warn("Cannot call psutil method {} : Access Denied".format(method)) return stats def _set_internal_profiling_stats(self, before, after): self._internal_profiling_stats = {'before': before, 'after': after} def _get_internal_profiling_stats(self): """ If in developer mode, return a dictionary of statistics about the check run """ stats = self._internal_profiling_stats self._internal_profiling_stats = None return stats def run(self): """ Run all instances. """ # Store run statistics if needed before, after = None, None if self.in_developer_mode and self.name != AGENT_METRICS_CHECK_NAME: try: before = AgentCheck._collect_internal_stats() except Exception: # It's fine if we can't collect stats for the run, just log and proceed self.log.debug("Failed to collect Agent Stats before check {0}".format(self.name)) instance_statuses = [] for i, instance in enumerate(self.instances): try: min_collection_interval = instance.get( 'min_collection_interval', self.init_config.get( 'min_collection_interval', self.DEFAULT_MIN_COLLECTION_INTERVAL ) ) now = time.time() if now - self.last_collection_time[i] < min_collection_interval: self.log.debug("Not running instance #{0} of check {1} as it ran less than {2}s ago".format(i, self.name, min_collection_interval)) continue self.last_collection_time[i] = now check_start_time = None if self.in_developer_mode: check_start_time = timeit.default_timer() self.check(copy.deepcopy(instance)) instance_check_stats = None if check_start_time is not None: instance_check_stats = {'run_time': timeit.default_timer() - check_start_time} if self.has_warnings(): instance_status = check_status.InstanceStatus( i, check_status.STATUS_WARNING, warnings=self.get_warnings(), instance_check_stats=instance_check_stats ) else: instance_status = check_status.InstanceStatus( i, check_status.STATUS_OK, instance_check_stats=instance_check_stats ) except Exception, e: self.log.exception("Check '%s' instance #%s failed" % (self.name, i)) instance_status = check_status.InstanceStatus( i, check_status.STATUS_ERROR, error=str(e), tb=traceback.format_exc() ) finally: self._roll_up_instance_metadata() instance_statuses.append(instance_status) if self.in_developer_mode and self.name != AGENT_METRICS_CHECK_NAME: try: after = AgentCheck._collect_internal_stats() self._set_internal_profiling_stats(before, after) log.info("\n \t %s %s" % (self.name, pretty_statistics(self._internal_profiling_stats))) except Exception: # It's fine if we can't collect stats for the run, just log and proceed self.log.debug("Failed to collect Agent Stats after check {0}".format(self.name)) return instance_statuses def check(self, instance): """ Overriden by the check class. This will be called to run the check. :param instance: A dict with the instance information. This will vary depending on your config structure. """ raise NotImplementedError() def stop(self): """ To be executed when the agent is being stopped to clean ressources """ pass @classmethod def from_yaml(cls, path_to_yaml=None, agentConfig=None, yaml_text=None, check_name=None): """ A method used for testing your check without running the agent. """ if path_to_yaml: check_name = os.path.basename(path_to_yaml).split('.')[0] try: f = open(path_to_yaml) except IOError: raise Exception('Unable to open yaml config: %s' % path_to_yaml) yaml_text = f.read() f.close() config = yaml.load(yaml_text, Loader=yLoader) try: check = cls(check_name, config.get('init_config') or {}, agentConfig or {}, config.get('instances')) except TypeError: # Compatibility for the check not supporting instances check = cls(check_name, config.get('init_config') or {}, agentConfig or {}) return check, config.get('instances', []) def normalize(self, metric, prefix=None, fix_case=False): """ Turn a metric into a well-formed metric name prefix.b.c :param metric The metric name to normalize :param prefix A prefix to to add to the normalized name, default None :param fix_case A boolean, indicating whether to make sure that the metric name returned is in underscore_case """ if fix_case: name = self.convert_to_underscore_separated(metric) if prefix is not None: prefix = self.convert_to_underscore_separated(prefix) else: name = re.sub(r"[,\+\*\-/()\[\]{}\s]", "_", metric) # Eliminate multiple _ name = re.sub(r"__+", "_", name) # Don't start/end with _ name = re.sub(r"^_", "", name) name = re.sub(r"_$", "", name) # Drop ._ and _. name = re.sub(r"\._", ".", name) name = re.sub(r"_\.", ".", name) if prefix is not None: return prefix + "." + name else: return name FIRST_CAP_RE = re.compile('(.)([A-Z][a-z]+)') ALL_CAP_RE = re.compile('([a-z0-9])([A-Z])') METRIC_REPLACEMENT = re.compile(r'([^a-zA-Z0-9_.]+)|(^[^a-zA-Z]+)') DOT_UNDERSCORE_CLEANUP = re.compile(r'_*\._*') def convert_to_underscore_separated(self, name): """ Convert from CamelCase to camel_case And substitute illegal metric characters """ metric_name = self.FIRST_CAP_RE.sub(r'\1_\2', name) metric_name = self.ALL_CAP_RE.sub(r'\1_\2', metric_name).lower() metric_name = self.METRIC_REPLACEMENT.sub('_', metric_name) return self.DOT_UNDERSCORE_CLEANUP.sub('.', metric_name).strip('_') @staticmethod def read_config(instance, key, message=None, cast=None): val = instance.get(key) if val is None: message = message or 'Must provide `%s` value in instance config' % key raise Exception(message) if cast is None: return val else: return cast(val) def agent_formatter(metric, value, timestamp, tags, hostname, device_name=None, metric_type=None, interval=None): """ Formats metrics coming from the MetricsAggregator. Will look like: (metric, timestamp, value, {"tags": ["tag1", "tag2"], ...}) """ attributes = {} if tags: attributes['tags'] = list(tags) if hostname: attributes['hostname'] = hostname if device_name: attributes['device_name'] = device_name if metric_type: attributes['type'] = metric_type if interval: # For now, don't send the interval for agent metrics, since they don't # come at very predictable intervals. # attributes['interval'] = None pass if attributes: return (metric, int(timestamp), value, attributes) return (metric, int(timestamp), value) def create_service_check(check_name, status, tags=None, timestamp=None, hostname=None, check_run_id=None, message=None): """ Create a service_check dict. See AgentCheck.service_check() for docs on the parameters. """ if check_run_id is None: check_run_id = get_next_id('service_check') return { 'id': check_run_id, 'check': check_name, 'status': status, 'host_name': hostname, 'tags': tags, 'timestamp': float(timestamp or time.time()), 'message': message }
# Copyright (c) 2012 Citrix Systems, 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. """The Aggregate admin API extension.""" import datetime from webob import exc from nova.api.openstack import extensions from nova.compute import api as compute_api from nova import exception from nova.openstack.common.gettextutils import _ from nova.openstack.common import log as logging from nova import utils LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer('compute', 'aggregates') def _get_context(req): return req.environ['nova.context'] def get_host_from_body(fn): """Makes sure that the host exists.""" def wrapped(self, req, id, body, *args, **kwargs): if len(body) == 1 and "host" in body: host = body['host'] else: raise exc.HTTPBadRequest() return fn(self, req, id, host, *args, **kwargs) return wrapped class AggregateController(object): """The Host Aggregates API controller for the OpenStack API.""" def __init__(self): self.api = compute_api.AggregateAPI() def index(self, req): """Returns a list a host aggregate's id, name, availability_zone.""" context = _get_context(req) authorize(context) aggregates = self.api.get_aggregate_list(context) return {'aggregates': [self._marshall_aggregate(a)['aggregate'] for a in aggregates]} def create(self, req, body): """ Creates an aggregate, given its name and optional availability zone. """ context = _get_context(req) authorize(context) if len(body) != 1: raise exc.HTTPBadRequest() try: host_aggregate = body["aggregate"] name = host_aggregate["name"] except KeyError: raise exc.HTTPBadRequest() avail_zone = host_aggregate.get("availability_zone") try: utils.check_string_length(name, "Aggregate name", 1, 255) except exception.InvalidInput as e: raise exc.HTTPBadRequest(explanation=e.format_message()) try: aggregate = self.api.create_aggregate(context, name, avail_zone) except exception.AggregateNameExists as e: LOG.info(e) raise exc.HTTPConflict() except exception.InvalidAggregateAction as e: LOG.info(e) raise return self._marshall_aggregate(aggregate) def show(self, req, id): """Shows the details of an aggregate, hosts and metadata included.""" context = _get_context(req) authorize(context) try: aggregate = self.api.get_aggregate(context, id) except exception.AggregateNotFound: LOG.info(_("Cannot show aggregate: %s"), id) raise exc.HTTPNotFound() return self._marshall_aggregate(aggregate) def update(self, req, id, body): """Updates the name and/or availability_zone of given aggregate.""" context = _get_context(req) authorize(context) if len(body) != 1: raise exc.HTTPBadRequest() try: updates = body["aggregate"] except KeyError: raise exc.HTTPBadRequest() if len(updates) < 1: raise exc.HTTPBadRequest() for key in updates.keys(): if key not in ["name", "availability_zone"]: raise exc.HTTPBadRequest() if 'name' in updates: try: utils.check_string_length(updates['name'], "Aggregate name", 1, 255) except exception.InvalidInput as e: raise exc.HTTPBadRequest(explanation=e.format_message()) try: aggregate = self.api.update_aggregate(context, id, updates) except exception.AggregateNotFound: LOG.info(_('Cannot update aggregate: %s'), id) raise exc.HTTPNotFound() except exception.InvalidAggregateAction as e: raise exc.HTTPBadRequest(explanation=e.format_message()) return self._marshall_aggregate(aggregate) def delete(self, req, id): """Removes an aggregate by id.""" context = _get_context(req) authorize(context) try: self.api.delete_aggregate(context, id) except exception.AggregateNotFound: LOG.info(_('Cannot delete aggregate: %s'), id) raise exc.HTTPNotFound() def action(self, req, id, body): _actions = { 'add_host': self._add_host, 'remove_host': self._remove_host, 'set_metadata': self._set_metadata, } for action, data in body.iteritems(): if action not in _actions.keys(): msg = _('Aggregates does not have %s action') % action raise exc.HTTPBadRequest(explanation=msg) return _actions[action](req, id, data) raise exc.HTTPBadRequest(explanation=_("Invalid request body")) @get_host_from_body def _add_host(self, req, id, host): """Adds a host to the specified aggregate.""" context = _get_context(req) authorize(context) try: aggregate = self.api.add_host_to_aggregate(context, id, host) except (exception.AggregateNotFound, exception.ComputeHostNotFound): LOG.info(_('Cannot add host %(host)s in aggregate %(id)s'), {'host': host, 'id': id}) raise exc.HTTPNotFound() except (exception.AggregateHostExists, exception.InvalidAggregateAction) as e: LOG.info(_('Cannot add host %(host)s in aggregate %(id)s'), {'host': host, 'id': id}) raise exc.HTTPConflict(explanation=e.format_message()) return self._marshall_aggregate(aggregate) @get_host_from_body def _remove_host(self, req, id, host): """Removes a host from the specified aggregate.""" context = _get_context(req) authorize(context) try: aggregate = self.api.remove_host_from_aggregate(context, id, host) except (exception.AggregateNotFound, exception.AggregateHostNotFound, exception.ComputeHostNotFound): LOG.info(_('Cannot remove host %(host)s in aggregate %(id)s'), {'host': host, 'id': id}) raise exc.HTTPNotFound() except exception.InvalidAggregateAction: LOG.info(_('Cannot remove host %(host)s in aggregate %(id)s'), {'host': host, 'id': id}) raise exc.HTTPConflict() return self._marshall_aggregate(aggregate) def _set_metadata(self, req, id, body): """Replaces the aggregate's existing metadata with new metadata.""" context = _get_context(req) authorize(context) if len(body) != 1: raise exc.HTTPBadRequest() try: metadata = body["metadata"] except KeyError: raise exc.HTTPBadRequest() try: aggregate = self.api.update_aggregate_metadata(context, id, metadata) except exception.AggregateNotFound: LOG.info(_('Cannot set metadata %(metadata)s in aggregate %(id)s'), {'metadata': metadata, 'id': id}) raise exc.HTTPNotFound() except exception.InvalidAggregateAction as e: raise exc.HTTPBadRequest(explanation=e.format_message()) return self._marshall_aggregate(aggregate) def _marshall_aggregate(self, aggregate): _aggregate = {} for key, value in aggregate.items(): # NOTE(danms): The original API specified non-TZ-aware timestamps if isinstance(value, datetime.datetime): value = value.replace(tzinfo=None) _aggregate[key] = value return {"aggregate": _aggregate} class Aggregates(extensions.ExtensionDescriptor): """Admin-only aggregate administration.""" name = "Aggregates" alias = "os-aggregates" namespace = "http://docs.openstack.org/compute/ext/aggregates/api/v1.1" updated = "2012-01-12T00:00:00+00:00" def get_resources(self): resources = [] res = extensions.ResourceExtension('os-aggregates', AggregateController(), member_actions={"action": "POST", }) resources.append(res) return resources
# -*- test-case-name: vumi_message_store.tests.test_batch_info_cache -*- # -*- coding: utf-8 -*- from calendar import timegm from datetime import datetime from twisted.internet.defer import returnValue from vumi.persist.redis_base import Manager from vumi.message import TransportEvent, VUMI_DATE_FORMAT from vumi.errors import VumiError def to_timestamp(timestamp): """ Return a timestamp value for a datetime value. """ if isinstance(timestamp, basestring): timestamp = datetime.strptime(timestamp, VUMI_DATE_FORMAT) # We can't use time.mktime(), because that takes local time and we have # UTC. The UTC equivalent, for some obscure reason, is in the calendar # module. return timegm(timestamp.timetuple()) class BatchInfoCacheException(VumiError): pass class BatchInfoCache(object): """ Redis-based cache for assorted batch-related information that is expensive to acquire from Riak but useful to have low-latency access to. """ BATCH_KEY = 'batches' OUTBOUND_KEY = 'outbound' OUTBOUND_COUNT_KEY = 'outbound_count' INBOUND_KEY = 'inbound' INBOUND_COUNT_KEY = 'inbound_count' TO_ADDR_KEY = 'to_addr_hll' FROM_ADDR_KEY = 'from_addr_hll' EVENT_KEY = 'event' EVENT_COUNT_KEY = 'event_count' STATUS_KEY = 'status' TRUNCATE_MESSAGE_KEY_ZSET_AT = 2000 def __init__(self, redis): # Store redis as `manager` as well since @Manager.calls_manager # requires it to be named as such. self.redis = self.manager = redis def key(self, *args): return ':'.join([unicode(a) for a in args]) def batch_key(self, *args): return self.key(self.BATCH_KEY, *args) def outbound_key(self, batch_id): return self.batch_key(self.OUTBOUND_KEY, batch_id) def outbound_count_key(self, batch_id): return self.batch_key(self.OUTBOUND_COUNT_KEY, batch_id) def inbound_key(self, batch_id): return self.batch_key(self.INBOUND_KEY, batch_id) def inbound_count_key(self, batch_id): return self.batch_key(self.INBOUND_COUNT_KEY, batch_id) def to_addr_key(self, batch_id): return self.batch_key(self.TO_ADDR_KEY, batch_id) def from_addr_key(self, batch_id): return self.batch_key(self.FROM_ADDR_KEY, batch_id) def status_key(self, batch_id): return self.batch_key(self.STATUS_KEY, batch_id) def event_key(self, batch_id): return self.batch_key(self.EVENT_KEY, batch_id) def event_count_key(self, batch_id): return self.batch_key(self.EVENT_COUNT_KEY, batch_id) def obsolete_keys(self, batch_id): """ Return a list of obsolete keys that should be cleared. """ return [ self.batch_key("to_addr", batch_id), self.batch_key("from_addr", batch_id), ] @Manager.calls_manager def _truncate_keys(self, redis_key, truncate_at): truncate_at = (truncate_at or self.TRUNCATE_MESSAGE_KEY_ZSET_AT) keys_removed = yield self.redis.zremrangebyrank( redis_key, 0, -truncate_at - 1) returnValue(keys_removed) def truncate_inbound_message_keys(self, batch_id, truncate_at=None): return self._truncate_keys(self.inbound_key(batch_id), truncate_at) def truncate_outbound_message_keys(self, batch_id, truncate_at=None): return self._truncate_keys(self.outbound_key(batch_id), truncate_at) def truncate_event_keys(self, batch_id, truncate_at=None): return self._truncate_keys(self.event_key(batch_id), truncate_at) @Manager.calls_manager def batch_start(self, batch_id): """ Create the counter keys and status hash for a batch and add the batch identifier to the set of tracked batches. A call to this isn't strictly necessary, but is good for general housekeeping. This operation idempotent. """ # TODO: Do we really want to keep a set full of batch identifiers? yield self.redis.sadd(self.batch_key(), batch_id) yield self.redis.set(self.inbound_count_key(batch_id), 0) yield self.redis.set(self.outbound_count_key(batch_id), 0) yield self.redis.set(self.event_count_key(batch_id), 0) # If the status hash already exists and has any keys in it, this will # not reset those keys to zero. events = (TransportEvent.EVENT_TYPES.keys() + ['delivery_report.%s' % status for status in TransportEvent.DELIVERY_STATUSES] + ['sent']) for event in events: yield self.redis.hsetnx(self.status_key(batch_id), event, 0) def batch_exists(self, batch_id): return self.redis.sismember(self.batch_key(), batch_id) @Manager.calls_manager def clear_batch(self, batch_id): """ Removes all cached values for the given batch_id, useful before a reconciliation happens to ensure that we start from scratch. NOTE: This will reset all counters back to zero and will increment them as messages are received. If your UI depends on your cached values your UI values might be off while the reconciliation is taking place. """ for key in self.obsolete_keys(batch_id): yield self.redis.delete(key) yield self.redis.delete(self.inbound_key(batch_id)) yield self.redis.delete(self.inbound_count_key(batch_id)) yield self.redis.delete(self.outbound_key(batch_id)) yield self.redis.delete(self.outbound_count_key(batch_id)) yield self.redis.delete(self.event_key(batch_id)) yield self.redis.delete(self.event_count_key(batch_id)) yield self.redis.delete(self.status_key(batch_id)) yield self.redis.srem(self.batch_key(), batch_id) @Manager.calls_manager def add_inbound_message(self, batch_id, msg): """ Add an inbound message to the cache for the given batch_id. """ timestamp = to_timestamp(msg["timestamp"]) yield self.add_inbound_message_key( batch_id, msg["message_id"], timestamp) yield self.add_from_addr(batch_id, msg['from_addr']) @Manager.calls_manager def add_inbound_message_key(self, batch_id, message_key, timestamp): """ Add a message key, weighted with the timestamp to the batch_id. """ new_entry = yield self.redis.zadd(self.inbound_key(batch_id), **{ message_key.encode('utf-8'): timestamp, }) if new_entry: yield self.redis.incr(self.inbound_count_key(batch_id)) yield self.truncate_inbound_message_keys(batch_id) def add_from_addr(self, batch_id, *from_addrs): """ Add a from address to the HyperLogLog counter for the batch. """ if len(from_addrs) == 0: return from_addrs = [from_addr.encode('utf-8') for from_addr in from_addrs] return self.redis.pfadd(self.from_addr_key(batch_id), *from_addrs) @Manager.calls_manager def add_outbound_message(self, batch_id, msg): """ Add an outbound message to the cache for the given batch_id. """ timestamp = to_timestamp(msg['timestamp']) yield self.add_outbound_message_key( batch_id, msg['message_id'], timestamp) yield self.add_to_addr(batch_id, msg['to_addr']) @Manager.calls_manager def add_outbound_message_key(self, batch_id, message_key, timestamp): """ Add a message key, weighted with the timestamp to the batch_id. """ new_entry = yield self.redis.zadd(self.outbound_key(batch_id), **{ message_key.encode('utf-8'): timestamp, }) if new_entry: yield self.increment_event_status(batch_id, 'sent') yield self.redis.incr(self.outbound_count_key(batch_id)) yield self.truncate_outbound_message_keys(batch_id) def add_to_addr(self, batch_id, *to_addrs): """ Add a from address to the HyperLogLog counter for the batch. """ if len(to_addrs) == 0: return to_addrs = [to_addr.encode('utf-8') for to_addr in to_addrs] return self.redis.pfadd(self.to_addr_key(batch_id), *to_addrs) @Manager.calls_manager def add_event(self, batch_id, event): """ Add an event to the cache for the given batch_id """ event_id = event['event_id'] timestamp = to_timestamp(event['timestamp']) event_type = event['event_type'] if event_type == 'delivery_report': event_type = "%s.%s" % (event_type, event['delivery_status']) yield self.add_event_key(batch_id, event_id, event_type, timestamp) @Manager.calls_manager def add_event_key(self, batch_id, event_key, event_type, timestamp): """ Add the event key to the set of known event keys. If the event is a delivery report, event_type should include the delivery status. """ new_entry = yield self.redis.zadd(self.event_key(batch_id), **{ event_key.encode('utf-8'): timestamp, }) if new_entry: yield self.redis.incr(self.event_count_key(batch_id)) yield self.truncate_event_keys(batch_id) yield self.increment_event_status(batch_id, event_type) @Manager.calls_manager def increment_event_status(self, batch_id, event_type, count=1): """ Increment the status for the given event_type for the given batch_id. If the event is a delivery report, event_type should include the delivery status. """ status_key = self.status_key(batch_id) yield self.redis.hincrby(status_key, event_type, count) if event_type.startswith("delivery_report."): yield self.redis.hincrby(status_key, "delivery_report", count) @Manager.calls_manager def add_inbound_message_count(self, batch_id, count): """ Add a count to all inbound message counters. (Used for recon.) """ yield self.redis.incr(self.inbound_count_key(batch_id), count) @Manager.calls_manager def add_outbound_message_count(self, batch_id, count): """ Add a count to all outbound message counters. (Used for recon.) """ yield self.increment_event_status(batch_id, 'sent', count) yield self.redis.incr(self.outbound_count_key(batch_id), count) @Manager.calls_manager def add_event_count(self, batch_id, status, count): """ Add a count to all relevant event counters. (Used for recon.) """ yield self.increment_event_status(batch_id, status, count) yield self.redis.incr(self.event_count_key(batch_id), count) @Manager.calls_manager def get_batch_status(self, batch_id): """ Return a dictionary containing the latest event stats for the given batch_id. """ stats = yield self.redis.hgetall(self.status_key(batch_id)) returnValue(dict([(k, int(v)) for k, v in stats.iteritems()])) @Manager.calls_manager def _get_counter_value(self, counter_key): count = yield self.redis.get(counter_key) returnValue(0 if count is None else int(count)) def get_inbound_message_count(self, batch_id): """ Return the count of inbound messages. """ return self._get_counter_value(self.inbound_count_key(batch_id)) def get_outbound_message_count(self, batch_id): """ Return the count of outbound messages. """ return self._get_counter_value(self.outbound_count_key(batch_id)) def get_event_count(self, batch_id): """ Return the count of events. """ return self._get_counter_value(self.event_count_key(batch_id)) def get_from_addr_count(self, batch_id): """ Return the count of from addresses. """ return self.redis.pfcount(self.from_addr_key(batch_id)) def get_to_addr_count(self, batch_id): """ Return the count of to addresses. """ return self.redis.pfcount(self.to_addr_key(batch_id)) @Manager.calls_manager def rebuild_cache(self, batch_id, qms, page_size=None): """ Rebuild the cache using the provided IQueryMessageStore implementation. """ yield self.clear_batch(batch_id) yield self.batch_start(batch_id) yield self._rebuild_inbound_messages(batch_id, qms, page_size) yield self._rebuild_outbound_messages(batch_id, qms, page_size) yield self._rebuild_events(batch_id, qms, page_size) @Manager.calls_manager def _rebuild_inbound_messages(self, batch_id, qms, page_size=None): """ Rebuild the cache by loading the latest inbound messages for the given batch into the cache and counting all the messages. """ inbound_page = yield qms.list_batch_inbound_messages( batch_id, page_size=page_size) count = 0 recents_added = False while inbound_page is not None: from_addrs = set() for key, timestamp, from_addr in inbound_page: count += 1 from_addrs.add(from_addr) # Treat the most recent messages as though we were recording # them in flight. if not recents_added: yield self.add_inbound_message_key( batch_id, key, to_timestamp(timestamp)) yield self.add_from_addr(batch_id, from_addr) if count == self.TRUNCATE_MESSAGE_KEY_ZSET_AT: recents_added = True count = 0 yield self.add_from_addr(batch_id, *from_addrs) # After storing the most recent messages, count the rest, updating # the count in Redis after processing each page. if recents_added: yield self.add_inbound_message_count(batch_id, count) count = 0 inbound_page = yield inbound_page.next_page() @Manager.calls_manager def _rebuild_outbound_messages(self, batch_id, qms, page_size=None): """ Rebuild the cache by loading the latest outbound messages for the given batch into the cache and counting all the messages. """ outbound_page = yield qms.list_batch_outbound_messages( batch_id, page_size=page_size) count = 0 recents_added = False while outbound_page is not None: to_addrs = set() for key, timestamp, to_addr in outbound_page: count += 1 to_addrs.add(to_addr) # Treat the most recent messages as though we were recording # them in flight. if not recents_added: yield self.add_outbound_message_key( batch_id, key, to_timestamp(timestamp)) if count == self.TRUNCATE_MESSAGE_KEY_ZSET_AT: recents_added = True count = 0 yield self.add_to_addr(batch_id, *to_addrs) # After storing the most recent messages, count the rest, updating # the count in Redis after processing each page. if recents_added: yield self.add_outbound_message_count(batch_id, count) count = 0 outbound_page = yield outbound_page.next_page() @Manager.calls_manager def _rebuild_events(self, batch_id, qms, page_size=None): """ Rebuild the cache by loading the latest events for the given batch into the cache and counting all the events. """ event_page = yield qms.list_batch_events(batch_id, page_size=page_size) count = 0 recents_added = False statuses = {} while event_page is not None: for key, timestamp, status in event_page: count += 1 # Treat the most recent events as though we were recording # them in flight. if not recents_added: yield self.add_event_key( batch_id, key, status, to_timestamp(timestamp)) if count == self.TRUNCATE_MESSAGE_KEY_ZSET_AT: recents_added = True count = 0 else: statuses[status] = statuses.get(status, 0) + 1 # After storing the most recent events, count the rest, updating # the count in Redis after processing each page. if recents_added: for status, count in statuses.iteritems(): yield self.add_event_count(batch_id, status, count) statuses.clear() event_page = yield event_page.next_page()
# pylint: disable-msg=C0111,C0103 import unittest from openmdao.main.api import Assembly, Component, Driver, set_as_top from openmdao.main.datatypes.api import Float, Array from openmdao.main.hasconstraints import HasConstraints, HasEqConstraints, HasIneqConstraints, Constraint from openmdao.units.units import PhysicalQuantity from openmdao.util.decorators import add_delegate @add_delegate(HasConstraints) class MyDriver(Driver): pass @add_delegate(HasEqConstraints) class MyEqDriver(Driver): pass @add_delegate(HasIneqConstraints) class MyInEqDriver(Driver): pass class SimpleUnits(Component): a = Float(iotype='in', units='inch') b = Float(iotype='in', units='inch') c = Float(iotype='out', units='ft') d = Float(iotype='out', units='ft') arr = Array([1., 2., 3.], iotype='in', units='inch') arr_out = Array([1., 2., 3.], iotype='out', units='ft') def __init__(self): super(SimpleUnits, self).__init__() self.a = 1 self.b = 2 self.c = 3 self.d = -1 def execute(self): self.c = PhysicalQuantity(self.a + self.b, 'inch').in_units_of('ft').value self.d = PhysicalQuantity(self.a - self.b, 'inch').in_units_of('ft').value class Simple(Component): a = Float(iotype='in') b = Float(iotype='in') c = Float(iotype='out') d = Float(iotype='out') def __init__(self): super(Simple, self).__init__() self.a = 1 self.b = 2 self.c = 3 self.d = -1 def execute(self): self.c = self.a + self.b self.d = self.a - self.b class HasConstraintsTestCase(unittest.TestCase): def setUp(self): self.asm = set_as_top(Assembly()) self.asm.add('comp1', Simple()) self.asm.add('comp2', Simple()) self.asm.add('comp3', SimpleUnits()) self.asm.add('comp4', SimpleUnits()) def test_list_constraints(self): drv = self.asm.add('driver', MyDriver()) self.asm.run() drv.add_constraint('comp1.a < comp1.b') drv.add_constraint('comp1.c = comp1.d') self.assertEqual(drv.list_constraints(), ['comp1.c=comp1.d', 'comp1.a<comp1.b']) def test_list_eq_constraints(self): drv = self.asm.add('driver', MyEqDriver()) drv.add_constraint('comp1.a = comp1.b') drv.add_constraint('comp1.c = comp1.d') self.assertEqual(drv.list_constraints(), ['comp1.a=comp1.b', 'comp1.c=comp1.d']) def test_list_ineq_constraints(self): drv = self.asm.add('driver', MyDriver()) drv.add_constraint('comp1.a < comp1.b') drv.add_constraint('comp1.c >= comp1.d') self.assertEqual(drv.list_constraints(), ['comp1.a<comp1.b', 'comp1.c>=comp1.d']) def _check_ineq_add_constraint(self, drv): self.asm.add('driver', drv) try: drv.add_constraint('comp1.b==comp1.a') except Exception as err: self.assertEqual(str(err), "driver: Constraints require an explicit comparator (=, <, >, <=, or >=)") else: self.fail("Exception expected") self.assertEqual(len(drv.get_ineq_constraints()), 0) drv.add_constraint(' comp1.a > comp1.b') try: drv.add_constraint('comp1.a>comp1.b') except Exception as err: self.assertEqual(str(err), 'driver: A constraint of the form "comp1.a>comp1.b" already exists ' 'in the driver. Add failed.') else: self.fail("Exception Expected") self.assertEqual(len(drv.get_ineq_constraints()), 1) drv.remove_constraint(' comp1.a> comp1.b ') self.assertEqual(len(drv.get_ineq_constraints()), 0) try: drv.remove_constraint('comp1.bogus < comp1.d') except Exception as err: self.assertEqual(str(err), "driver: Constraint 'comp1.bogus<comp1.d' was not found. Remove failed.") else: self.fail("Exception expected") drv.add_constraint(' comp1.a > comp1.b') self.assertEqual(len(drv.get_ineq_constraints()), 1) drv.add_constraint('comp1.b < comp1.c', name='foobar') self.assertEqual(len(drv.get_ineq_constraints()), 2) try: drv.add_constraint('comp1.b < comp1.a', name='foobar') except Exception as err: self.assertEqual(str(err), 'driver: A constraint named "foobar" already exists in the driver. Add failed.') else: self.fail("Exception expected") self.assertEqual(len(drv.get_ineq_constraints()), 2) drv.remove_constraint('foobar') self.assertEqual(len(drv.get_ineq_constraints()), 1) drv.clear_constraints() self.assertEqual(len(drv.get_ineq_constraints()), 0) try: drv.add_constraint('comp1.b < comp1.qq') except ValueError as err: self.assertEqual(str(err), "Right hand side of constraint 'comp1.b < comp1.qq' has invalid variables 'comp1.qq'") else: self.fail('expected ValueError') def _check_eq_add_constraint(self, drv): self.asm.add('driver', drv) self.assertEqual(len(drv.get_eq_constraints()), 0) self.assertEqual(len(drv.get_eq_constraints()), 0) drv.add_constraint('comp1.c = comp1.d ') self.assertEqual(len(drv.get_eq_constraints()), 1) try: drv.add_constraint('comp1.c=comp1.d') except Exception as err: self.assertEqual(str(err), 'driver: A constraint of the form "comp1.c=comp1.d" already exists ' 'in the driver. Add failed.') else: self.fail("Exception Expected") drv.remove_constraint(' comp1.c=comp1.d') self.assertEqual(len(drv.get_eq_constraints()), 0) try: drv.remove_constraint('comp1.bogus = comp1.d') except Exception as err: self.assertEqual(str(err), "driver: Constraint 'comp1.bogus=comp1.d' was not found. Remove failed.") else: self.fail("Exception expected") self.assertEqual(len(drv.get_eq_constraints()), 0) drv.add_constraint('comp1.c =comp1.d ') self.assertEqual(len(drv.get_eq_constraints()), 1) drv.add_constraint('comp1.b = comp1.c', name='foobar') self.assertEqual(len(drv.get_eq_constraints()), 2) try: drv.add_constraint('comp1.b = comp1.a', name='foobar') except Exception as err: self.assertEqual(str(err), 'driver: A constraint named "foobar" already exists in the driver. Add failed.') else: self.fail("Exception expected") drv.remove_constraint('foobar') self.assertEqual(len(drv.get_eq_constraints()), 1) drv.clear_constraints() self.assertEqual(len(drv.get_eq_constraints()), 0) try: drv.add_constraint('comp1.qq = comp1.b') except ValueError as err: self.assertEqual(str(err), "Left hand side of constraint 'comp1.qq = comp1.b' has invalid variables 'comp1.qq'") else: self.fail('expected ValueError') def _check_eq_eval_constraints(self, drv): self.asm.add('driver', drv) vals = drv.eval_eq_constraints() self.assertEqual(len(vals), 0) drv.add_constraint('comp1.c = comp1.d ') self.asm.comp1.a = 4 self.asm.comp1.b = 5 self.asm.comp1.c = 9 self.asm.comp1.d = -1 self.asm.run() vals = drv.eval_eq_constraints() self.assertEqual(len(vals), 1) self.assertEqual(vals[0], 10.) vals = drv.get_eq_constraints() self.assertEqual(len(vals), 1) self.assertTrue(isinstance(vals['comp1.c=comp1.d'], Constraint)) def _check_ineq_eval_constraints(self, drv): self.asm.add('driver', drv) vals = drv.eval_ineq_constraints() self.assertEqual(len(vals), 0) drv.add_constraint(' comp1.a > comp1.b') self.asm.comp1.a = 4 self.asm.comp1.b = 5 self.asm.comp1.c = 9 self.asm.comp1.d = -1 self.asm.run() vals = drv.eval_ineq_constraints() self.assertEqual(len(vals), 1) self.assertEqual(vals[0], 1) vals = drv.get_ineq_constraints() self.assertEqual(len(vals), 1) self.assertTrue(isinstance(vals['comp1.a>comp1.b'], Constraint)) def test_constraint_scaler_adder(self): drv = self.asm.add('driver', MyDriver()) self.asm.comp1.a = 3000 self.asm.comp1.b = 5000 drv.add_constraint('(comp1.a-4000.)/1000.0 < comp1.b') self.asm.run() result = drv.eval_ineq_constraints() self.assertEqual(result[0], -5001.0) drv.remove_constraint('(comp1.a-4000.)/1000.0 < comp1.b') # cant add constraints that are already there result = drv.eval_ineq_constraints() self.assertEqual(result, []) # try: # drv.add_constraint('-comp1.a*5.0 < -comp1.b*5.0') # except ValueError as err: # self.assertEqual(str(err), # "Scaler parameter should be a float > 0") # else: # self.fail('expected ValueError') # try: # drv.add_constraint('comp1.a < comp1.b', scaler=2) # except ValueError as err: # self.assertEqual(str(err), # "Scaler parameter should be a float") # else: # self.fail('expected ValueError') # try: # drv.add_constraint('comp1.a < comp1.b', adder=2) # except ValueError as err: # self.assertEqual(str(err), # "Adder parameter should be a float") # else: # self.fail('expected ValueError') def test_add_constraint_eq_eq(self): drv = MyDriver() self.asm.add('driver', drv) try: drv.add_constraint('comp1.b==comp1.a') except Exception as err: self.assertEqual(str(err), "driver: Constraints require an explicit comparator (=, <, >, <=, or >=)") else: self.fail("Exception expected") def test_add_constraint(self): drv = MyDriver() self._check_eq_add_constraint(drv) self._check_ineq_add_constraint(drv) def test_add_eq_constraint(self): self._check_eq_add_constraint(MyEqDriver()) def test_add_ineq_constraint(self): self._check_ineq_add_constraint(MyInEqDriver()) def test_implicit_constraint(self): drv = self.asm.add('driver', MyEqDriver()) try: drv.add_constraint('comp1.a + comp1.b') except ValueError, err: self.assertEqual(str(err), "driver: Constraints require an explicit comparator (=, <, >, <=, or >=)") else: self.fail('ValueError expected') def test_eval_constraint(self): self._check_eq_eval_constraints(MyDriver()) self._check_ineq_eval_constraints(MyDriver()) def test_eval_eq_constraint(self): self._check_eq_eval_constraints(MyEqDriver()) def test_eval_ineq_constraint(self): self._check_ineq_eval_constraints(MyInEqDriver()) def test_pseudocomps(self): self.asm.add('driver', MyDriver()) self.asm.driver.workflow.add(['comp1', 'comp2']) self.assertEqual(self.asm._depgraph.list_connections(), []) self.asm.driver.add_constraint('comp1.c-comp2.a>5.') self.assertEqual(self.asm._pseudo_0._orig_expr, '5.-(comp1.c-comp2.a)') self.assertEqual(set(self.asm._depgraph.list_connections()), set([('comp2.a', '_pseudo_0.in1'), ('comp1.c', '_pseudo_0.in0')])) self.assertEqual(set(self.asm._exprmapper.list_connections()), set([('comp2.a', '_pseudo_0.in1'), ('comp1.c', '_pseudo_0.in0')])) self.asm.driver.remove_constraint('comp1.c-comp2.a>5.') self.assertEqual(self.asm._depgraph.list_connections(), []) self.assertEqual(self.asm._exprmapper.list_connections(), []) self.asm.driver.add_constraint('comp1.c > 0.') self.assertEqual(set(self.asm._depgraph.list_connections()), set([('comp1.c', '_pseudo_1.in0')])) self.assertEqual(set(self.asm._exprmapper.list_connections()), set([('comp1.c', '_pseudo_1.in0')])) self.assertEqual(self.asm._pseudo_1._orig_expr, '-(comp1.c)') self.asm.driver.add_constraint('comp1.c-comp2.a<5.') self.assertEqual(self.asm._pseudo_2._orig_expr, 'comp1.c-comp2.a-(5.)') self.asm.driver.add_constraint('comp1.c < 0.') self.assertEqual(self.asm._pseudo_3._orig_expr, 'comp1.c') # unit conversions don't show up in constraints or objectives self.asm.driver.add_constraint('comp3.c-comp4.a>5.') self.assertEqual(self.asm._pseudo_4._orig_expr, '5.-(comp3.c-comp4.a)') self.asm.driver.clear_constraints() self.asm.comp1.a = 2 self.asm.comp1.b = 1 self.asm.comp2.a = 4 self.asm.comp2.b = 2 # comp1.c = 3 # comp1.d = 1 # comp2.c = 6 # comp2.d = 2 self.asm.driver.add_constraint('comp2.c - 2*comp1.d > 5') self.asm.driver.add_constraint('comp2.c - 2*comp1.d < 5') self.asm.driver.add_constraint('comp2.d < 0') self.asm.run() self.assertEqual(self.asm._pseudo_5.out0, 1.0) self.assertEqual(self.asm._pseudo_6.out0, -1.0) self.assertEqual(self.asm._pseudo_7.out0, 2.0) if __name__ == "__main__": unittest.main()
# -*- coding: utf-8 -*- """Landlab component for overland flow using the linearized diffusion-wave approximation. Created on Fri May 27 14:26:13 2016 @author: gtucker """ import numpy as np from landlab import Component _FOUR_THIRDS = 4.0 / 3.0 _SEVEN_THIRDS = 7.0 / 3.0 _MICRO_DEPTH = 1.0e-6 # tiny water depth to avoid blowup in time-step estimator class LinearDiffusionOverlandFlowRouter(Component): r"""Calculate water flow over topography. Landlab component that implements a two-dimensional, linearized diffusion-wave model. The diffusion-wave approximation is a simplification of the shallow-water equations that omits the momentum terms. The flow velocity is calculated using the local water-surface slope as an approximation of the energy slope. With this linearized form, flow velocity is calculated using a linearized Manning equation, with the water-surface slope being used as the slope factor. There are two governing equations, one that represents conservation of water mass: ..math:: \frac{\partial H}{\partial t} = (P - I) - \nabla\cdot\mathbf{q} where :math:`H(x,y,t)` is local water depth, :math:`t` is time, :math:`P` is precipitation rate, :math:`I` is infiltration rate, and :math:`\mathbf{q}` is specific water discharge, which equals depth times depth-averaged velocity. The other governing equation represents specific discharge as a function of gravity, pressure, and friction: ..math:: \mathbf{q} = \frac{H^{4/3}}{n^2 U_c} \nabla w where :math:`n` is the friction factor ("Manning's n"), :math:`U_c` is a characteristic flow velocity, and :math:`w` is water-surface height, which is the sum of topographic elevation plus water depth. Infiltration rate should decline smoothly to zero as surface water depth approaches zero. To ensure this, infiltration rate is calculated as ..math:: I = I_c \left( 1 - e^{-H / H_i} ) \right) where :math:`H_i` is a characteristic water depth. The concept here is that when :math:`H \le H_i`, small spatial variations in water depth will leave parts of the ground un-ponded and therefore not subject to any infiltration. Mathematically, :math:`I \approx 0.95 I_c` when :math:`H = 3H_i`. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 3)) >>> _ = grid.add_zeros('topographic__elevation', at='node') >>> olf = LinearDiffusionOverlandFlowRouter(grid, roughness=0.1) >>> round(olf.vel_coef) 100 >>> olf.rain_rate 1e-05 >>> olf.rain_rate = 1.0e-4 >>> olf.run_one_step(dt=10.0) >>> grid.at_node['surface_water__depth'][4] 0.001 References ---------- **Required Software Citation(s) Specific to this Component** None Listed **Additional References** None Listed """ _name = "LinearDiffusionOverlandFlowRouter" _unit_agnostic = True _info = { "surface_water__depth": { "dtype": float, "intent": "out", "optional": False, "units": "m", "mapping": "node", "doc": "Depth of water on the surface", }, "surface_water__depth_at_link": { "dtype": float, "intent": "out", "optional": False, "units": "m", "mapping": "link", "doc": "Depth of water on the surface at grid links", }, "topographic__elevation": { "dtype": float, "intent": "in", "optional": False, "units": "m", "mapping": "node", "doc": "Land surface topographic elevation", }, "water__specific_discharge": { "dtype": float, "intent": "out", "optional": False, "units": "m2/s", "mapping": "link", "doc": "flow discharge component in the direction of the link", }, "water__velocity": { "dtype": float, "intent": "out", "optional": False, "units": "m/s", "mapping": "link", "doc": "flow velocity component in the direction of the link", }, "water_surface__gradient": { "dtype": float, "intent": "out", "optional": False, "units": "m/s", "mapping": "link", "doc": "Downstream gradient of the water surface.", }, } def __init__( self, grid, roughness=0.01, rain_rate=1.0e-5, infilt_rate=0.0, infilt_depth_scale=0.001, velocity_scale=1.0, cfl_factor=0.2, ): """Initialize the LinearDiffusionOverlandFlowRouter. Parameters ---------- grid : ModelGrid Landlab ModelGrid object roughness : float, defaults to 0.01 Manning roughness coefficient, s/m^1/3 rain_rate : float, optional (defaults to 36 mm/hr) Rainfall rate, m/s infilt_depth_scale : float, defaults to 0.001 Depth scale for water infiltration, m infilt_rate : float, optional (defaults to 0) Maximum rate of infiltration, m/s velocity_scale : float, defaults to 1 Characteristic flow velocity, m/s cfl_factor : float, optional (defaults to 0.2) Time-step control factor: fraction of maximum estimated time-step that is actually used (must be <=1) """ super().__init__(grid) if roughness <= 0.0: raise ValueError(f"roughness must be greater than zero {roughness}") if rain_rate < 0.0: raise ValueError(f"rain_rate must not be negative {rain_rate}") if infilt_depth_scale <= 0.0: raise ValueError( f"infilt_depth_scale must be greater than zero {infilt_depth_scale}" ) if infilt_rate < 0.0: raise ValueError(f"infilt_rate must not be negative {infilt_rate}") if velocity_scale <= 0.0: raise ValueError( f"velocity_scale must be greater than zero {velocity_scale}" ) if cfl_factor > 1.0 or cfl_factor <= 0.0: raise ValueError(f"cfl_factor must >0, <=1 {cfl_factor}") # Store parameters and do unit conversion self._rain = rain_rate self._infilt = infilt_rate self._infilt_depth_scale = infilt_depth_scale self._vel_coef = 1.0 / (roughness**2 * velocity_scale) self._elev = grid.at_node["topographic__elevation"] self.initialize_output_fields() self._depth = grid.at_node["surface_water__depth"] self._depth_at_link = grid.at_link["surface_water__depth_at_link"] self._vel = grid.at_link["water__velocity"] self._disch = grid.at_link["water__specific_discharge"] self._wsgrad = grid.at_link["water_surface__gradient"] self._water_surf_elev = np.zeros(grid.number_of_nodes) self._inactive_links = grid.status_at_link == grid.BC_LINK_IS_INACTIVE self._cfl_param = cfl_factor * 0.5 * np.amin(grid.length_of_link) ** 2 @property def rain_rate(self): """Rainfall rate""" return self._rain @rain_rate.setter def rain_rate(self, value): if value < 0.0: raise ValueError(f"rain_rate must be positive {value}") self._rain = value @property def vel_coef(self): """Velocity coefficient. (1/(roughness^2 x velocity_scale) """ return self._vel_coef def _cfl_time_step(self): """Calculate maximum time-step size using CFL criterion for explicit FTCS diffusion.""" max_water_depth = np.amax(self._depth, initial=_MICRO_DEPTH) max_diffusivity = self._vel_coef * max_water_depth**_SEVEN_THIRDS return self._cfl_param / max_diffusivity def update_for_one_iteration(self, iter_dt): """Update state variables for one iteration of duration iter_dt.""" # Calculate the water-surface elevation self._water_surf_elev[:] = self._elev + self._depth # Calculate water depth at links. This implements an "upwind" scheme # in which water depth at the links is the depth at the higher of the # two nodes. self._grid.map_value_at_max_node_to_link( self._water_surf_elev, "surface_water__depth", out=self._depth_at_link ) # Calculate the water-surface gradient and impose any closed boundaries self.grid.calc_grad_at_link(self._water_surf_elev, out=self._wsgrad) self._wsgrad[self._inactive_links] = 0.0 # Calculate velocity using the linearized Manning equation. self._vel[:] = ( -self._vel_coef * self._depth_at_link**_FOUR_THIRDS * self._wsgrad ) # Calculate discharge self._disch[:] = self._depth_at_link * self._vel # Flux divergence dqda = self._grid.calc_flux_div_at_node(self._disch) # Rates of infiltration and runoff infilt = self._infilt * (1.0 - np.exp(-self._depth / self._infilt_depth_scale)) # Rate of change of water depth dHdt = self._rain - infilt - dqda # Update water depth: simple forward Euler scheme self._depth[self._grid.core_nodes] += dHdt[self._grid.core_nodes] * iter_dt # Very crude numerical hack: prevent negative water depth (TODO: better) self._depth.clip(min=0.0, out=self._depth) def run_one_step(self, dt): """Calculate water flow for a time period `dt`. Default units for dt are *seconds*. We use a time-step subdivision algorithm that ensures step size is always below CFL limit. """ remaining_time = dt while remaining_time > 0.0: dtmax = self._cfl_time_step() # biggest possible time step size dt_this_iter = min(dtmax, remaining_time) # step we'll actually use self.update_for_one_iteration(dt_this_iter) remaining_time -= dt_this_iter
from test.support import run_unittest from test.support.import_helper import unload, CleanImport from test.support.warnings_helper import check_warnings import unittest import sys import importlib from importlib.util import spec_from_file_location import pkgutil import os import os.path import tempfile import shutil import zipfile # Note: pkgutil.walk_packages is currently tested in test_runpy. This is # a hack to get a major issue resolved for 3.3b2. Longer term, it should # be moved back here, perhaps by factoring out the helper code for # creating interesting package layouts to a separate module. # Issue #15348 declares this is indeed a dodgy hack ;) class PkgutilTests(unittest.TestCase): def setUp(self): self.dirname = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.dirname) sys.path.insert(0, self.dirname) def tearDown(self): del sys.path[0] def test_getdata_filesys(self): pkg = 'test_getdata_filesys' # Include a LF and a CRLF, to test that binary data is read back RESOURCE_DATA = b'Hello, world!\nSecond line\r\nThird line' # Make a package with some resources package_dir = os.path.join(self.dirname, pkg) os.mkdir(package_dir) # Empty init.py f = open(os.path.join(package_dir, '__init__.py'), "wb") f.close() # Resource files, res.txt, sub/res.txt f = open(os.path.join(package_dir, 'res.txt'), "wb") f.write(RESOURCE_DATA) f.close() os.mkdir(os.path.join(package_dir, 'sub')) f = open(os.path.join(package_dir, 'sub', 'res.txt'), "wb") f.write(RESOURCE_DATA) f.close() # Check we can read the resources res1 = pkgutil.get_data(pkg, 'res.txt') self.assertEqual(res1, RESOURCE_DATA) res2 = pkgutil.get_data(pkg, 'sub/res.txt') self.assertEqual(res2, RESOURCE_DATA) del sys.modules[pkg] def test_getdata_zipfile(self): zip = 'test_getdata_zipfile.zip' pkg = 'test_getdata_zipfile' # Include a LF and a CRLF, to test that binary data is read back RESOURCE_DATA = b'Hello, world!\nSecond line\r\nThird line' # Make a package with some resources zip_file = os.path.join(self.dirname, zip) z = zipfile.ZipFile(zip_file, 'w') # Empty init.py z.writestr(pkg + '/__init__.py', "") # Resource files, res.txt, sub/res.txt z.writestr(pkg + '/res.txt', RESOURCE_DATA) z.writestr(pkg + '/sub/res.txt', RESOURCE_DATA) z.close() # Check we can read the resources sys.path.insert(0, zip_file) res1 = pkgutil.get_data(pkg, 'res.txt') self.assertEqual(res1, RESOURCE_DATA) res2 = pkgutil.get_data(pkg, 'sub/res.txt') self.assertEqual(res2, RESOURCE_DATA) names = [] for moduleinfo in pkgutil.iter_modules([zip_file]): self.assertIsInstance(moduleinfo, pkgutil.ModuleInfo) names.append(moduleinfo.name) self.assertEqual(names, ['test_getdata_zipfile']) del sys.path[0] del sys.modules[pkg] def test_unreadable_dir_on_syspath(self): # issue7367 - walk_packages failed if unreadable dir on sys.path package_name = "unreadable_package" d = os.path.join(self.dirname, package_name) # this does not appear to create an unreadable dir on Windows # but the test should not fail anyway os.mkdir(d, 0) self.addCleanup(os.rmdir, d) for t in pkgutil.walk_packages(path=[self.dirname]): self.fail("unexpected package found") def test_walkpackages_filesys(self): pkg1 = 'test_walkpackages_filesys' pkg1_dir = os.path.join(self.dirname, pkg1) os.mkdir(pkg1_dir) f = open(os.path.join(pkg1_dir, '__init__.py'), "wb") f.close() os.mkdir(os.path.join(pkg1_dir, 'sub')) f = open(os.path.join(pkg1_dir, 'sub', '__init__.py'), "wb") f.close() f = open(os.path.join(pkg1_dir, 'sub', 'mod.py'), "wb") f.close() # Now, to juice it up, let's add the opposite packages, too. pkg2 = 'sub' pkg2_dir = os.path.join(self.dirname, pkg2) os.mkdir(pkg2_dir) f = open(os.path.join(pkg2_dir, '__init__.py'), "wb") f.close() os.mkdir(os.path.join(pkg2_dir, 'test_walkpackages_filesys')) f = open(os.path.join(pkg2_dir, 'test_walkpackages_filesys', '__init__.py'), "wb") f.close() f = open(os.path.join(pkg2_dir, 'test_walkpackages_filesys', 'mod.py'), "wb") f.close() expected = [ 'sub', 'sub.test_walkpackages_filesys', 'sub.test_walkpackages_filesys.mod', 'test_walkpackages_filesys', 'test_walkpackages_filesys.sub', 'test_walkpackages_filesys.sub.mod', ] actual= [e[1] for e in pkgutil.walk_packages([self.dirname])] self.assertEqual(actual, expected) for pkg in expected: if pkg.endswith('mod'): continue del sys.modules[pkg] def test_walkpackages_zipfile(self): """Tests the same as test_walkpackages_filesys, only with a zip file.""" zip = 'test_walkpackages_zipfile.zip' pkg1 = 'test_walkpackages_zipfile' pkg2 = 'sub' zip_file = os.path.join(self.dirname, zip) z = zipfile.ZipFile(zip_file, 'w') z.writestr(pkg2 + '/__init__.py', "") z.writestr(pkg2 + '/' + pkg1 + '/__init__.py', "") z.writestr(pkg2 + '/' + pkg1 + '/mod.py', "") z.writestr(pkg1 + '/__init__.py', "") z.writestr(pkg1 + '/' + pkg2 + '/__init__.py', "") z.writestr(pkg1 + '/' + pkg2 + '/mod.py', "") z.close() sys.path.insert(0, zip_file) expected = [ 'sub', 'sub.test_walkpackages_zipfile', 'sub.test_walkpackages_zipfile.mod', 'test_walkpackages_zipfile', 'test_walkpackages_zipfile.sub', 'test_walkpackages_zipfile.sub.mod', ] actual= [e[1] for e in pkgutil.walk_packages([zip_file])] self.assertEqual(actual, expected) del sys.path[0] for pkg in expected: if pkg.endswith('mod'): continue del sys.modules[pkg] def test_walk_packages_raises_on_string_or_bytes_input(self): str_input = 'test_dir' with self.assertRaises((TypeError, ValueError)): list(pkgutil.walk_packages(str_input)) bytes_input = b'test_dir' with self.assertRaises((TypeError, ValueError)): list(pkgutil.walk_packages(bytes_input)) def test_name_resolution(self): import logging import logging.handlers success_cases = ( ('os', os), ('os.path', os.path), ('os.path:pathsep', os.path.pathsep), ('logging', logging), ('logging:', logging), ('logging.handlers', logging.handlers), ('logging.handlers:', logging.handlers), ('logging.handlers:SysLogHandler', logging.handlers.SysLogHandler), ('logging.handlers.SysLogHandler', logging.handlers.SysLogHandler), ('logging.handlers:SysLogHandler.LOG_ALERT', logging.handlers.SysLogHandler.LOG_ALERT), ('logging.handlers.SysLogHandler.LOG_ALERT', logging.handlers.SysLogHandler.LOG_ALERT), ('builtins.int', int), ('builtins:int', int), ('builtins.int.from_bytes', int.from_bytes), ('builtins:int.from_bytes', int.from_bytes), ('builtins.ZeroDivisionError', ZeroDivisionError), ('builtins:ZeroDivisionError', ZeroDivisionError), ('os:path', os.path), ) failure_cases = ( (None, TypeError), (1, TypeError), (2.0, TypeError), (True, TypeError), ('', ValueError), ('?abc', ValueError), ('abc/foo', ValueError), ('foo', ImportError), ('os.foo', AttributeError), ('os.foo:', ImportError), ('os.pth:pathsep', ImportError), ('logging.handlers:NoSuchHandler', AttributeError), ('logging.handlers:SysLogHandler.NO_SUCH_VALUE', AttributeError), ('logging.handlers.SysLogHandler.NO_SUCH_VALUE', AttributeError), ('ZeroDivisionError', ImportError), ('os.path.9abc', ValueError), ('9abc', ValueError), ) # add some Unicode package names to the mix. unicode_words = ('\u0935\u092e\u0938', '\xe9', '\xc8', '\uc548\ub155\ud558\uc138\uc694', '\u3055\u3088\u306a\u3089', '\u3042\u308a\u304c\u3068\u3046', '\u0425\u043e\u0440\u043e\u0448\u043e', '\u0441\u043f\u0430\u0441\u0438\u0431\u043e', '\u73b0\u4ee3\u6c49\u8bed\u5e38\u7528\u5b57\u8868') for uw in unicode_words: d = os.path.join(self.dirname, uw) try: os.makedirs(d, exist_ok=True) except UnicodeEncodeError: # When filesystem encoding cannot encode uw: skip this test continue # make an empty __init__.py file f = os.path.join(d, '__init__.py') with open(f, 'w') as f: f.write('') f.flush() # now import the package we just created; clearing the caches is # needed, otherwise the newly created package isn't found importlib.invalidate_caches() mod = importlib.import_module(uw) success_cases += (uw, mod), if len(uw) > 1: failure_cases += (uw[:-1], ImportError), # add an example with a Unicode digit at the start failure_cases += ('\u0966\u0935\u092e\u0938', ValueError), for s, expected in success_cases: with self.subTest(s=s): o = pkgutil.resolve_name(s) self.assertEqual(o, expected) for s, exc in failure_cases: with self.subTest(s=s): with self.assertRaises(exc): pkgutil.resolve_name(s) class PkgutilPEP302Tests(unittest.TestCase): class MyTestLoader(object): def create_module(self, spec): return None def exec_module(self, mod): # Count how many times the module is reloaded mod.__dict__['loads'] = mod.__dict__.get('loads', 0) + 1 def get_data(self, path): return "Hello, world!" class MyTestImporter(object): def find_spec(self, fullname, path=None, target=None): loader = PkgutilPEP302Tests.MyTestLoader() return spec_from_file_location(fullname, '<%s>' % loader.__class__.__name__, loader=loader, submodule_search_locations=[]) def setUp(self): sys.meta_path.insert(0, self.MyTestImporter()) def tearDown(self): del sys.meta_path[0] def test_getdata_pep302(self): # Use a dummy finder/loader self.assertEqual(pkgutil.get_data('foo', 'dummy'), "Hello, world!") del sys.modules['foo'] def test_alreadyloaded(self): # Ensure that get_data works without reloading - the "loads" module # variable in the example loader should count how many times a reload # occurs. import foo self.assertEqual(foo.loads, 1) self.assertEqual(pkgutil.get_data('foo', 'dummy'), "Hello, world!") self.assertEqual(foo.loads, 1) del sys.modules['foo'] # These tests, especially the setup and cleanup, are hideous. They # need to be cleaned up once issue 14715 is addressed. class ExtendPathTests(unittest.TestCase): def create_init(self, pkgname): dirname = tempfile.mkdtemp() sys.path.insert(0, dirname) pkgdir = os.path.join(dirname, pkgname) os.mkdir(pkgdir) with open(os.path.join(pkgdir, '__init__.py'), 'w') as fl: fl.write('from pkgutil import extend_path\n__path__ = extend_path(__path__, __name__)\n') return dirname def create_submodule(self, dirname, pkgname, submodule_name, value): module_name = os.path.join(dirname, pkgname, submodule_name + '.py') with open(module_name, 'w') as fl: print('value={}'.format(value), file=fl) def test_simple(self): pkgname = 'foo' dirname_0 = self.create_init(pkgname) dirname_1 = self.create_init(pkgname) self.create_submodule(dirname_0, pkgname, 'bar', 0) self.create_submodule(dirname_1, pkgname, 'baz', 1) import foo.bar import foo.baz # Ensure we read the expected values self.assertEqual(foo.bar.value, 0) self.assertEqual(foo.baz.value, 1) # Ensure the path is set up correctly self.assertEqual(sorted(foo.__path__), sorted([os.path.join(dirname_0, pkgname), os.path.join(dirname_1, pkgname)])) # Cleanup shutil.rmtree(dirname_0) shutil.rmtree(dirname_1) del sys.path[0] del sys.path[0] del sys.modules['foo'] del sys.modules['foo.bar'] del sys.modules['foo.baz'] # Another awful testing hack to be cleaned up once the test_runpy # helpers are factored out to a common location def test_iter_importers(self): iter_importers = pkgutil.iter_importers get_importer = pkgutil.get_importer pkgname = 'spam' modname = 'eggs' dirname = self.create_init(pkgname) pathitem = os.path.join(dirname, pkgname) fullname = '{}.{}'.format(pkgname, modname) sys.modules.pop(fullname, None) sys.modules.pop(pkgname, None) try: self.create_submodule(dirname, pkgname, modname, 0) importlib.import_module(fullname) importers = list(iter_importers(fullname)) expected_importer = get_importer(pathitem) for finder in importers: spec = pkgutil._get_spec(finder, fullname) loader = spec.loader try: loader = loader.loader except AttributeError: # For now we still allow raw loaders from # find_module(). pass self.assertIsInstance(finder, importlib.machinery.FileFinder) self.assertEqual(finder, expected_importer) self.assertIsInstance(loader, importlib.machinery.SourceFileLoader) self.assertIsNone(pkgutil._get_spec(finder, pkgname)) with self.assertRaises(ImportError): list(iter_importers('invalid.module')) with self.assertRaises(ImportError): list(iter_importers('.spam')) finally: shutil.rmtree(dirname) del sys.path[0] try: del sys.modules['spam'] del sys.modules['spam.eggs'] except KeyError: pass def test_mixed_namespace(self): pkgname = 'foo' dirname_0 = self.create_init(pkgname) dirname_1 = self.create_init(pkgname) self.create_submodule(dirname_0, pkgname, 'bar', 0) # Turn this into a PEP 420 namespace package os.unlink(os.path.join(dirname_0, pkgname, '__init__.py')) self.create_submodule(dirname_1, pkgname, 'baz', 1) import foo.bar import foo.baz # Ensure we read the expected values self.assertEqual(foo.bar.value, 0) self.assertEqual(foo.baz.value, 1) # Ensure the path is set up correctly self.assertEqual(sorted(foo.__path__), sorted([os.path.join(dirname_0, pkgname), os.path.join(dirname_1, pkgname)])) # Cleanup shutil.rmtree(dirname_0) shutil.rmtree(dirname_1) del sys.path[0] del sys.path[0] del sys.modules['foo'] del sys.modules['foo.bar'] del sys.modules['foo.baz'] # XXX: test .pkg files class NestedNamespacePackageTest(unittest.TestCase): def setUp(self): self.basedir = tempfile.mkdtemp() self.old_path = sys.path[:] def tearDown(self): sys.path[:] = self.old_path shutil.rmtree(self.basedir) def create_module(self, name, contents): base, final = name.rsplit('.', 1) base_path = os.path.join(self.basedir, base.replace('.', os.path.sep)) os.makedirs(base_path, exist_ok=True) with open(os.path.join(base_path, final + ".py"), 'w') as f: f.write(contents) def test_nested(self): pkgutil_boilerplate = ( 'import pkgutil; ' '__path__ = pkgutil.extend_path(__path__, __name__)') self.create_module('a.pkg.__init__', pkgutil_boilerplate) self.create_module('b.pkg.__init__', pkgutil_boilerplate) self.create_module('a.pkg.subpkg.__init__', pkgutil_boilerplate) self.create_module('b.pkg.subpkg.__init__', pkgutil_boilerplate) self.create_module('a.pkg.subpkg.c', 'c = 1') self.create_module('b.pkg.subpkg.d', 'd = 2') sys.path.insert(0, os.path.join(self.basedir, 'a')) sys.path.insert(0, os.path.join(self.basedir, 'b')) import pkg self.addCleanup(unload, 'pkg') self.assertEqual(len(pkg.__path__), 2) import pkg.subpkg self.addCleanup(unload, 'pkg.subpkg') self.assertEqual(len(pkg.subpkg.__path__), 2) from pkg.subpkg.c import c from pkg.subpkg.d import d self.assertEqual(c, 1) self.assertEqual(d, 2) class ImportlibMigrationTests(unittest.TestCase): # With full PEP 302 support in the standard import machinery, the # PEP 302 emulation in this module is in the process of being # deprecated in favour of importlib proper def check_deprecated(self): return check_warnings( ("This emulation is deprecated and slated for removal in " "Python 3.12; use 'importlib' instead", DeprecationWarning)) def test_importer_deprecated(self): with self.check_deprecated(): pkgutil.ImpImporter("") def test_loader_deprecated(self): with self.check_deprecated(): pkgutil.ImpLoader("", "", "", "") def test_get_loader_avoids_emulation(self): with check_warnings() as w: self.assertIsNotNone(pkgutil.get_loader("sys")) self.assertIsNotNone(pkgutil.get_loader("os")) self.assertIsNotNone(pkgutil.get_loader("test.support")) self.assertEqual(len(w.warnings), 0) @unittest.skipIf(__name__ == '__main__', 'not compatible with __main__') def test_get_loader_handles_missing_loader_attribute(self): global __loader__ this_loader = __loader__ del __loader__ try: with check_warnings() as w: self.assertIsNotNone(pkgutil.get_loader(__name__)) self.assertEqual(len(w.warnings), 0) finally: __loader__ = this_loader def test_get_loader_handles_missing_spec_attribute(self): name = 'spam' mod = type(sys)(name) del mod.__spec__ with CleanImport(name): sys.modules[name] = mod loader = pkgutil.get_loader(name) self.assertIsNone(loader) def test_get_loader_handles_spec_attribute_none(self): name = 'spam' mod = type(sys)(name) mod.__spec__ = None with CleanImport(name): sys.modules[name] = mod loader = pkgutil.get_loader(name) self.assertIsNone(loader) def test_get_loader_None_in_sys_modules(self): name = 'totally bogus' sys.modules[name] = None try: loader = pkgutil.get_loader(name) finally: del sys.modules[name] self.assertIsNone(loader) def test_find_loader_missing_module(self): name = 'totally bogus' loader = pkgutil.find_loader(name) self.assertIsNone(loader) def test_find_loader_avoids_emulation(self): with check_warnings() as w: self.assertIsNotNone(pkgutil.find_loader("sys")) self.assertIsNotNone(pkgutil.find_loader("os")) self.assertIsNotNone(pkgutil.find_loader("test.support")) self.assertEqual(len(w.warnings), 0) def test_get_importer_avoids_emulation(self): # We use an illegal path so *none* of the path hooks should fire with check_warnings() as w: self.assertIsNone(pkgutil.get_importer("*??")) self.assertEqual(len(w.warnings), 0) def test_iter_importers_avoids_emulation(self): with check_warnings() as w: for importer in pkgutil.iter_importers(): pass self.assertEqual(len(w.warnings), 0) def test_main(): run_unittest(PkgutilTests, PkgutilPEP302Tests, ExtendPathTests, NestedNamespacePackageTest, ImportlibMigrationTests) # this is necessary if test is run repeated (like when finding leaks) import zipimport import importlib zipimport._zip_directory_cache.clear() importlib.invalidate_caches() if __name__ == '__main__': test_main()
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from __future__ import absolute_import import os.path import pytest from . import util from .errors import UnsupportedCommandError from .info import TestInfo, TestPath, ParentInfo def add_cli_subparser(cmd, name, parent): """Add a new subparser to the given parent and add args to it.""" parser = parent.add_parser(name) if cmd == 'discover': # For now we don't have any tool-specific CLI options to add. pass else: raise UnsupportedCommandError(cmd) return parser def discover(pytestargs=None, hidestdio=False, _pytest_main=pytest.main, _plugin=None, **_ignored): """Return the results of test discovery.""" if _plugin is None: _plugin = TestCollector() pytestargs = _adjust_pytest_args(pytestargs) # We use this helper rather than "-pno:terminal" due to possible # platform-dependent issues. with util.hide_stdio() if hidestdio else util.noop_cm(): ec = _pytest_main(pytestargs, [_plugin]) if ec != 0: raise Exception('pytest discovery failed (exit code {})'.format(ec)) if not _plugin._started: raise Exception('pytest discovery did not start') return ( _plugin._tests.parents, #[p._replace( # id=p.id.lstrip('.' + os.path.sep), # parentid=p.parentid.lstrip('.' + os.path.sep), # ) # for p in _plugin._tests.parents], list(_plugin._tests), ) def _adjust_pytest_args(pytestargs): pytestargs = list(pytestargs) if pytestargs else [] # Duplicate entries should be okay. pytestargs.insert(0, '--collect-only') # TODO: pull in code from: # src/client/unittests/pytest/services/discoveryService.ts # src/client/unittests/pytest/services/argsService.ts return pytestargs class TestCollector(object): """This is a pytest plugin that collects the discovered tests.""" NORMCASE = staticmethod(os.path.normcase) PATHSEP = os.path.sep def __init__(self, tests=None): if tests is None: tests = DiscoveredTests() self._tests = tests self._started = False # Relevant plugin hooks: # https://docs.pytest.org/en/latest/reference.html#collection-hooks def pytest_collection_modifyitems(self, session, config, items): self._started = True self._tests.reset() for item in items: test, suiteids = _parse_item(item, self.NORMCASE, self.PATHSEP) self._tests.add_test(test, suiteids) # This hook is not specified in the docs, so we also provide # the "modifyitems" hook just in case. def pytest_collection_finish(self, session): self._started = True try: items = session.items except AttributeError: # TODO: Is there an alternative? return self._tests.reset() for item in items: test, suiteids = _parse_item(item, self.NORMCASE, self.PATHSEP) self._tests.add_test(test, suiteids) class DiscoveredTests(object): def __init__(self): self.reset() def __len__(self): return len(self._tests) def __getitem__(self, index): return self._tests[index] @property def parents(self): return sorted(self._parents.values(), key=lambda v: (v.root or v.name, v.id)) def reset(self): self._parents = {} self._tests = [] def add_test(self, test, suiteids): parentid = self._ensure_parent(test.path, test.parentid, suiteids) test = test._replace(parentid=parentid) if not test.id.startswith('.' + os.path.sep): test = test._replace(id=os.path.join('.', test.id)) self._tests.append(test) def _ensure_parent(self, path, parentid, suiteids): if not parentid.startswith('.' + os.path.sep): parentid = os.path.join('.', parentid) fileid = self._ensure_file(path.root, path.relfile) rootdir = path.root if not path.func: return parentid fullsuite, _, funcname = path.func.rpartition('.') suiteid = self._ensure_suites(fullsuite, rootdir, fileid, suiteids) parent = suiteid if suiteid else fileid if path.sub: if (rootdir, parentid) not in self._parents: funcinfo = ParentInfo(parentid, 'function', funcname, rootdir, parent) self._parents[(rootdir, parentid)] = funcinfo elif parent != parentid: # TODO: What to do? raise NotImplementedError return parentid def _ensure_file(self, rootdir, relfile): if (rootdir, '.') not in self._parents: self._parents[(rootdir, '.')] = ParentInfo('.', 'folder', rootdir) if relfile.startswith('.' + os.path.sep): fileid = relfile else: fileid = relfile = os.path.join('.', relfile) if (rootdir, fileid) not in self._parents: folderid, filebase = os.path.split(fileid) fileinfo = ParentInfo(fileid, 'file', filebase, rootdir, folderid) self._parents[(rootdir, fileid)] = fileinfo while folderid != '.' and (rootdir, folderid) not in self._parents: parentid, name = os.path.split(folderid) folderinfo = ParentInfo(folderid, 'folder', name, rootdir, parentid) self._parents[(rootdir, folderid)] = folderinfo folderid = parentid return relfile def _ensure_suites(self, fullsuite, rootdir, fileid, suiteids): if not fullsuite: if suiteids: # TODO: What to do? raise NotImplementedError return None if len(suiteids) != fullsuite.count('.') + 1: # TODO: What to do? raise NotImplementedError suiteid = suiteids.pop() if not suiteid.startswith('.' + os.path.sep): suiteid = os.path.join('.', suiteid) final = suiteid while '.' in fullsuite and (rootdir, suiteid) not in self._parents: parentid = suiteids.pop() if not parentid.startswith('.' + os.path.sep): parentid = os.path.join('.', parentid) fullsuite, _, name = fullsuite.rpartition('.') suiteinfo = ParentInfo(suiteid, 'suite', name, rootdir, parentid) self._parents[(rootdir, suiteid)] = suiteinfo suiteid = parentid else: name = fullsuite suiteinfo = ParentInfo(suiteid, 'suite', name, rootdir, fileid) if (rootdir, suiteid) not in self._parents: self._parents[(rootdir, suiteid)] = suiteinfo return final def _parse_item(item, _normcase, _pathsep): """ (pytest.Collector) pytest.Session pytest.Package pytest.Module pytest.Class (pytest.File) (pytest.Item) pytest.Function """ #_debug_item(item, showsummary=True) kind, _ = _get_item_kind(item) # Figure out the func, suites, and subs. (fileid, suiteids, suites, funcid, basename, parameterized ) = _parse_node_id(item.nodeid, kind) if kind == 'function': funcname = basename if funcid and item.function.__name__ != funcname: # TODO: What to do? raise NotImplementedError if suites: testfunc = '.'.join(suites) + '.' + funcname else: testfunc = funcname elif kind == 'doctest': testfunc = None funcname = None # Figure out the file. fspath = str(item.fspath) if not fspath.endswith(_pathsep + fileid): raise NotImplementedError filename = fspath[-len(fileid):] testroot = str(item.fspath)[:-len(fileid)].rstrip(_pathsep) if _pathsep in filename: relfile = filename else: relfile = '.' + _pathsep + filename srcfile, lineno, fullname = item.location if srcfile != fileid: # pytest supports discovery of tests imported from other # modules. This is reflected by a different filename # in item.location. if _normcase(fileid) == _normcase(srcfile): srcfile = fileid else: srcfile = relfile location = '{}:{}'.format(srcfile, lineno) if kind == 'function': if testfunc and fullname != testfunc + parameterized: print(fullname, testfunc) # TODO: What to do? raise NotImplementedError elif kind == 'doctest': if testfunc and fullname != testfunc + parameterized: print(fullname, testfunc) # TODO: What to do? raise NotImplementedError # Sort out the parent. if parameterized: parentid = funcid elif suites: parentid = suiteids[-1] else: parentid = fileid # Sort out markers. # See: https://docs.pytest.org/en/latest/reference.html#marks markers = set() for marker in item.own_markers: if marker.name == 'parameterize': # We've already covered these. continue elif marker.name == 'skip': markers.add('skip') elif marker.name == 'skipif': markers.add('skip-if') elif marker.name == 'xfail': markers.add('expected-failure') # TODO: Support other markers? test = TestInfo( id=item.nodeid, name=item.name, path=TestPath( root=testroot, relfile=relfile, func=testfunc, sub=[parameterized] if parameterized else None, ), source=location, markers=sorted(markers) if markers else None, parentid=parentid, ) return test, suiteids def _parse_node_id(nodeid, kind='function'): if kind == 'doctest': try: parentid, name = nodeid.split('::') except ValueError: # TODO: Unexpected! What to do? raise NotImplementedError funcid = None parameterized = '' else: parameterized = '' if nodeid.endswith(']'): funcid, sep, parameterized = nodeid.partition('[') if not sep: # TODO: Unexpected! What to do? raise NotImplementedError parameterized = sep + parameterized else: funcid = nodeid parentid, _, name = funcid.rpartition('::') if not name: # TODO: What to do? We expect at least a filename and a function raise NotImplementedError suites = [] suiteids = [] while '::' in parentid: suiteids.insert(0, parentid) parentid, _, suitename = parentid.rpartition('::') suites.insert(0, suitename) fileid = parentid return fileid, suiteids, suites, funcid, name, parameterized def _get_item_kind(item): """Return (kind, isunittest) for the given item.""" try: itemtype = item.kind except AttributeError: itemtype = item.__class__.__name__ if itemtype == 'DoctestItem': return 'doctest', False elif itemtype == 'Function': return 'function', False elif itemtype == 'TestCaseFunction': return 'function', True elif item.hasattr('function'): return 'function', False else: return None, False ############################# # useful for debugging def _debug_item(item, showsummary=False): item._debugging = True try: # TODO: Make a PytestTest class to wrap the item? summary = { 'id': item.nodeid, 'kind': _get_item_kind(item), 'class': item.__class__.__name__, 'name': item.name, 'fspath': item.fspath, 'location': item.location, 'func': getattr(item, 'function', None), 'markers': item.own_markers, #'markers': list(item.iter_markers()), 'props': item.user_properties, 'attrnames': dir(item), } finally: item._debugging = False if showsummary: print(item.nodeid) for key in ('kind', 'class', 'name', 'fspath', 'location', 'func', 'markers', 'props'): print(' {:12} {}'.format(key, summary[key])) print() return summary def _group_attr_names(attrnames): grouped = { 'dunder': [n for n in attrnames if n.startswith('__') and n.endswith('__')], 'private': [n for n in attrnames if n.startswith('_')], 'constants': [n for n in attrnames if n.isupper()], 'classes': [n for n in attrnames if n == n.capitalize() and not n.isupper()], 'vars': [n for n in attrnames if n.islower()], } grouped['other'] = [n for n in attrnames if n not in grouped['dunder'] and n not in grouped['private'] and n not in grouped['constants'] and n not in grouped['classes'] and n not in grouped['vars'] ] return grouped
# SPDX-License-Identifier: Apache-2.0 # # Copyright (C) 2015, ARM Limited and contributors. # # 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. # """ Trace Parser Module """ import numpy as np import os import pandas as pd import sys import trappy import json import warnings import operator import logging from analysis_register import AnalysisRegister from collections import namedtuple from devlib.utils.misc import memoized from trappy.utils import listify, handle_duplicate_index NON_IDLE_STATE = -1 ResidencyTime = namedtuple('ResidencyTime', ['total', 'active']) ResidencyData = namedtuple('ResidencyData', ['label', 'residency']) class Trace(object): """ The Trace object is the LISA trace events parser. :param platform: a dictionary containing information about the target platform :type platform: dict :param data_dir: folder containing all trace data :type data_dir: str :param events: events to be parsed (everything in the trace by default) :type events: list(str) :param window: time window to consider when parsing the trace :type window: tuple(int, int) :param normalize_time: normalize trace time stamps :type normalize_time: bool :param trace_format: format of the trace. Possible values are: - FTrace - SysTrace :type trace_format: str :param plots_dir: directory where to save plots :type plots_dir: str :param plots_prefix: prefix for plots file names :type plots_prefix: str """ def __init__(self, platform, data_dir, events, window=(0, None), normalize_time=True, trace_format='FTrace', plots_dir=None, plots_prefix=''): # The platform used to run the experiments self.platform = platform # TRAPpy Trace object self.ftrace = None # Trace format self.trace_format = trace_format # The time window used to limit trace parsing to self.window = window # Dynamically registered TRAPpy events self.trappy_cls = {} # Maximum timespan for all collected events self.time_range = 0 # Time the system was overutilzied self.overutilized_time = 0 self.overutilized_prc = 0 # List of events required by user self.events = [] # List of events available in the parsed trace self.available_events = [] # Cluster frequency coherency flag self.freq_coherency = True # Folder containing all trace data self.data_dir = None # Setup logging self._log = logging.getLogger('Trace') # Folder containing trace if not os.path.isdir(data_dir): self.data_dir = os.path.dirname(data_dir) else: self.data_dir = data_dir # By deafult, use the trace dir to save plots self.plots_dir = plots_dir if self.plots_dir is None: self.plots_dir = self.data_dir self.plots_prefix = plots_prefix self.__registerTraceEvents(events) self.__parseTrace(data_dir, window, normalize_time, trace_format) self.__computeTimeSpan() # Minimum and Maximum x_time to use for all plots self.x_min = 0 self.x_max = self.time_range # Reset x axis time range to full scale t_min = self.window[0] t_max = self.window[1] self.setXTimeRange(t_min, t_max) self.data_frame = TraceData() self._registerDataFrameGetters(self) self.analysis = AnalysisRegister(self) def _registerDataFrameGetters(self, module): """ Internal utility function that looks up getter functions with a "_dfg_" prefix in their name and bounds them to the specified module. :param module: module to which the function is added :type module: class """ self._log.debug('Registering [%s] local data frames', module) for func in dir(module): if not func.startswith('_dfg_'): continue dfg_name = func.replace('_dfg_', '') dfg_func = getattr(module, func) self._log.debug(' %s', dfg_name) setattr(self.data_frame, dfg_name, dfg_func) def setXTimeRange(self, t_min=None, t_max=None): """ Set x axis time range to the specified values. :param t_min: lower bound :type t_min: int or float :param t_max: upper bound :type t_max: int or float """ if t_min is None: self.x_min = 0 else: self.x_min = t_min if t_max is None: self.x_max = self.time_range else: self.x_max = t_max self._log.debug('Set plots time range to (%.6f, %.6f)[s]', self.x_min, self.x_max) def __registerTraceEvents(self, events): """ Save a copy of the parsed events. :param events: single event name or list of events names :type events: str or list(str) """ if isinstance(events, basestring): self.events = events.split(' ') elif isinstance(events, list): self.events = events else: raise ValueError('Events must be a string or a list of strings') # Register devlib fake cpu_frequency events if 'cpu_frequency' in events: self.events.append('cpu_frequency_devlib') def __parseTrace(self, path, window, normalize_time, trace_format): """ Internal method in charge of performing the actual parsing of the trace. :param path: path to the trace folder (or trace file) :type path: str :param window: time window to consider when parsing the trace :type window: tuple(int, int) :param normalize_time: normalize trace time stamps :type normalize_time: bool :param trace_format: format of the trace. Possible values are: - FTrace - SysTrace :type trace_format: str """ self._log.debug('Loading [sched] events from trace in [%s]...', path) self._log.debug('Parsing events: %s', self.events) if trace_format.upper() == 'SYSTRACE' or path.endswith('html'): self._log.debug('Parsing SysTrace format...') trace_class = trappy.SysTrace self.trace_format = 'SysTrace' elif trace_format.upper() == 'FTRACE': self._log.debug('Parsing FTrace format...') trace_class = trappy.FTrace self.trace_format = 'FTrace' else: raise ValueError("Unknown trace format {}".format(trace_format)) self.ftrace = trace_class(path, scope="custom", events=self.events, window=window, normalize_time=normalize_time) # Load Functions profiling data has_function_stats = self._loadFunctionsStats(path) # Check for events available on the parsed trace self.__checkAvailableEvents() if len(self.available_events) == 0: if has_function_stats: self._log.info('Trace contains only functions stats') return raise ValueError('The trace does not contain useful events ' 'nor function stats') # Index PIDs and Task names self.__loadTasksNames() # Setup internal data reference to interesting events/dataframes self._sanitize_SchedLoadAvgCpu() self._sanitize_SchedLoadAvgTask() self._sanitize_SchedCpuCapacity() self._sanitize_SchedBoostCpu() self._sanitize_SchedBoostTask() self._sanitize_SchedEnergyDiff() self._sanitize_SchedOverutilized() self._sanitize_CpuFrequency() # Compute plot window if not normalize_time: start = self.window[0] if self.window[1]: duration = min(self.ftrace.get_duration(), self.window[1]) else: duration = self.ftrace.get_duration() self.window = (self.ftrace.basetime + start, self.ftrace.basetime + duration) def __checkAvailableEvents(self, key=""): """ Internal method used to build a list of available events. :param key: key to be used for TRAPpy filtering :type key: str """ for val in self.ftrace.get_filters(key): obj = getattr(self.ftrace, val) if len(obj.data_frame): self.available_events.append(val) self._log.debug('Events found on trace:') for evt in self.available_events: self._log.debug(' - %s', evt) def __loadTasksNames(self): """ Try to load tasks names using one of the supported events. """ def load(event, name_key, pid_key): df = self._dfg_trace_event(event) self._scanTasks(df, name_key=name_key, pid_key=pid_key) if 'sched_switch' in self.available_events: load('sched_switch', 'prev_comm', 'prev_pid') return if 'sched_load_avg_task' in self.available_events: load('sched_load_avg_task', 'comm', 'pid') return self._log.warning('Failed to load tasks names from trace events') def hasEvents(self, dataset): """ Returns True if the specified event is present in the parsed trace, False otherwise. :param dataset: trace event name or list of trace events :type dataset: str or list(str) """ if dataset in self.available_events: return True return False def __computeTimeSpan(self): """ Compute time axis range, considering all the parsed events. """ ts = sys.maxint te = 0 for events in self.available_events: df = self._dfg_trace_event(events) if len(df) == 0: continue if (df.index[0]) < ts: ts = df.index[0] if (df.index[-1]) > te: te = df.index[-1] self.time_range = te - ts self._log.debug('Collected events spans a %.3f [s] time interval', self.time_range) # Build a stat on trace overutilization if self.hasEvents('sched_overutilized'): df = self._dfg_trace_event('sched_overutilized') self.overutilized_time = df[df.overutilized == 1].len.sum() self.overutilized_prc = 100. * self.overutilized_time / self.time_range self._log.debug('Overutilized time: %.6f [s] (%.3f%% of trace time)', self.overutilized_time, self.overutilized_prc) def _scanTasks(self, df, name_key='comm', pid_key='pid'): """ Extract tasks names and PIDs from the input data frame. The data frame should contain a task name column and PID column. :param df: data frame containing trace events from which tasks names and PIDs will be extracted :type df: :mod:`pandas.DataFrame` :param name_key: The name of the dataframe columns containing task names :type name_key: str :param pid_key: The name of the dataframe columns containing task PIDs :type pid_key: str """ df = df[[name_key, pid_key]] self._tasks_by_pid = (df.drop_duplicates(subset=pid_key, keep='last') .rename(columns={ pid_key : 'PID', name_key : 'TaskName'}) .set_index('PID').sort_index()) def getTaskByName(self, name): """ Get the PIDs of all tasks with the specified name. The same PID can have different task names, mainly because once a task is generated it inherits the parent name and then its name is updated to represent what the task really is. This API works under the assumption that a task name is updated at most one time and it always considers the name a task had the last time it has been scheduled for execution in the current trace. :param name: task name :type name: str :return: a list of PID for tasks which name matches the required one, the last time they ran in the current trace """ return (self._tasks_by_pid[self._tasks_by_pid.TaskName == name] .index.tolist()) def getTaskByPid(self, pid): """ Get the name of the task with the specified PID. The same PID can have different task names, mainly because once a task is generated it inherits the parent name and then its name is updated to represent what the task really is. This API works under the assumption that a task name is updated at most one time and it always report the name the task had the last time it has been scheduled for execution in the current trace. :param name: task PID :type name: int :return: the name of the task which PID matches the required one, the last time they ran in the current trace """ try: return self._tasks_by_pid.ix[pid].values[0] except KeyError: return None def getTasks(self): """ Get a dictionary of all the tasks in the Trace. :return: a dictionary which maps each PID to the corresponding task name """ return self._tasks_by_pid.TaskName.to_dict() ############################################################################### # DataFrame Getter Methods ############################################################################### def df(self, event): """ Get a dataframe containing all occurrences of the specified trace event in the parsed trace. :param event: Trace event name :type event: str """ warnings.simplefilter('always', DeprecationWarning) #turn off filter warnings.warn("\n\tUse of Trace::df() is deprecated and will be soon removed." "\n\tUse Trace::data_frame.trace_event(event_name) instead.", category=DeprecationWarning) warnings.simplefilter('default', DeprecationWarning) #reset filter return self._dfg_trace_event(event) def _dfg_trace_event(self, event): """ Get a dataframe containing all occurrences of the specified trace event in the parsed trace. :param event: Trace event name :type event: str """ if self.data_dir is None: raise ValueError("trace data not (yet) loaded") if self.ftrace and hasattr(self.ftrace, event): return getattr(self.ftrace, event).data_frame raise ValueError('Event [{}] not supported. ' 'Supported events are: {}' .format(event, self.available_events)) def _dfg_functions_stats(self, functions=None): """ Get a DataFrame of specified kernel functions profile data For each profiled function a DataFrame is returned which reports stats on kernel functions execution time. The reported stats are per-CPU and includes: number of times the function has been executed (hits), average execution time (avg), overall execution time (time) and samples variance (s_2). By default returns a DataFrame of all the functions profiled. :param functions: the name of the function or a list of function names to report :type functions: str or list(str) """ if not hasattr(self, '_functions_stats_df'): return None df = self._functions_stats_df if not functions: return df return df.loc[df.index.get_level_values(1).isin(listify(functions))] ############################################################################### # Trace Events Sanitize Methods ############################################################################### def _sanitize_SchedCpuCapacity(self): """ Add more columns to cpu_capacity data frame if the energy model is available. """ if not self.hasEvents('cpu_capacity') \ or 'nrg_model' not in self.platform: return df = self._dfg_trace_event('cpu_capacity') # Add column with LITTLE and big CPUs max capacities nrg_model = self.platform['nrg_model'] max_lcap = nrg_model['little']['cpu']['cap_max'] max_bcap = nrg_model['big']['cpu']['cap_max'] df['max_capacity'] = np.select( [df.cpu.isin(self.platform['clusters']['little'])], [max_lcap], max_bcap) # Add LITTLE and big CPUs "tipping point" threshold tip_lcap = 0.8 * max_lcap tip_bcap = 0.8 * max_bcap df['tip_capacity'] = np.select( [df.cpu.isin(self.platform['clusters']['little'])], [tip_lcap], tip_bcap) def _sanitize_SchedLoadAvgCpu(self): """ If necessary, rename certain signal names from v5.0 to v5.1 format. """ if not self.hasEvents('sched_load_avg_cpu'): return df = self._dfg_trace_event('sched_load_avg_cpu') if 'utilization' in df: df.rename(columns={'utilization': 'util_avg'}, inplace=True) df.rename(columns={'load': 'load_avg'}, inplace=True) def _sanitize_SchedLoadAvgTask(self): """ If necessary, rename certain signal names from v5.0 to v5.1 format. """ if not self.hasEvents('sched_load_avg_task'): return df = self._dfg_trace_event('sched_load_avg_task') if 'utilization' in df: df.rename(columns={'utilization': 'util_avg'}, inplace=True) df.rename(columns={'load': 'load_avg'}, inplace=True) df.rename(columns={'avg_period': 'period_contrib'}, inplace=True) df.rename(columns={'runnable_avg_sum': 'load_sum'}, inplace=True) df.rename(columns={'running_avg_sum': 'util_sum'}, inplace=True) df['cluster'] = np.select( [df.cpu.isin(self.platform['clusters']['little'])], ['LITTLE'], 'big') # Add a column which represents the max capacity of the smallest # clustre which can accomodate the task utilization little_cap = self.platform['nrg_model']['little']['cpu']['cap_max'] big_cap = self.platform['nrg_model']['big']['cpu']['cap_max'] df['min_cluster_cap'] = df.util_avg.map( lambda util_avg: big_cap if util_avg > little_cap else little_cap ) def _sanitize_SchedBoostCpu(self): """ Add a boosted utilization signal as the sum of utilization and margin. Also, if necessary, rename certain signal names from v5.0 to v5.1 format. """ if not self.hasEvents('sched_boost_cpu'): return df = self._dfg_trace_event('sched_boost_cpu') if 'usage' in df: df.rename(columns={'usage': 'util'}, inplace=True) df['boosted_util'] = df['util'] + df['margin'] def _sanitize_SchedBoostTask(self): """ Add a boosted utilization signal as the sum of utilization and margin. Also, if necessary, rename certain signal names from v5.0 to v5.1 format. """ if not self.hasEvents('sched_boost_task'): return df = self._dfg_trace_event('sched_boost_task') if 'utilization' in df: # Convert signals name from to v5.1 format df.rename(columns={'utilization': 'util'}, inplace=True) df['boosted_util'] = df['util'] + df['margin'] def _sanitize_SchedEnergyDiff(self): """ If a energy model is provided, some signals are added to the sched_energy_diff trace event data frame. Also convert between existing field name formats for sched_energy_diff """ if not self.hasEvents('sched_energy_diff') \ or 'nrg_model' not in self.platform: return nrg_model = self.platform['nrg_model'] em_lcluster = nrg_model['little']['cluster'] em_bcluster = nrg_model['big']['cluster'] em_lcpu = nrg_model['little']['cpu'] em_bcpu = nrg_model['big']['cpu'] lcpus = len(self.platform['clusters']['little']) bcpus = len(self.platform['clusters']['big']) SCHED_LOAD_SCALE = 1024 power_max = em_lcpu['nrg_max'] * lcpus + em_bcpu['nrg_max'] * bcpus + \ em_lcluster['nrg_max'] + em_bcluster['nrg_max'] self._log.debug( "Maximum estimated system energy: {0:d}".format(power_max)) df = self._dfg_trace_event('sched_energy_diff') translations = {'nrg_d' : 'nrg_diff', 'utl_d' : 'usage_delta', 'payoff' : 'nrg_payoff' } df.rename(columns=translations, inplace=True) df['nrg_diff_pct'] = SCHED_LOAD_SCALE * df.nrg_diff / power_max # Tag columns by usage_delta ccol = df.usage_delta df['usage_delta_group'] = np.select( [ccol < 150, ccol < 400, ccol < 600], ['< 150', '< 400', '< 600'], '>= 600') # Tag columns by nrg_payoff ccol = df.nrg_payoff df['nrg_payoff_group'] = np.select( [ccol > 2e9, ccol > 0, ccol > -2e9], ['Optimal Accept', 'SchedTune Accept', 'SchedTune Reject'], 'Suboptimal Reject') def _sanitize_SchedOverutilized(self): """ Add a column with overutilized status duration. """ if not self.hasEvents('sched_overutilized'): return df = self._dfg_trace_event('sched_overutilized') df['start'] = df.index df['len'] = (df.start - df.start.shift()).fillna(0).shift(-1) df.drop('start', axis=1, inplace=True) def _chunker(self, seq, size): """ Given a data frame or a series, generate a sequence of chunks of the given size. :param seq: data to be split into chunks :type seq: :mod:`pandas.Series` or :mod:`pandas.DataFrame` :param size: size of each chunk :type size: int """ return (seq.iloc[pos:pos + size] for pos in range(0, len(seq), size)) def _sanitize_CpuFrequency(self): """ Verify that all platform reported clusters are frequency coherent (i.e. frequency scaling is performed at a cluster level). """ if not self.hasEvents('cpu_frequency_devlib'): return devlib_freq = self._dfg_trace_event('cpu_frequency_devlib') devlib_freq.rename(columns={'cpu_id':'cpu'}, inplace=True) devlib_freq.rename(columns={'state':'frequency'}, inplace=True) df = self._dfg_trace_event('cpu_frequency') clusters = self.platform['clusters'] # devlib always introduces fake cpu_frequency events, in case the # OS has not generated cpu_frequency envets there are the only # frequency events to report if len(df) == 0: # Register devlib injected events as 'cpu_frequency' events setattr(self.ftrace.cpu_frequency, 'data_frame', devlib_freq) df = devlib_freq self.available_events.append('cpu_frequency') # make sure fake cpu_frequency events are never interleaved with # OS generated events else: if len(devlib_freq) > 0: # Frequencies injection is done in a per-cluster based. # This is based on the assumption that clusters are # frequency choerent. # For each cluster we inject devlib events only if # these events does not overlaps with os-generated ones. # Inject "initial" devlib frequencies os_df = df dl_df = devlib_freq.iloc[:self.platform['cpus_count']] for _,c in self.platform['clusters'].iteritems(): dl_freqs = dl_df[dl_df.cpu.isin(c)] os_freqs = os_df[os_df.cpu.isin(c)] self._log.debug("First freqs for %s:\n%s", c, dl_freqs) # All devlib events "before" os-generated events self._log.debug("Min os freq @: %s", os_freqs.index.min()) if os_freqs.empty or \ os_freqs.index.min() > dl_freqs.index.max(): self._log.debug("Insert devlib freqs for %s", c) df = pd.concat([dl_freqs, df]) # Inject "final" devlib frequencies os_df = df dl_df = devlib_freq.iloc[self.platform['cpus_count']:] for _,c in self.platform['clusters'].iteritems(): dl_freqs = dl_df[dl_df.cpu.isin(c)] os_freqs = os_df[os_df.cpu.isin(c)] self._log.debug("Last freqs for %s:\n%s", c, dl_freqs) # All devlib events "after" os-generated events self._log.debug("Max os freq @: %s", os_freqs.index.max()) if os_freqs.empty or \ os_freqs.index.max() < dl_freqs.index.min(): self._log.debug("Append devlib freqs for %s", c) df = pd.concat([df, dl_freqs]) df.sort_index(inplace=True) setattr(self.ftrace.cpu_frequency, 'data_frame', df) # Frequency Coherency Check for _, cpus in clusters.iteritems(): cluster_df = df[df.cpu.isin(cpus)] for chunk in self._chunker(cluster_df, len(cpus)): f = chunk.iloc[0].frequency if any(chunk.frequency != f): self._log.warning('Cluster Frequency is not coherent! ' 'Failure in [cpu_frequency] events at:') self._log.warning(chunk) self.freq_coherency = False return self._log.info('Platform clusters verified to be Frequency coherent') ############################################################################### # Utility Methods ############################################################################### def integrate_square_wave(self, sq_wave): """ Compute the integral of a square wave time series. :param sq_wave: square wave assuming only 1.0 and 0.0 values :type sq_wave: :mod:`pandas.Series` """ sq_wave.iloc[-1] = 0.0 # Compact signal to obtain only 1-0-1-0 sequences comp_sig = sq_wave.loc[sq_wave.shift() != sq_wave] # First value for computing the difference must be a 1 if comp_sig.iloc[0] == 0.0: return sum(comp_sig.iloc[2::2].index - comp_sig.iloc[1:-1:2].index) else: return sum(comp_sig.iloc[1::2].index - comp_sig.iloc[:-1:2].index) def _loadFunctionsStats(self, path='trace.stats'): """ Read functions profiling file and build a data frame containing all relevant data. :param path: path to the functions profiling trace file :type path: str """ if os.path.isdir(path): path = os.path.join(path, 'trace.stats') if (path.endswith('dat') or path.endswith('txt') or path.endswith('html')): pre, ext = os.path.splitext(path) path = pre + '.stats' if not os.path.isfile(path): return False # Opening functions profiling JSON data file self._log.debug('Loading functions profiling data from [%s]...', path) with open(os.path.join(path), 'r') as fh: trace_stats = json.load(fh) # Build DataFrame of function stats frames = {} for cpu, data in trace_stats.iteritems(): frames[int(cpu)] = pd.DataFrame.from_dict(data, orient='index') # Build and keep track of the DataFrame self._functions_stats_df = pd.concat(frames.values(), keys=frames.keys()) return len(self._functions_stats_df) > 0 @memoized def getCPUActiveSignal(self, cpu): """ Build a square wave representing the active (i.e. non-idle) CPU time, i.e.: cpu_active[t] == 1 if the CPU is reported to be non-idle by cpuidle at time t cpu_active[t] == 0 otherwise :param cpu: CPU ID :type cpu: int :returns: A :mod:`pandas.Series` or ``None`` if the trace contains no "cpu_idle" events """ if not self.hasEvents('cpu_idle'): self._log.warning('Events [cpu_idle] not found, ' 'cannot compute CPU active signal!') return None idle_df = self._dfg_trace_event('cpu_idle') cpu_df = idle_df[idle_df.cpu_id == cpu] cpu_active = cpu_df.state.apply( lambda s: 1 if s == NON_IDLE_STATE else 0 ) start_time = 0.0 if not self.ftrace.normalized_time: start_time = self.ftrace.basetime if cpu_active.empty: cpu_active = pd.Series([0], index=[start_time]) elif cpu_active.index[0] != start_time: entry_0 = pd.Series(cpu_active.iloc[0] ^ 1, index=[start_time]) cpu_active = pd.concat([entry_0, cpu_active]) # Fix sequences of wakeup/sleep events reported with the same index return handle_duplicate_index(cpu_active) @memoized def getClusterActiveSignal(self, cluster): """ Build a square wave representing the active (i.e. non-idle) cluster time, i.e.: cluster_active[t] == 1 if at least one CPU is reported to be non-idle by CPUFreq at time t cluster_active[t] == 0 otherwise :param cluster: list of CPU IDs belonging to a cluster :type cluster: list(int) :returns: A :mod:`pandas.Series` or ``None`` if the trace contains no "cpu_idle" events """ if not self.hasEvents('cpu_idle'): self._log.warning('Events [cpu_idle] not found, ' 'cannot compute cluster active signal!') return None active = self.getCPUActiveSignal(cluster[0]).to_frame(name=cluster[0]) for cpu in cluster[1:]: active = active.join( self.getCPUActiveSignal(cpu).to_frame(name=cpu), how='outer' ) active.fillna(method='ffill', inplace=True) # Cluster active is the OR between the actives on each CPU # belonging to that specific cluster cluster_active = reduce( operator.or_, [cpu_active.astype(int) for _, cpu_active in active.iteritems()] ) return cluster_active class TraceData: """ A DataFrame collector exposed to Trace's clients """ pass # vim :set tabstop=4 shiftwidth=4 expandtab
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for common notifcations.""" import copy from oslo.config import cfg from nova.compute import instance_types from nova.compute import task_states from nova.compute import vm_states from nova import context from nova import db from nova.network import api as network_api from nova import notifications from nova.openstack.common.notifier import api as notifier_api from nova.openstack.common.notifier import test_notifier from nova import test from nova.tests import fake_network CONF = cfg.CONF CONF.import_opt('compute_driver', 'nova.virt.driver') class NotificationsTestCase(test.TestCase): def setUp(self): super(NotificationsTestCase, self).setUp() self.net_info = fake_network.fake_get_instance_nw_info(self.stubs, 1, 1, spectacular=True) def fake_get_nw_info(cls, ctxt, instance): self.assertTrue(ctxt.is_admin) return self.net_info self.stubs.Set(network_api.API, 'get_instance_nw_info', fake_get_nw_info) fake_network.set_stub_network_methods(self.stubs) notifier_api._reset_drivers() self.addCleanup(notifier_api._reset_drivers) self.flags(compute_driver='nova.virt.fake.FakeDriver', notification_driver=[test_notifier.__name__], network_manager='nova.network.manager.FlatManager', notify_on_state_change="vm_and_task_state", host='testhost') self.user_id = 'fake' self.project_id = 'fake' self.context = context.RequestContext(self.user_id, self.project_id) test_notifier.NOTIFICATIONS = [] self.instance = self._wrapped_create() def _wrapped_create(self, params=None): instance_type = instance_types.get_instance_type_by_name('m1.tiny') sys_meta = instance_types.save_instance_type_info({}, instance_type) inst = {} inst['image_ref'] = 1 inst['user_id'] = self.user_id inst['project_id'] = self.project_id inst['instance_type_id'] = instance_type['id'] inst['root_gb'] = 0 inst['ephemeral_gb'] = 0 inst['access_ip_v4'] = '1.2.3.4' inst['access_ip_v6'] = 'feed:5eed' inst['display_name'] = 'test_instance' inst['hostname'] = 'test_instance_hostname' inst['system_metadata'] = sys_meta if params: inst.update(params) return db.instance_create(self.context, inst) def test_send_api_fault_disabled(self): self.flags(notify_api_faults=False) notifications.send_api_fault("http://example.com/foo", 500, None) self.assertEquals(0, len(test_notifier.NOTIFICATIONS)) def test_send_api_fault(self): self.flags(notify_api_faults=True) exception = None try: # Get a real exception with a call stack. raise test.TestingException("junk") except test.TestingException, e: exception = e notifications.send_api_fault("http://example.com/foo", 500, exception) self.assertEquals(1, len(test_notifier.NOTIFICATIONS)) n = test_notifier.NOTIFICATIONS[0] self.assertEquals(n['priority'], 'ERROR') self.assertEquals(n['event_type'], 'api.fault') self.assertEquals(n['payload']['url'], 'http://example.com/foo') self.assertEquals(n['payload']['status'], 500) self.assertTrue(n['payload']['exception'] is not None) def test_notif_disabled(self): # test config disable of the notifcations self.flags(notify_on_state_change=None) self.flags(notify_on_any_change=False) old = copy.copy(self.instance) self.instance["vm_state"] = vm_states.ACTIVE old_vm_state = old['vm_state'] new_vm_state = self.instance["vm_state"] old_task_state = old['task_state'] new_task_state = self.instance["task_state"] notifications.send_update_with_states(self.context, self.instance, old_vm_state, new_vm_state, old_task_state, new_task_state, verify_states=True) notifications.send_update(self.context, old, self.instance) self.assertEquals(0, len(test_notifier.NOTIFICATIONS)) def test_task_notif(self): # test config disable of just the task state notifications self.flags(notify_on_state_change="vm_state") # we should not get a notification on task stgate chagne now old = copy.copy(self.instance) self.instance["task_state"] = task_states.SPAWNING old_vm_state = old['vm_state'] new_vm_state = self.instance["vm_state"] old_task_state = old['task_state'] new_task_state = self.instance["task_state"] notifications.send_update_with_states(self.context, self.instance, old_vm_state, new_vm_state, old_task_state, new_task_state, verify_states=True) self.assertEquals(0, len(test_notifier.NOTIFICATIONS)) # ok now enable task state notifcations and re-try self.flags(notify_on_state_change="vm_and_task_state") notifications.send_update(self.context, old, self.instance) self.assertEquals(1, len(test_notifier.NOTIFICATIONS)) def test_send_no_notif(self): # test notification on send no initial vm state: old_vm_state = self.instance['vm_state'] new_vm_state = self.instance['vm_state'] old_task_state = self.instance['task_state'] new_task_state = self.instance['task_state'] notifications.send_update_with_states(self.context, self.instance, old_vm_state, new_vm_state, old_task_state, new_task_state, service="compute", host=None, verify_states=True) self.assertEquals(0, len(test_notifier.NOTIFICATIONS)) def test_send_on_vm_change(self): # pretend we just transitioned to ACTIVE: params = {"vm_state": vm_states.ACTIVE} (old_ref, new_ref) = db.instance_update_and_get_original(self.context, self.instance['uuid'], params) notifications.send_update(self.context, old_ref, new_ref) self.assertEquals(1, len(test_notifier.NOTIFICATIONS)) def test_send_on_task_change(self): # pretend we just transitioned to task SPAWNING: params = {"task_state": task_states.SPAWNING} (old_ref, new_ref) = db.instance_update_and_get_original(self.context, self.instance['uuid'], params) notifications.send_update(self.context, old_ref, new_ref) self.assertEquals(1, len(test_notifier.NOTIFICATIONS)) def test_no_update_with_states(self): notifications.send_update_with_states(self.context, self.instance, vm_states.BUILDING, vm_states.BUILDING, task_states.SPAWNING, task_states.SPAWNING, verify_states=True) self.assertEquals(0, len(test_notifier.NOTIFICATIONS)) def test_vm_update_with_states(self): notifications.send_update_with_states(self.context, self.instance, vm_states.BUILDING, vm_states.ACTIVE, task_states.SPAWNING, task_states.SPAWNING, verify_states=True) self.assertEquals(1, len(test_notifier.NOTIFICATIONS)) notif = test_notifier.NOTIFICATIONS[0] payload = notif["payload"] access_ip_v4 = self.instance["access_ip_v4"] access_ip_v6 = self.instance["access_ip_v6"] display_name = self.instance["display_name"] hostname = self.instance["hostname"] self.assertEquals(vm_states.BUILDING, payload["old_state"]) self.assertEquals(vm_states.ACTIVE, payload["state"]) self.assertEquals(task_states.SPAWNING, payload["old_task_state"]) self.assertEquals(task_states.SPAWNING, payload["new_task_state"]) self.assertEquals(payload["access_ip_v4"], access_ip_v4) self.assertEquals(payload["access_ip_v6"], access_ip_v6) self.assertEquals(payload["display_name"], display_name) self.assertEquals(payload["hostname"], hostname) def test_task_update_with_states(self): self.flags(notify_on_state_change="vm_and_task_state") notifications.send_update_with_states(self.context, self.instance, vm_states.BUILDING, vm_states.BUILDING, task_states.SPAWNING, None, verify_states=True) self.assertEquals(1, len(test_notifier.NOTIFICATIONS)) notif = test_notifier.NOTIFICATIONS[0] payload = notif["payload"] access_ip_v4 = self.instance["access_ip_v4"] access_ip_v6 = self.instance["access_ip_v6"] display_name = self.instance["display_name"] hostname = self.instance["hostname"] self.assertEquals(vm_states.BUILDING, payload["old_state"]) self.assertEquals(vm_states.BUILDING, payload["state"]) self.assertEquals(task_states.SPAWNING, payload["old_task_state"]) self.assertEquals(None, payload["new_task_state"]) self.assertEquals(payload["access_ip_v4"], access_ip_v4) self.assertEquals(payload["access_ip_v6"], access_ip_v6) self.assertEquals(payload["display_name"], display_name) self.assertEquals(payload["hostname"], hostname) def test_update_no_service_name(self): notifications.send_update_with_states(self.context, self.instance, vm_states.BUILDING, vm_states.BUILDING, task_states.SPAWNING, None) self.assertEquals(1, len(test_notifier.NOTIFICATIONS)) # service name should default to 'compute' notif = test_notifier.NOTIFICATIONS[0] self.assertEquals('compute.testhost', notif['publisher_id']) def test_update_with_service_name(self): notifications.send_update_with_states(self.context, self.instance, vm_states.BUILDING, vm_states.BUILDING, task_states.SPAWNING, None, service="testservice") self.assertEquals(1, len(test_notifier.NOTIFICATIONS)) # service name should default to 'compute' notif = test_notifier.NOTIFICATIONS[0] self.assertEquals('testservice.testhost', notif['publisher_id']) def test_update_with_host_name(self): notifications.send_update_with_states(self.context, self.instance, vm_states.BUILDING, vm_states.BUILDING, task_states.SPAWNING, None, host="someotherhost") self.assertEquals(1, len(test_notifier.NOTIFICATIONS)) # service name should default to 'compute' notif = test_notifier.NOTIFICATIONS[0] self.assertEquals('compute.someotherhost', notif['publisher_id']) def test_payload_has_fixed_ip_labels(self): info = notifications.info_from_instance(self.context, self.instance, self.net_info, None) self.assertTrue("fixed_ips" in info) self.assertEquals(info["fixed_ips"][0]["label"], "test1") def test_send_access_ip_update(self): notifications.send_update(self.context, self.instance, self.instance) self.assertEquals(1, len(test_notifier.NOTIFICATIONS)) notif = test_notifier.NOTIFICATIONS[0] payload = notif["payload"] access_ip_v4 = self.instance["access_ip_v4"] access_ip_v6 = self.instance["access_ip_v6"] self.assertEquals(payload["access_ip_v4"], access_ip_v4) self.assertEquals(payload["access_ip_v6"], access_ip_v6) def test_send_name_update(self): notifications.send_update(self.context, self.instance, self.instance) self.assertEquals(1, len(test_notifier.NOTIFICATIONS)) notif = test_notifier.NOTIFICATIONS[0] payload = notif["payload"] display_name = self.instance["display_name"] self.assertEquals(payload["display_name"], display_name) def test_send_no_state_change(self): called = [False] def sending_no_state_change(context, instance, **kwargs): called[0] = True self.stubs.Set(notifications, '_send_instance_update_notification', sending_no_state_change) notifications.send_update(self.context, self.instance, self.instance) self.assertTrue(called[0]) def test_fail_sending_update(self): def fail_sending(context, instance, **kwargs): raise Exception('failed to notify') self.stubs.Set(notifications, '_send_instance_update_notification', fail_sending) notifications.send_update(self.context, self.instance, self.instance) self.assertEquals(0, len(test_notifier.NOTIFICATIONS))
# copyright 2004-2005 Samuele Pedroni import sys import os import re scriptdir = os.path.dirname(__file__) import directives import java_parser import java_templating from java_templating import JavaTemplate,jast_make,jast, make_id, make_literal # Some examples for modif_re # (one)two -> group 1 = "one" # group 2 = "two" # (one,two,three)four -> group 1 = "one,two,three" # group 2 = "four" # hello -> group 1 = None # group 2 = "hello" modif_re = re.compile(r"(?:\(([\w,]+)\))?(\w+)") # Explanation of named groups in regular expression ktg_re: # k = one character key ("o","i" and "s" in "ois") # opt = optional (the "?" in "o?") # dfl = default for optional (the "blah" in o?(blah) ) # tg = descriptive argument name (the "I'm anything but a curly brace in o{I'm anything but a curly brace} ) ktg_re = re.compile("(?P<k>\w)(?P<opt>\?(:?\((?P<dfl>[^)]*)\))?)?(?:\{(?P<tg>[^}]*)\})?") def make_name(n): return JavaTemplate(jast_make(jast.QualifiedIdentifier,[java_parser.make_id(n)])) class Gen: priority_order = ['require','define', 'type_as', 'type_name','type_class','type_base_class', 'incl', 'expose_getset', 'expose_unary','expose_binary', 'expose_vanilla_cmp','expose_vanilla_pow', 'expose_key_getitem', 'expose_index_getitem', 'expose_cmeth', 'expose_meth', 'expose_wide_meth', 'expose_new_mutable', 'expose_new_immutable', 'rest'] def __init__(self,bindings=None,priority_order=None): if bindings is None: self.global_bindings = { 'csub': java_templating.csub, 'concat': java_templating.concat, 'strfy': java_templating.strfy } else: self.global_bindings = bindings if priority_order: self.priority_order = priority_order self.call_meths_cache = {} self.auxiliary = None self.no_setup = False self.statements = [] def debug(self,bindings): for name,val in bindings.items(): if isinstance(val,JavaTemplate): print "%s:" % name print val.texpand({}) def invalid(self,dire,value): raise Exception,"invalid '%s': %s" % (dire,value) def get_aux(self,name): if self.auxiliary is None: aux_gen = Gen(priority_order=['require','define']) directives.execute(directives.load(os.path.join(scriptdir,'gexpose-defs')),aux_gen) self.auxiliary = aux_gen.global_bindings return self.auxiliary[name] def dire_require(self,name,parm,body): if body is not None: self.invalid('require','non-empty body') sub_gen = Gen(bindings=self.global_bindings, priority__order=['require','define']) directives.execute(directives.load(parm.strip()),sub_gen) def dire_define(self,name,parm,body): parms = parm.split() if not parms: self.invalid('define',parm) parsed_name = modif_re.match(parms[0]) if not parsed_name: self.invalid('define',parm) templ_kind = parsed_name.group(1) templ_name = parsed_name.group(2) naked = False if templ_kind is None: templ_kind = 'Fragment' templ = JavaTemplate(body, parms=':'.join(parms[1:]), bindings = self.global_bindings, start = templ_kind) self.global_bindings[templ_name] = templ def dire_type_as(self,name,parm,body): if body is not None: self.invalid(name,'non-empty body') parms = parm.split() if len(parms) not in (1,2): self.invalid(name,parm) self.type_as = JavaTemplate(parms[0]) if len(parms) == 2: if parms[1] == 'no-setup': self.no_setup = True else: self.invalid(name,parm) def dire_type_name(self,name,parm,body): if body is not None: self.invalid(name,'non-empty body') self.type_name_plain = parm.strip() self.type_name = make_name(self.type_name_plain) self.global_bindings['typname'] = self.type_name def dire_type_class(self,name,parm,body): if body is not None: self.invalid(name,'non-empty body') self.type_class = JavaTemplate(parm.strip()) self.global_bindings['typ'] = self.type_class def dire_type_base_class(self,name,parm,body): if body is not None: self.invalid(name,'non-empty body') self.type_base_class = JavaTemplate(parm.strip()) def dire_incl(self,name,parm,body): if body is not None: self.invalid(name,'non-empty body') directives.execute(directives.load(parm.strip()+'.expose'),self) def dire_expose_getset(self,name,parm,body): if body is not None: self.invalid(name,'non-empty body') parms = parm.strip().split() if len(parms) not in (2,3,4): self.invalid(name, parm) name = parms[0] get = '"%s"' % parms[1] if len(parms) >= 3: set = '"%s"' % parms[2] else: set = "null" if len(parms) == 4: del_meth = '"%s"' % parms[3] else: del_meth = "null" getset_bindings = self.global_bindings.copy() getset_bindings['name'] = JavaTemplate(make_id(name)) getset_bindings['get'] = JavaTemplate(make_literal(get)) getset_bindings['set'] = JavaTemplate(make_literal(set)) getset_bindings['del'] = JavaTemplate(make_literal(del_meth)) getset = self.get_aux('getset') self.statements.append(getset.tbind(getset_bindings)) NOARGS = JavaTemplate("void()") EMPTYALL = JavaTemplate(jast_make(jast.Expressions)) def parse_sig(self,name,sig): argspecs = [] some_opt = 0 for m in ktg_re.finditer(sig): k = m.group('k') opt = m.group('opt') and 1 or 0 if opt: some_opt = 1 if opt != some_opt: self.invalid(name,"cannot interleave opt and non-opt arguments") dfl = m.group('dfl') if opt and dfl is None: dfl = '' tg = m.group('tg') argspecs.append((k,opt,dfl,tg)) everything = [(k,tg) for k,opt,dfl,tg in argspecs] dfls = [ dfl for k,opt,dfl,tg in argspecs if opt] return everything,dfls def arg_i(self, argj, j, tg): if tg: err = "%s must be an integer" % tg else: err = "expected an integer" return JavaTemplate("%s.asInt(%s)" % (argj, j)), err # !!! def arg_l(self, argj, j, tg): if tg: err = "%s must be a long" % tg else: err = "expected a long" return JavaTemplate("%s.asLong(%s)" % (argj, j)), err # !!! def arg_b(self, argj, j, tg): return JavaTemplate("%s.__nonzero__()" % (argj)),None def arg_o(self,argj,j,tg): return JavaTemplate(argj),None def arg_S(self,argj,j,tg): if tg: err = "%s must be a string or None" % tg else: err = "expected a string or None" return JavaTemplate("%s.asStringOrNull(%s)" % (argj,j)),err # !!! def arg_s(self,argj,j,tg): if tg: err = "%s must be a string" % tg else: err = "expected a string" return JavaTemplate("%s.asString(%s)" % (argj,j)),err # !!! def arg_n(self,argj,j,tg): if tg: err = "%s must be a string" % tg else: err = "expected a string" return JavaTemplate("%s.asName(%s)" % (argj,j)),err # !!! def make_call_meths(self,n,bindings): try: return self.call_meths_cache[n].tbind(bindings) except KeyError: templ = "`call_meths`(`args%d,`body%d);" defs = [] for i in range(n): defs.append(templ % (i,i)) defs = '\n'.join(defs) jtempl = JavaTemplate(defs,start='ClassBodyDeclarations') self.call_meths_cache[n] = jtempl return jtempl.tbind(bindings) def handle_expose_meth_sig(self,sig,call_meths_bindings,body,body_bindings): proto_body_jt = JavaTemplate(body) everything,dfls = self.parse_sig('expose_meth',sig) dfls = map(JavaTemplate,dfls) tot = len(everything) rng = len(dfls)+1 for dflc in range(rng): new_body_bindings = body_bindings.copy() args = self.NOARGS all = self.EMPTYALL j = 0 conv_errors = {} for k,tg in everything[:tot-dflc]: argj = "arg%d" % j args += JavaTemplate("void(PyObject %s)" % argj) new_body_bindings[argj],err = getattr(self,'arg_%s' % k)(argj,j,tg) all += JavaTemplate(jast_make(jast.Expressions,[new_body_bindings[argj].fragment])) if err: conv_errors.setdefault(err,[]).append(j) j += 1 new_body_bindings['all'] = all for dv in dfls[rng-1-dflc:]: new_body_bindings["arg%d" % j] = dv j += 1 for deleg_templ_name in ('void','deleg','vdeleg','rdeleg','ideleg','ldeleg','bdeleg','sdeleg', 'udeleg'): deleg_templ = self.get_aux(deleg_templ_name) new_body_bindings[deleg_templ_name] = deleg_templ.tbind(new_body_bindings) body_jt = proto_body_jt.tbind(new_body_bindings) if conv_errors: cases = JavaTemplate(jast_make(jast.SwitchBlockStatementGroups)) for err,indexes in conv_errors.items(): suite = JavaTemplate('msg = "%s"; break; ' % err).fragment.BlockStatements cases += java_templating.switchgroup(indexes,suite) bindings = {'cases': cases, 'unsafe_body': body_jt } body_jt = self.get_aux('conv_error_handling').tbind(bindings) call_meths_bindings['body%d' % dflc] = body_jt call_meths_bindings['args%d' % dflc] = args inst_call_meths = self.make_call_meths(rng,call_meths_bindings) return inst_call_meths,tot-rng+1,tot def expose_meth_body(self, name, parm, body): parm = parm.strip() if parm.find('>') != -1: prefix, parm = parm.split('>', 1) parm = parm.strip() else: prefix = self.type_name_plain+'_' if body is not None: return parm, prefix, body if parm.startswith(':'): retk,rest = parm.split(None,1) body = { ":i" : "`ideleg;", ":l" : "`ldeleg;", ":b" : "`bdeleg;", ":s" : "`sdeleg;", ":u" : "`udeleg;", ":-" : "`vdeleg; `void; ", ":o" : "`rdeleg;" }.get(retk, None) if not body: self.invalid(name,retk) return rest, prefix, body else: return parm, prefix, "`rdeleg;" def dire_expose_meth(self,name,parm,body): # !!! parm, prefix, body = self.expose_meth_body(name, parm, body) expose = self.get_aux('expose_narrow_meth') type_class = getattr(self,'type_class',None) type_name = getattr(self,'type_name',None) if type_class is None or type_name is None: raise Exception,"type_class or type_name not defined" parms = parm.strip().split(None,1) if len(parms) not in (1,2): self.invalid(name,parm) if len(parms) == 1: parms.append('') expose_bindings = {} expose_bindings['typ'] = type_class expose_bindings['name'] = JavaTemplate(parms[0]) expose_bindings['deleg_prefix'] = make_name(prefix) # !!! call_meths_bindings = expose_bindings.copy() body_bindings = self.global_bindings.copy() body_bindings.update(expose_bindings) call_meths_bindings['call_meths'] = self.get_aux('call_meths').tbind({'typ': type_class}) inst_call_meths,minargs,maxargs = self.handle_expose_meth_sig(parms[1],call_meths_bindings,body,body_bindings) expose_bindings['call_meths'] = inst_call_meths expose_bindings['minargs'] = JavaTemplate(str(minargs)) expose_bindings['maxargs'] = JavaTemplate(str(maxargs)) self.statements.append(expose.tbind(expose_bindings)) def dire_expose_cmeth(self,name,parm,body): if body is None: body = 'return `concat`(`deleg_prefix,`name)((PyType)getSelf(),`all);' parm, prefix, body = self.expose_meth_body(name, parm, body) expose = self.get_aux('expose_narrow_cmeth') type_class = getattr(self, 'type_class', None) parms = parm.strip().split(None,1) if len(parms) not in (1,2): self.invalid(name,parm) if len(parms) == 1: parms.append('') expose_bindings = {} expose_bindings['typ'] = type_class expose_bindings['name'] = JavaTemplate(parms[0]) expose_bindings['deleg_prefix'] = make_name(prefix) # !!! call_meths_bindings = expose_bindings.copy() body_bindings = self.global_bindings.copy() body_bindings.update(expose_bindings) call_meths_bindings['call_meths'] = self.get_aux('call_cmeths').tbind({'typ': type_class}) inst_call_meths,minargs,maxargs = self.handle_expose_meth_sig(parms[1],call_meths_bindings,body,body_bindings) expose_bindings['call_meths'] = inst_call_meths expose_bindings['minargs'] = JavaTemplate(str(minargs)) expose_bindings['maxargs'] = JavaTemplate(str(maxargs)) self.statements.append(expose.tbind(expose_bindings)) def dire_expose_unary(self,name,parm,body): if body is not None: self.invalid(name,'non-empty body') meth_names = parm.split() if meth_names[0].endswith('>'): meth_names = ["%s %s" % (meth_names[0], n) for n in meth_names[1:]] unary_body = self.get_aux('unary').fragment for meth_name in meth_names: self.dire_expose_meth('expose_unary_1',meth_name,unary_body) def dire_expose_binary(self,name,parm,body): if body is not None: self.invalid(name,'non-empty body') meth_names = parm.split() if meth_names[0].endswith('>'): meth_names = ["%s %s" % (meth_names[0], n) for n in meth_names[1:]] binary_body = self.get_aux('binary').fragment for meth_name in meth_names: self.dire_expose_meth('expose_binary_1',"%s o" % meth_name,binary_body) def dire_expose_key_getitem(self,name,parm,body): if body is not None: self.invalid(name,'non-empty body') prefix = "" if parm.endswith('>'): prefix = parm key_getitem_body = self.get_aux('key_getitem').fragment self.dire_expose_meth('expose_key_getitem',"%s __getitem__ o" % prefix,key_getitem_body) def dire_expose_index_getitem(self,name,parm,body): if body is not None: self.invalid(name,'non-empty body') prefix = "" if parm.endswith('>'): prefix = parm index_getitem_body = self.get_aux('index_getitem').fragment self.dire_expose_meth('expose_index_getitem',"%s __getitem__ o" % prefix,index_getitem_body) def dire_expose_vanilla_cmp(self,name,parm,body): if body is not None: self.invalid(name,'non-empty body') prefix = "" if parm.endswith('>'): prefix = parm vanilla_cmp_body = self.get_aux('vanilla_cmp').fragment self.dire_expose_meth('expose_vanilla_cmp',"%s __cmp__ o" % prefix,vanilla_cmp_body) def dire_expose_vanilla_pow(self,name,parm,body): if body is not None: self.invalid(name,'non-empty body') prefix = "" if parm.endswith('>'): prefix = parm vanilla_pow_body = self.get_aux('vanilla_pow').fragment self.dire_expose_meth('expose_vanilla_pow',"%s __pow__ oo?(null)" % prefix,vanilla_pow_body) def dire_expose_wide_meth(self,name,parm,body): # !!! parm, prefix, body = self.expose_meth_body(name, parm, body) parms = parm.split() args = JavaTemplate("void(PyObject[] args,String[] keywords)") all = JavaTemplate("args, keywords",start='Expressions') bindings = self.global_bindings.copy() if len(parms) not in (1,3): self.invalid(name,parm) bindings['name'] = JavaTemplate(parms[0]) bindings['deleg_prefix'] = make_name(prefix) bindings['all'] = all bindings['args'] = args for deleg_templ_name in ('void','deleg','vdeleg','rdeleg'): deleg_templ = self.get_aux(deleg_templ_name) bindings[deleg_templ_name] = deleg_templ.tbind(bindings) body = JavaTemplate(body).tbind(bindings) bindings['body'] = body call_meths = self.get_aux('call_meths').tbind(bindings) bindings['call_meths'] = call_meths parms = (parms+[-1,-1])[1:3] bindings['minargs'] = JavaTemplate(parms[0]) bindings['maxargs'] = JavaTemplate(parms[1]) expose = self.get_aux('expose_wide_meth').tbind(bindings) self.statements.append(expose) def dire_expose_new_mutable(self,name,parm,body): expose_new = self.get_aux('expose_new') parms = parm.split() body_bindings = self.global_bindings.copy() if body is None: body = self.get_aux('mutable_new_body') else: body = JavaTemplate(body) if not parms: parms = ['-1','-1'] else: if len(parms) != 2: self.invalid(name,parm) body_bindings['minargs'] = JavaTemplate(parms[0]) body_bindings['maxargs'] = JavaTemplate(parms[1]) body = body.tbind(body_bindings) templ = expose_new.tbind(body_bindings) self.statements.append(templ.tbind({'body': body})) def dire_expose_new_immutable(self,name,parm,body): expose_new = self.get_aux('expose_new') parms = parm.split() body_bindings = self.global_bindings.copy() if body is not None: self.invalid(name,"non-empty body") body = self.get_aux('immutable_new_body') if not parms: parms = ['-1','-1'] else: if len(parms) != 2: self.invalid(name,parm) body_bindings['minargs'] = JavaTemplate(parms[0]) body_bindings['maxargs'] = JavaTemplate(parms[1]) body = body.tbind(body_bindings) templ = expose_new.tbind(body_bindings) self.statements.append(templ.tbind({'body': body})) def dire_rest(self,name,parm,body): if parm: self.invalid(name,'non-empty parm') if body is None: return self.statements.append(JavaTemplate(body,start='BlockStatements')) def generate(self): typeinfo0 = self.get_aux('typeinfo0') basic = JavaTemplate("",start='ClassBodyDeclarations') bindings = self.global_bindings.copy() if hasattr(self,'type_as'): basic = (basic + JavaTemplate("public static final Class exposed_as = `as.class;", start = 'ClassBodyDeclarations')) bindings['as'] = self.type_as else: basic = (basic + JavaTemplate( "public static final String exposed_name = `strfy`(`name);", start='ClassBodyDeclarations')) bindings['name'] = self.type_name if hasattr(self,'type_base_class'): basic = (basic + JavaTemplate( "public static final Class exposed_base = `base.class;", start='ClassBodyDeclarations')) bindings['base'] = self.type_base_class typeinfo = typeinfo0 setup = JavaTemplate("",start='BlockStatements') if not self.no_setup: typeinfo1 = self.get_aux('typeinfo1') pair = self.get_aux('pair') for statement in self.statements: setup = pair.tbind({'trailer': setup, 'last': statement}) typeinfo = typeinfo.tfree() + typeinfo1.tfree() return typeinfo.tnaked().texpand({'basic': basic.tbind(bindings), 'setup': setup},nindent=1) def process(fn, mergefile=None, lazy=False): if lazy and mergefile and os.stat(fn).st_mtime < os.stat(mergefile).st_mtime: return print mergefile gen = Gen() directives.execute(directives.load(fn),gen) result = gen.generate() if mergefile is None: print result else: print 'Merging %s into %s' % (fn, mergefile) result = merge(mergefile, result) #gen.debug() def merge(filename, generated): in_generated = False start_found = False end_found = False start_pattern = ' //~ BEGIN GENERATED REGION -- DO NOT EDIT SEE gexpose.py' end_pattern = ' //~ END GENERATED REGION -- DO NOT EDIT SEE gexpose.py' output = [] f = file(filename, 'r') for line in f: if line.startswith(start_pattern): in_generated = True start_found = True elif line.startswith(end_pattern): in_generated = False end_found = True output.append('%s\n%s\n%s\n' % (start_pattern, generated, end_pattern)) elif in_generated: continue else: output.append(line) f.close() if not start_found: raise 'pattern [%s] not found in %s' % (start_pattern, filename) if not end_found: raise 'pattern [%s] not found in %s' % (end_pattern, filename) f = file(filename, 'w') f.write("".join(output)) f.close() def load_mappings(): scriptdir = os.path.dirname(os.path.abspath(__file__)) srcdir = os.path.dirname(scriptdir) mappings = {} for line in open(os.path.join(scriptdir, 'mappings')): if line.strip() is '' or line.startswith('#'): continue tmpl, klass = line.strip().split(':') mappings[tmpl] = (os.path.join(scriptdir, tmpl), os.path.join(srcdir, *klass.split('.')) + '.java') return mappings def usage(): print """Usage: python %s [--lazy|--help] <template> <outfile> If lazy is given, a template is only processed if its modtime is greater than outfile. If outfile isn't specified, the outfile from mappings for the given template is used. If template isn't given, all templates from mappings are processed.""" % sys.argv[0] if __name__ == '__main__': lazy = False if len(sys.argv) > 4: usage() sys.exit(1) if len(sys.argv) >= 2: if '--help' in sys.argv: usage() sys.exit(0) elif '--lazy' in sys.argv: lazy = True sys.argv.remove('--lazy') mappings = load_mappings() if len(sys.argv) == 1: for template, mapping in mappings.items(): if template.endswith('expose'): process(mapping[0], mapping[1], lazy) elif len(sys.argv) == 2: mapping = mappings[sys.argv[1]] process(mapping[0], mapping[1], lazy) else: process(sys.argv[1], sys.argv[2], lazy)
# -*- coding: utf-8 -*- # Copyright 2010-2021, 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: # # * 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 Google Inc. 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. """A library to operate version definition file. This script has two functionarity which relate to version definition file. 1. Generate version definition file from template and given parameters. To generate version definition file, use GenerateVersionFileFromTemplate method. 2. Parse (generated) version definition file. To parse, use MozcVersion class. Typically version definition file is ${PROJECT_ROOT}/mozc_version.txt (Not in the repository because it is generated by this script) Typically version template file is ${PROJECT_ROOT}/data/version/mozc_version_template.bzl, which is in the repository. The syntax of template is written in the template file. """ # TODO(matsuzaki): MozcVersion class should have factory method which takes # file path and we should remove all the module methods instead to # simplify the design. Currently I'd keep this design to reduce # client side's change. from __future__ import absolute_import import datetime import logging import optparse import os import re import sys TARGET_PLATFORM_TO_DIGIT = { 'Windows': '0', 'Mac': '1', 'Linux': '2', 'Android': '3', 'ChromeOS': '4', 'iOS': '6', 'iOS_sim': '6', 'Wasm': '7', } VERSION_PROPERTIES = [ 'MAJOR', 'MINOR', 'BUILD', 'REVISION', 'TARGET_PLATFORM', 'BUILD_OSS', 'QT_VERSION', 'ENGINE_VERSION', 'DATA_VERSION', ] MOZC_EPOCH = datetime.date(2009, 5, 24) def _GetRevisionForPlatform(revision, target_platform): """Returns the revision for the current platform.""" if revision is None: logging.critical('REVISION property is not found in the template file') sys.exit(1) last_digit = TARGET_PLATFORM_TO_DIGIT.get(target_platform, None) if last_digit is None: logging.critical('target_platform %s is invalid. Accetable ones are %s', target_platform, list(TARGET_PLATFORM_TO_DIGIT.keys())) sys.exit(1) if not revision: return revision if last_digit: return revision[0:-1] + last_digit # If not supported, just use the specified version. return revision def _ParseVersionTemplateFile(template_path, target_platform, version_override): """Parses a version definition file. Args: template_path: A filename which has the version definition. target_platform: The target platform on which the programs run. version_override: An optional string to override version number. If it is a single number, it means a build number (e.g. "4500"). If it is a four numbers, it means a full version (e.g. "2.28.4500.0"). Returns: A dictionary generated from the template file. """ template_dict = {} with open(template_path) as template_file: for line in template_file: matchobj = re.match(r'(\w+) *= *(\w*)', line.strip()) if matchobj: var = matchobj.group(1) val = matchobj.group(2) if var in template_dict: logging.warning(('Dupulicate key: "%s". Later definition "%s"' 'overrides earlier one "%s".'), var, val, template_dict[var]) # If `val` is a variable (e.g. BUILD_OSS), replace it with the value. if val in template_dict: val = template_dict[val] template_dict[var] = val # Some properties need to be tweaked. template_dict['REVISION'] = _GetRevisionForPlatform( template_dict.get('REVISION', None), target_platform) template_dict['TARGET_PLATFORM'] = target_platform if version_override: nums = version_override.split('.') if len(nums) == 1: template_dict['BUILD'] = nums[0] if len(nums) == 4: template_dict['MAJOR'] = nums[0] template_dict['MINOR'] = nums[1] template_dict['BUILD'] = nums[2] template_dict['REVISION'] = nums[3] return template_dict def _GetVersionInFormat(properties, version_format): """Returns the version string based on the specified format. format can contains @MAJOR@, @MINOR@, @BUILD@ and @REVISION@ which are replaced by self._major, self._minor, self._build, and self._revision respectively. Args: properties: a property dicitonary. Typically gotten from _ParseVersionTemplateFile method. version_format: a string which contains version patterns. Returns: Return the version string in the format of format. """ result = version_format for keyword in VERSION_PROPERTIES: result = result.replace('@%s@' % keyword, properties.get(keyword, '')) return result def _GetChangelistNumber(build_override, build_changelist_file): """Returns the changelist number from the value or the file path.""" if build_override: return build_override if not build_changelist_file: return None with open(build_changelist_file, 'r') as cl_file: for line in cl_file: if line.startswith('BUILD_CHANGELIST'): return line.rstrip().split(' ')[1] return None def GenerateVersionFileFromTemplate(template_path, output_path, version_format, target_platform, version_override=None): """Generates version file from template file and given parameters. Args: template_path: A path to template file. output_path: A path to generated version file. If already exists and the content will not be updated, nothing is done (the timestamp is not updated). version_format: A string which contains version patterns. target_platform: The target platform on which the programs run. version_override: An optional string to override BUILD number in the template. If it is a single number, it means a build number (e.g. "4500"). If it is a four numbers, it means a full version (e.g. "2.28.4500.0"). """ properties = _ParseVersionTemplateFile(template_path, target_platform, version_override) version_definition = _GetVersionInFormat(properties, version_format) old_content = '' if os.path.exists(output_path): # If the target file already exists, need to check the necessity of update # to reduce file-creation frequency. # Currently generated version file is not seen from Make (and Make like # tools) so recreation will not cause serious issue but just in case. with open(output_path) as output_file: old_content = output_file.read() if version_definition != old_content: with open(output_path, 'w') as output_file: output_file.write(version_definition) def GenerateVersionFile(version_template_path, version_path, target_platform, version_override=None): """Reads the version template file and stores it into version_path. This doesn't update the "version_path" if nothing will be changed to reduce unnecessary build caused by file timestamp. Args: version_template_path: a file name which contains the template of version. version_path: a file name to be stored the official version. target_platform: target platform name. c.f. --target_platform option version_override: an optional string to override version number. If it is a single number, it means a build number (e.g. "4500"). If it is a four numbers, it means a full version (e.g. "2.28.4500.0"). """ version_format = '\n'.join([ 'MAJOR=@MAJOR@', 'MINOR=@MINOR@', 'BUILD=@BUILD@', 'REVISION=@REVISION@', 'TARGET_PLATFORM=@TARGET_PLATFORM@', 'BUILD_OSS=@BUILD_OSS@', 'QT_VERSION=@QT_VERSION@', 'ENGINE_VERSION=@ENGINE_VERSION@', 'DATA_VERSION=@DATA_VERSION@', ]) + '\n' GenerateVersionFileFromTemplate( version_template_path, version_path, version_format, target_platform=target_platform, version_override=version_override) class MozcVersion(object): """A class to parse and maintain the version definition data. Note that this class is not intended to parse "template" file but to "generated" file. Typical usage is; GenerateVersionFileFromTemplate(template_path, version_path, format) version = MozcVersion(version_path) """ def __init__(self, path): """Parses a version definition file. Args: path: A filename which has the version definition. If the file is not existent, empty properties are prepared instead. """ self._properties = {} if not os.path.isfile(path): return for line in open(path): matchobj = re.match(r'(\w+)=(.*)', line.strip()) if matchobj: var = matchobj.group(1) val = matchobj.group(2) if var not in self._properties: self._properties[var] = val # Check mandatory properties. for key in VERSION_PROPERTIES: if key not in self._properties: # Don't raise error nor exit. # Error handling is the client's responsibility. logging.warning('Mandatory key "%s" does not exist in %s', key, path) def IsDevChannel(self): """Returns true if the parsed version is dev-channel.""" revision = self._properties['REVISION'] return revision is not None and len(revision) >= 3 and revision[-3] == '1' def GetTargetPlatform(self): """Returns the target platform. Returns: A string for target platform. If the version file is not existent, None is returned. """ return self._properties.get('TARGET_PLATFORM', None) def GetVersionString(self): """Returns the normal version info string. Returns: a string in format of "MAJOR.MINOR.BUILD.REVISION" """ return self.GetVersionInFormat('@MAJOR@.@MINOR@.@BUILD@.@REVISION@') def GetShortVersionString(self, use_build_oss=False): """Returns the short version info string. Args: use_build_oss: use BUILD_OSS if true. Returns: a string in format of "MAJOR.MINOR.BUILD" """ if use_build_oss: return self.GetVersionInFormat('@MAJOR@.@MINOR@.@BUILD_OSS@') return self.GetVersionInFormat('@MAJOR@.@MINOR@.@BUILD@') def GetVersionInFormat(self, version_format): """Returns the version string based on the specified format.""" return _GetVersionInFormat(self._properties, version_format) def main(): """Generates version file based on the default format. Generated file is mozc_version.txt compatible. """ parser = optparse.OptionParser(usage='Usage: %prog ') parser.add_option('--template_path', dest='template_path', help='Path to a template version file.') parser.add_option('--output', dest='output', help='Path to the output version file.') parser.add_option('--target_platform', dest='target_platform', help='Target platform of the version info.') parser.add_option('--build_override', dest='build_override', help='Overrides BUILD number in the template.') parser.add_option('--build_changelist_file', dest='build_changelist_file', help='Filepath containing the BUILD number.') (options, args) = parser.parse_args() assert not args, 'Unexpected arguments.' assert options.template_path, 'No --template_path was specified.' assert options.output, 'No --output was specified.' assert options.target_platform, 'No --target_platform was specified.' cl_number = _GetChangelistNumber(options.build_override, options.build_changelist_file) GenerateVersionFile( version_template_path=options.template_path, version_path=options.output, target_platform=options.target_platform, version_override=cl_number) if __name__ == '__main__': main()
"""Tests for certbot.le_util.""" import argparse import errno import os import shutil import stat import tempfile import unittest import mock import six from certbot import errors class RunScriptTest(unittest.TestCase): """Tests for certbot.le_util.run_script.""" @classmethod def _call(cls, params): from certbot.le_util import run_script return run_script(params) @mock.patch("certbot.le_util.subprocess.Popen") def test_default(self, mock_popen): """These will be changed soon enough with reload.""" mock_popen().returncode = 0 mock_popen().communicate.return_value = ("stdout", "stderr") out, err = self._call(["test"]) self.assertEqual(out, "stdout") self.assertEqual(err, "stderr") @mock.patch("certbot.le_util.subprocess.Popen") def test_bad_process(self, mock_popen): mock_popen.side_effect = OSError self.assertRaises(errors.SubprocessError, self._call, ["test"]) @mock.patch("certbot.le_util.subprocess.Popen") def test_failure(self, mock_popen): mock_popen().communicate.return_value = ("", "") mock_popen().returncode = 1 self.assertRaises(errors.SubprocessError, self._call, ["test"]) class ExeExistsTest(unittest.TestCase): """Tests for certbot.le_util.exe_exists.""" @classmethod def _call(cls, exe): from certbot.le_util import exe_exists return exe_exists(exe) @mock.patch("certbot.le_util.os.path.isfile") @mock.patch("certbot.le_util.os.access") def test_full_path(self, mock_access, mock_isfile): mock_access.return_value = True mock_isfile.return_value = True self.assertTrue(self._call("/path/to/exe")) @mock.patch("certbot.le_util.os.path.isfile") @mock.patch("certbot.le_util.os.access") def test_on_path(self, mock_access, mock_isfile): mock_access.return_value = True mock_isfile.return_value = True self.assertTrue(self._call("exe")) @mock.patch("certbot.le_util.os.path.isfile") @mock.patch("certbot.le_util.os.access") def test_not_found(self, mock_access, mock_isfile): mock_access.return_value = False mock_isfile.return_value = True self.assertFalse(self._call("exe")) class MakeOrVerifyDirTest(unittest.TestCase): """Tests for certbot.le_util.make_or_verify_dir. Note that it is not possible to test for a wrong directory owner, as this testing script would have to be run as root. """ def setUp(self): self.root_path = tempfile.mkdtemp() self.path = os.path.join(self.root_path, "foo") os.mkdir(self.path, 0o400) self.uid = os.getuid() def tearDown(self): shutil.rmtree(self.root_path, ignore_errors=True) def _call(self, directory, mode): from certbot.le_util import make_or_verify_dir return make_or_verify_dir(directory, mode, self.uid, strict=True) def test_creates_dir_when_missing(self): path = os.path.join(self.root_path, "bar") self._call(path, 0o650) self.assertTrue(os.path.isdir(path)) self.assertEqual(stat.S_IMODE(os.stat(path).st_mode), 0o650) def test_existing_correct_mode_does_not_fail(self): self._call(self.path, 0o400) self.assertEqual(stat.S_IMODE(os.stat(self.path).st_mode), 0o400) def test_existing_wrong_mode_fails(self): self.assertRaises(errors.Error, self._call, self.path, 0o600) def test_reraises_os_error(self): with mock.patch.object(os, "makedirs") as makedirs: makedirs.side_effect = OSError() self.assertRaises(OSError, self._call, "bar", 12312312) class CheckPermissionsTest(unittest.TestCase): """Tests for certbot.le_util.check_permissions. Note that it is not possible to test for a wrong file owner, as this testing script would have to be run as root. """ def setUp(self): _, self.path = tempfile.mkstemp() self.uid = os.getuid() def tearDown(self): os.remove(self.path) def _call(self, mode): from certbot.le_util import check_permissions return check_permissions(self.path, mode, self.uid) def test_ok_mode(self): os.chmod(self.path, 0o600) self.assertTrue(self._call(0o600)) def test_wrong_mode(self): os.chmod(self.path, 0o400) self.assertFalse(self._call(0o600)) class UniqueFileTest(unittest.TestCase): """Tests for certbot.le_util.unique_file.""" def setUp(self): self.root_path = tempfile.mkdtemp() self.default_name = os.path.join(self.root_path, "foo.txt") def tearDown(self): shutil.rmtree(self.root_path, ignore_errors=True) def _call(self, mode=0o600): from certbot.le_util import unique_file return unique_file(self.default_name, mode) def test_returns_fd_for_writing(self): fd, name = self._call() fd.write("bar") fd.close() self.assertEqual(open(name).read(), "bar") def test_right_mode(self): self.assertEqual(0o700, os.stat(self._call(0o700)[1]).st_mode & 0o777) self.assertEqual(0o100, os.stat(self._call(0o100)[1]).st_mode & 0o777) def test_default_exists(self): name1 = self._call()[1] # create 0000_foo.txt name2 = self._call()[1] name3 = self._call()[1] self.assertNotEqual(name1, name2) self.assertNotEqual(name1, name3) self.assertNotEqual(name2, name3) self.assertEqual(os.path.dirname(name1), self.root_path) self.assertEqual(os.path.dirname(name2), self.root_path) self.assertEqual(os.path.dirname(name3), self.root_path) basename1 = os.path.basename(name2) self.assertTrue(basename1.endswith("foo.txt")) basename2 = os.path.basename(name2) self.assertTrue(basename2.endswith("foo.txt")) basename3 = os.path.basename(name3) self.assertTrue(basename3.endswith("foo.txt")) class UniqueLineageNameTest(unittest.TestCase): """Tests for certbot.le_util.unique_lineage_name.""" def setUp(self): self.root_path = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.root_path, ignore_errors=True) def _call(self, filename, mode=0o777): from certbot.le_util import unique_lineage_name return unique_lineage_name(self.root_path, filename, mode) def test_basic(self): f, path = self._call("wow") self.assertTrue(isinstance(f, file)) self.assertEqual(os.path.join(self.root_path, "wow.conf"), path) def test_multiple(self): for _ in xrange(10): f, name = self._call("wow") self.assertTrue(isinstance(f, file)) self.assertTrue(isinstance(name, str)) self.assertTrue("wow-0009.conf" in name) @mock.patch("certbot.le_util.os.fdopen") def test_failure(self, mock_fdopen): err = OSError("whoops") err.errno = errno.EIO mock_fdopen.side_effect = err self.assertRaises(OSError, self._call, "wow") @mock.patch("certbot.le_util.os.fdopen") def test_subsequent_failure(self, mock_fdopen): self._call("wow") err = OSError("whoops") err.errno = errno.EIO mock_fdopen.side_effect = err self.assertRaises(OSError, self._call, "wow") class SafelyRemoveTest(unittest.TestCase): """Tests for certbot.le_util.safely_remove.""" def setUp(self): self.tmp = tempfile.mkdtemp() self.path = os.path.join(self.tmp, "foo") def tearDown(self): shutil.rmtree(self.tmp) def _call(self): from certbot.le_util import safely_remove return safely_remove(self.path) def test_exists(self): with open(self.path, "w"): pass # just create the file self._call() self.assertFalse(os.path.exists(self.path)) def test_missing(self): self._call() # no error, yay! self.assertFalse(os.path.exists(self.path)) @mock.patch("certbot.le_util.os.remove") def test_other_error_passthrough(self, mock_remove): mock_remove.side_effect = OSError self.assertRaises(OSError, self._call) class SafeEmailTest(unittest.TestCase): """Test safe_email.""" @classmethod def _call(cls, addr): from certbot.le_util import safe_email return safe_email(addr) def test_valid_emails(self): addrs = [ "certbot@certbot.org", "tbd.ade@gmail.com", "abc_def.jdk@hotmail.museum", ] for addr in addrs: self.assertTrue(self._call(addr), "%s failed." % addr) def test_invalid_emails(self): addrs = [ "certbot@certbot..org", ".tbd.ade@gmail.com", "~/abc_def.jdk@hotmail.museum", ] for addr in addrs: self.assertFalse(self._call(addr), "%s failed." % addr) class AddDeprecatedArgumentTest(unittest.TestCase): """Test add_deprecated_argument.""" def setUp(self): self.parser = argparse.ArgumentParser() def _call(self, argument_name, nargs): from certbot.le_util import add_deprecated_argument add_deprecated_argument(self.parser.add_argument, argument_name, nargs) def test_warning_no_arg(self): self._call("--old-option", 0) stderr = self._get_argparse_warnings(["--old-option"]) self.assertTrue("--old-option is deprecated" in stderr) def test_warning_with_arg(self): self._call("--old-option", 1) stderr = self._get_argparse_warnings(["--old-option", "42"]) self.assertTrue("--old-option is deprecated" in stderr) def _get_argparse_warnings(self, args): stderr = six.StringIO() with mock.patch("certbot.le_util.sys.stderr", new=stderr): self.parser.parse_args(args) return stderr.getvalue() def test_help(self): self._call("--old-option", 2) stdout = six.StringIO() with mock.patch("certbot.le_util.sys.stdout", new=stdout): try: self.parser.parse_args(["-h"]) except SystemExit: pass self.assertTrue("--old-option" not in stdout.getvalue()) class EnforceDomainSanityTest(unittest.TestCase): """Test enforce_domain_sanity.""" def _call(self, domain): from certbot.le_util import enforce_domain_sanity return enforce_domain_sanity(domain) def test_nonascii_str(self): self.assertRaises(errors.ConfigurationError, self._call, u"eichh\u00f6rnchen.example.com".encode("utf-8")) def test_nonascii_unicode(self): self.assertRaises(errors.ConfigurationError, self._call, u"eichh\u00f6rnchen.example.com") if __name__ == "__main__": unittest.main() # pragma: no cover
# Authors: Dirko Coetsee # License: 3-clause BSD """ Implements a Hidden Alignment Conditional Random Field (HACRF). """ import numpy as np import lbfgs from .algorithms import forward, backward from .algorithms import forward_predict, forward_max_predict from .algorithms import gradient, gradient_sparse, populate_sparse_features, sparse_multiply from .state_machine import DefaultStateMachine class Hacrf(object): """ Hidden Alignment Conditional Random Field with L2 regularizer. Parameters ---------- l2_regularization : float, optional (default=0.0) The regularization parameter. optimizer : function, optional (default=None) The optimizing function that should be used minimize the negative log posterior. The function should have the signature: min_objective, argmin_objective, ... = fmin(obj, x0, **optimizer_kwargs), where obj is a function that returns the objective function and its gradient given a parameter vector; and x0 is the initial parameter vector. optimizer_kwargs : dictionary, optional (default=None) The keyword arguments to pass to the optimizing function. Only used when `optimizer` is also specified. state_machine : Instance of `GeneralStateMachine` or `DefaultStateMachine`, optional (default=`DefaultStateMachine`) The state machine to use to generate the lattice. viterbi : Boolean, optional (default=False). Whether to use Viterbi (max-sum) decoding for predictions (not training) instead of the default sum-product algorithm. References ---------- See *A Conditional Random Field for Discriminatively-trained Finite-state String Edit Distance* by McCallum, Bellare, and Pereira, and the report *Conditional Random Fields for Noisy text normalisation* by Dirko Coetsee. """ def __init__(self, l2_regularization=0.0, optimizer=None, optimizer_kwargs=None, state_machine=None, viterbi=False): self.parameters = None self.classes = None self.l2_regularization = l2_regularization self._optimizer = optimizer self._optimizer_kwargs = optimizer_kwargs self.viterbi = viterbi self._optimizer_result = None self._state_machine = state_machine self._states_to_classes = None self._evaluation_count = None def fit(self, X, y, verbosity=0): """Fit the model according to the given training data. Parameters ---------- X : List of ndarrays, one for each training example. Each training example's shape is (string1_len, string2_len, n_features), where string1_len and string2_len are the length of the two training strings and n_features the number of features. y : array-like, shape (n_samples,) Target vector relative to X. Returns ------- self : object Returns self. """ self.classes = list(set(y)) n_points = len(y) if len(X) != n_points: raise Exception('Number of training points should be the same as training labels.') if not self._state_machine: self._state_machine = DefaultStateMachine(self.classes) # Initialize the parameters given the state machine, features, and target classes. self.parameters = self._initialize_parameters(self._state_machine, X[0].shape[2]) # Create a new model object for each training example models = [_Model(self._state_machine, x, ty) for x, ty in zip(X, y)] self._evaluation_count = 0 def _objective(parameters): gradient = np.zeros(self.parameters.shape) ll = 0.0 # Log likelihood # TODO: Embarrassingly parallel for model in models: dll, dgradient = model.forward_backward(parameters.reshape(self.parameters.shape)) ll += dll gradient += dgradient parameters_without_bias = np.array(parameters, dtype='float64') # exclude the bias parameters from being regularized parameters_without_bias[0] = 0 ll -= self.l2_regularization * np.dot(parameters_without_bias.T, parameters_without_bias) gradient = gradient.flatten() - 2.0 * self.l2_regularization * parameters_without_bias if verbosity > 0: if self._evaluation_count == 0: print('{:10} {:10} {:10}'.format('Iteration', 'Log-likelihood', '|gradient|')) if self._evaluation_count % verbosity == 0: print('{:10} {:10.4} {:10.4}'.format(self._evaluation_count, ll, (abs(gradient).sum()))) self._evaluation_count += 1 # TODO: Allow some of the parameters to be frozen. ie. not trained. Can later also completely remove # TODO: the computation associated with these parameters. return -ll, -gradient def _objective_copy_gradient(paramers, g): nll, ngradient = _objective(paramers) g[:] = ngradient return nll if self._optimizer: self.optimizer_result = self._optimizer(_objective, self.parameters.flatten(), **self._optimizer_kwargs) self.parameters = self.optimizer_result[0].reshape(self.parameters.shape) else: optimizer = lbfgs.LBFGS() final_betas = optimizer.minimize(_objective_copy_gradient, x0=self.parameters.flatten(), progress=None) self.optimizer_result = final_betas self.parameters = final_betas.reshape(self.parameters.shape) return self def predict_proba(self, X): """Probability estimates. The returned estimates for all classes are ordered by the label of classes. Parameters ---------- X : List of ndarrays, one for each training example. Each training example's shape is (string1_len, string2_len, n_features, where string1_len and string2_len are the length of the two training strings and n_features the number of features. Returns ------- T : array-like, shape = [n_samples, n_classes] Returns the probability of the sample for each class in the model, where classes are ordered as they are in ``self.classes_``. """ parameters = np.ascontiguousarray(self.parameters.T) predictions = [_Model(self._state_machine, x).predict(parameters, self.viterbi) for x in X] predictions = np.array([[probability for _, probability in sorted(prediction.items())] for prediction in predictions]) return predictions def predict(self, X): """Predict the class for X. The predicted class for each sample in X is returned. Parameters ---------- X : List of ndarrays, one for each training example. Each training example's shape is (string1_len, string2_len, n_features), where string1_len and string2_len are the length of the two training strings and n_features the number of features. Returns ------- y : iterable of shape = [n_samples] The predicted classes. """ return [self.classes[prediction.argmax()] for prediction in self.predict_proba(X)] @staticmethod def _initialize_parameters(state_machine, n_features): """ Helper to create initial parameter vector with the correct shape. """ return np.zeros((state_machine.n_states + state_machine.n_transitions, n_features)) def get_params(self, deep=True): """Get parameters for this estimator. Parameters ---------- deep: boolean, optional If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns ------- params : mapping of string to any Parameter names mapped to their values. """ return {'l2_regularization': self.l2_regularization, 'optimizer': self._optimizer, 'optimizer_kwargs': self._optimizer_kwargs} def set_params(self, l2_regularization=0.0, optimizer=None, optimizer_kwargs=None): """Set the parameters of this estimator. Returns ------- self """ self.l2_regularization = l2_regularization self._optimizer = optimizer self._optimizer_kwargs = optimizer_kwargs return self class _Model(object): """ The actual model that implements the inference routines. """ def __init__(self, state_machine, x, y=None): self.state_machine = state_machine self.states_to_classes = state_machine.states_to_classes self.x = x self.sparse_x = 'uninitialized' self.y = y self._lattice = self.state_machine.build_lattice(self.x) def forward_backward(self, parameters): """ Run the forward backward algorithm with the given parameters. """ # If the features are sparse, we can use an optimization. # I'm not using scipy.sparse here because we want to avoid a scipy dependency and also scipy.sparse doesn't seem # to handle arrays of shape higher than 2. if isinstance(self.sparse_x, str) and self.sparse_x == 'uninitialized': if (self.x == 0).sum() * 1.0 / self.x.size > 0.6: self.sparse_x = self._construct_sparse_features(self.x) else: self.sparse_x = 'not sparse' I, J, K = self.x.shape if not isinstance(self.sparse_x, str): C = self.sparse_x[0].shape[2] S, _ = parameters.shape x_dot_parameters = np.zeros((I, J, S)) sparse_multiply(x_dot_parameters, self.sparse_x[0], self.sparse_x[1], parameters.T, I, J, K, C, S) else: x_dot_parameters = np.dot(self.x, parameters.T) # Pre-compute the dot product alpha = self._forward(x_dot_parameters) beta = self._backward(x_dot_parameters) classes_to_ints = {k: i for i, k in enumerate(set(self.states_to_classes.values()))} states_to_classes = np.array([classes_to_ints[self.states_to_classes[state]] for state in range(max(self.states_to_classes.keys()) + 1)], dtype='int64') if not isinstance(self.sparse_x, str): ll, deriv = gradient_sparse(alpha, beta, parameters, states_to_classes, self.sparse_x[0], self.sparse_x[1], classes_to_ints[self.y], I, J, self.sparse_x[0].shape[2]) else: ll, deriv = gradient(alpha, beta, parameters, states_to_classes, self.x, classes_to_ints[self.y], I, J, K) return ll, deriv def predict(self, parameters, viterbi): """ Run forward algorithm to find the predicted distribution over classes. """ x_dot_parameters = np.einsum('ijk,kl->ijl', self.x, parameters) if not viterbi: alpha = forward_predict(self._lattice, x_dot_parameters, self.state_machine.n_states) else: alpha = forward_max_predict(self._lattice, x_dot_parameters, self.state_machine.n_states) I, J, _ = self.x.shape class_Z = {} Z = -np.inf for state, predicted_class in self.states_to_classes.items(): weight = alpha[I - 1, J - 1, state] class_Z[self.states_to_classes[state]] = weight Z = np.logaddexp(Z, weight) return {label: np.exp(class_z - Z) for label, class_z in class_Z.items()} def _forward(self, x_dot_parameters): """ Helper to calculate the forward weights. """ return forward(self._lattice, x_dot_parameters, self.state_machine.n_states) def _backward(self, x_dot_parameters): """ Helper to calculate the backward weights. """ I, J, _ = self.x.shape return backward(self._lattice, x_dot_parameters, I, J, self.state_machine.n_states) def _construct_sparse_features(self, x): """ Helper to construct a sparse representation of the features. """ I, J, K = x.shape new_array_height = (x != 0).sum(axis=2).max() index_array = -np.ones((I, J, new_array_height), dtype='int64') value_array = -np.ones((I, J, new_array_height), dtype='float64') populate_sparse_features(x, index_array, value_array, I, J, K) return index_array, value_array
from __future__ import unicode_literals import json import re from unidecode import unidecode from django.db import models from django.shortcuts import render from django.utils.translation import ugettext_lazy as _ from django.utils.text import slugify from django.utils.encoding import python_2_unicode_compatible from django.utils.six import text_type from django.core.serializers.json import DjangoJSONEncoder from wagtail.wagtailcore.models import Page, Orderable, UserPagePermissionsProxy, get_page_types from wagtail.wagtailadmin.edit_handlers import FieldPanel from wagtail.wagtailadmin.utils import send_mail from .forms import FormBuilder FORM_FIELD_CHOICES = ( ('singleline', _('Single line text')), ('multiline', _('Multi-line text')), ('email', _('Email')), ('number', _('Number')), ('url', _('URL')), ('checkbox', _('Checkbox')), ('checkboxes', _('Checkboxes')), ('dropdown', _('Drop down')), ('radio', _('Radio buttons')), ('date', _('Date')), ('datetime', _('Date/time')), ) HTML_EXTENSION_RE = re.compile(r"(.*)\.html") @python_2_unicode_compatible class FormSubmission(models.Model): """Data for a Form submission.""" form_data = models.TextField() page = models.ForeignKey(Page) submit_time = models.DateTimeField(verbose_name=_('Submit time'), auto_now_add=True) def get_data(self): return json.loads(self.form_data) def __str__(self): return self.form_data class Meta: verbose_name = _('Form Submission') class AbstractFormField(Orderable): """ Database Fields required for building a Django Form field. """ label = models.CharField( verbose_name=_('Label'), max_length=255, help_text=_('The label of the form field') ) field_type = models.CharField(verbose_name=_('Field type'), max_length=16, choices=FORM_FIELD_CHOICES) required = models.BooleanField(verbose_name=_('Required'), default=True) choices = models.CharField( verbose_name=_('Choices'), max_length=512, blank=True, help_text=_('Comma separated list of choices. Only applicable in checkboxes, radio and dropdown.') ) default_value = models.CharField( verbose_name=_('Default value'), max_length=255, blank=True, help_text=_('Default value. Comma separated values supported for checkboxes.') ) help_text = models.CharField(verbose_name=_('Help text'), max_length=255, blank=True) @property def clean_name(self): # unidecode will return an ascii string while slugify wants a # unicode string on the other hand, slugify returns a safe-string # which will be converted to a normal str return str(slugify(text_type(unidecode(self.label)))) panels = [ FieldPanel('label'), FieldPanel('help_text'), FieldPanel('required'), FieldPanel('field_type', classname="formbuilder-type"), FieldPanel('choices', classname="formbuilder-choices"), FieldPanel('default_value', classname="formbuilder-default"), ] class Meta: abstract = True ordering = ['sort_order'] _FORM_CONTENT_TYPES = None def get_form_types(): global _FORM_CONTENT_TYPES if _FORM_CONTENT_TYPES is None: _FORM_CONTENT_TYPES = [ ct for ct in get_page_types() if issubclass(ct.model_class(), AbstractForm) ] return _FORM_CONTENT_TYPES def get_forms_for_user(user): """ Return a queryset of form pages that this user is allowed to access the submissions for """ editable_pages = UserPagePermissionsProxy(user).editable_pages() return editable_pages.filter(content_type__in=get_form_types()) class AbstractForm(Page): """ A Form Page. Pages implementing a form should inhert from it """ form_builder = FormBuilder def __init__(self, *args, **kwargs): super(AbstractForm, self).__init__(*args, **kwargs) if not hasattr(self, 'landing_page_template'): template_wo_ext = re.match(HTML_EXTENSION_RE, self.template).group(1) self.landing_page_template = template_wo_ext + '_landing.html' class Meta: abstract = True def get_form_class(self): fb = self.form_builder(self.form_fields.all()) return fb.get_form_class() def get_form_parameters(self): return {} def get_form(self, *args, **kwargs): form_class = self.get_form_class() form_params = self.get_form_parameters() form_params.update(kwargs) return form_class(*args, **form_params) def process_form_submission(self, form): FormSubmission.objects.create( form_data=json.dumps(form.cleaned_data, cls=DjangoJSONEncoder), page=self, ) def serve(self, request): if request.method == 'POST': form = self.get_form(request.POST) if form.is_valid(): self.process_form_submission(form) # render the landing_page # TODO: It is much better to redirect to it return render( request, self.landing_page_template, self.get_context(request) ) else: form = self.get_form() context = self.get_context(request) context['form'] = form return render( request, self.template, context ) preview_modes = [ ('form', 'Form'), ('landing', 'Landing page'), ] def serve_preview(self, request, mode): if mode == 'landing': return render( request, self.landing_page_template, self.get_context(request) ) else: return super(AbstractForm, self).serve_preview(request, mode) class AbstractEmailForm(AbstractForm): """ A Form Page that sends email. Pages implementing a form to be send to an email should inherit from it """ to_address = models.CharField(verbose_name=_('To address'), max_length=255, blank=True, help_text=_("Optional - form submissions will be emailed to this address")) from_address = models.CharField(verbose_name=_('From address'), max_length=255, blank=True) subject = models.CharField(verbose_name=_('Subject'), max_length=255, blank=True) def process_form_submission(self, form): super(AbstractEmailForm, self).process_form_submission(form) if self.to_address: content = '\n'.join([x[1].label + ': ' + text_type(form.data.get(x[0])) for x in form.fields.items()]) send_mail(self.subject, content, [self.to_address], self.from_address,) class Meta: abstract = True
# Copyright 2014 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_log import log import testtools from ec2api.tests.functional import base from ec2api.tests.functional import config CONF = config.CONF LOG = log.getLogger(__name__) class SubnetTest(base.EC2TestCase): BASE_CIDR = '10.2.0.0' VPC_CIDR = BASE_CIDR + '/20' vpc_id = None @classmethod @base.safe_setup def setUpClass(cls): super(SubnetTest, cls).setUpClass() if not base.TesterStateHolder().get_vpc_enabled(): raise cls.skipException('VPC is disabled') resp, data = cls.client.CreateVpc(CidrBlock=cls.VPC_CIDR) cls.assertResultStatic(resp, data) cls.vpc_id = data['Vpc']['VpcId'] cls.addResourceCleanUpStatic(cls.client.DeleteVpc, VpcId=cls.vpc_id) cls.get_vpc_waiter().wait_available(cls.vpc_id) def test_create_delete_subnet(self): cidr = self.BASE_CIDR + '/24' resp, data = self.client.CreateSubnet(VpcId=self.vpc_id, CidrBlock=cidr) self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data)) subnet_id = data['Subnet']['SubnetId'] res_clean = self.addResourceCleanUp(self.client.DeleteSubnet, SubnetId=subnet_id) self.assertEqual(cidr, data['Subnet']['CidrBlock']) self.assertIsNotNone(data['Subnet'].get('AvailableIpAddressCount')) self.get_subnet_waiter().wait_available(subnet_id) resp, data = self.client.DeleteSubnet(SubnetId=subnet_id) self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data)) self.cancelResourceCleanUp(res_clean) self.get_subnet_waiter().wait_delete(subnet_id) resp, data = self.client.DescribeSubnets(SubnetIds=[subnet_id]) self.assertEqual(400, resp.status_code) self.assertEqual('InvalidSubnetID.NotFound', data['Error']['Code']) resp, data = self.client.DeleteSubnet(SubnetId=subnet_id) self.assertEqual(400, resp.status_code) self.assertEqual('InvalidSubnetID.NotFound', data['Error']['Code']) def test_dependency_subnet_to_vpc(self): resp, data = self.client.CreateVpc(CidrBlock=self.VPC_CIDR) self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data)) vpc_id = data['Vpc']['VpcId'] vpc_clean = self.addResourceCleanUp(self.client.DeleteVpc, VpcId=vpc_id) self.get_vpc_waiter().wait_available(vpc_id) cidr = self.BASE_CIDR + '/24' resp, data = self.client.CreateSubnet(VpcId=vpc_id, CidrBlock=cidr) self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data)) subnet_id = data['Subnet']['SubnetId'] res_clean = self.addResourceCleanUp(self.client.DeleteSubnet, SubnetId=subnet_id) self.get_subnet_waiter().wait_available(subnet_id) resp, data = self.client.DeleteVpc(VpcId=vpc_id) self.assertEqual(400, resp.status_code) self.assertEqual('DependencyViolation', data['Error']['Code']) resp, data = self.client.DeleteSubnet(SubnetId=subnet_id) self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data)) self.cancelResourceCleanUp(res_clean) self.get_subnet_waiter().wait_delete(subnet_id) self.client.DeleteVpc(VpcId=vpc_id) self.cancelResourceCleanUp(vpc_clean) @testtools.skipUnless( CONF.aws.run_incompatible_tests, "bug with overlapped subnets") def test_create_overlapped_subnet(self): cidr = self.BASE_CIDR + '/24' resp, data = self.client.CreateSubnet(VpcId=self.vpc_id, CidrBlock=cidr) self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data)) subnet_id = data['Subnet']['SubnetId'] res_clean = self.addResourceCleanUp(self.client.DeleteSubnet, SubnetId=subnet_id) self.get_subnet_waiter().wait_available(subnet_id) cidr = '10.2.0.128/26' resp, data = self.client.CreateSubnet(VpcId=self.vpc_id, CidrBlock=cidr) if resp.status_code == 200: self.addResourceCleanUp(self.client.DeleteSubnet, SubnetId=data['Subnet']['SubnetId']) self.assertEqual(400, resp.status_code) self.assertEqual('InvalidSubnet.Conflict', data['Error']['Code']) resp, data = self.client.DeleteSubnet(SubnetId=subnet_id) self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data)) self.cancelResourceCleanUp(res_clean) self.get_subnet_waiter().wait_delete(subnet_id) def test_create_subnet_invalid_cidr(self): # NOTE(andrey-mp): another cidr than VPC has cidr = '10.1.0.0/24' resp, data = self.client.CreateSubnet(VpcId=self.vpc_id, CidrBlock=cidr) if resp.status_code == 200: self.addResourceCleanUp(self.client.DeleteSubnet, SubnetId=data['Subnet']['SubnetId']) self.assertEqual(400, resp.status_code) self.assertEqual('InvalidSubnet.Range', data['Error']['Code']) # NOTE(andrey-mp): bigger cidr than VPC has cidr = self.BASE_CIDR + '/19' resp, data = self.client.CreateSubnet(VpcId=self.vpc_id, CidrBlock=cidr) if resp.status_code == 200: self.addResourceCleanUp(self.client.DeleteSubnet, SubnetId=data['Subnet']['SubnetId']) self.assertEqual(400, resp.status_code) self.assertEqual('InvalidSubnet.Range', data['Error']['Code']) # NOTE(andrey-mp): too small cidr cidr = self.BASE_CIDR + '/29' resp, data = self.client.CreateSubnet(VpcId=self.vpc_id, CidrBlock=cidr) if resp.status_code == 200: self.addResourceCleanUp(self.client.DeleteSubnet, SubnetId=data['Subnet']['SubnetId']) self.assertEqual(400, resp.status_code) self.assertEqual('InvalidSubnet.Range', data['Error']['Code']) def test_describe_subnets_base(self): cidr = self.BASE_CIDR + '/24' resp, data = self.client.CreateSubnet(VpcId=self.vpc_id, CidrBlock=cidr) self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data)) subnet_id = data['Subnet']['SubnetId'] res_clean = self.addResourceCleanUp(self.client.DeleteSubnet, SubnetId=subnet_id) self.get_subnet_waiter().wait_available(subnet_id) # NOTE(andrey-mp): by real id resp, data = self.client.DescribeSubnets(SubnetIds=[subnet_id]) self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data)) self.assertEqual(1, len(data['Subnets'])) # NOTE(andrey-mp): by fake id resp, data = self.client.DescribeSubnets(SubnetIds=['subnet-0']) self.assertEqual(400, resp.status_code) self.assertEqual('InvalidSubnetID.NotFound', data['Error']['Code']) resp, data = self.client.DeleteSubnet(SubnetId=subnet_id) self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data)) self.cancelResourceCleanUp(res_clean) self.get_subnet_waiter().wait_delete(subnet_id) def test_describe_subnets_filters(self): cidr = self.BASE_CIDR + '/24' resp, data = self.client.CreateSubnet(VpcId=self.vpc_id, CidrBlock=cidr) self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data)) subnet_id = data['Subnet']['SubnetId'] res_clean = self.addResourceCleanUp(self.client.DeleteSubnet, SubnetId=subnet_id) self.get_subnet_waiter().wait_available(subnet_id) # NOTE(andrey-mp): by filter real cidr resp, data = self.client.DescribeSubnets( Filters=[{'Name': 'cidr', 'Values': [cidr]}]) self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data)) self.assertEqual(1, len(data['Subnets'])) # NOTE(andrey-mp): by filter fake cidr resp, data = self.client.DescribeSubnets( Filters=[{'Name': 'cidr', 'Values': ['123.0.0.0/16']}]) self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data)) self.assertEqual(0, len(data['Subnets'])) # NOTE(andrey-mp): by fake filter resp, data = self.client.DescribeSubnets( Filters=[{'Name': 'fake', 'Values': ['fake']}]) self.assertEqual(400, resp.status_code) self.assertEqual('InvalidParameterValue', data['Error']['Code']) resp, data = self.client.DeleteSubnet(SubnetId=subnet_id) self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data)) self.cancelResourceCleanUp(res_clean) self.get_subnet_waiter().wait_delete(subnet_id)
# Copyright 2013-2014 MongoDB, 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. """Tails the oplog of a shard and returns entries """ import bson import logging try: import Queue as queue except ImportError: import queue import pymongo import sys import time import threading import traceback from mongo_connector import errors, util from mongo_connector.constants import DEFAULT_BATCH_SIZE from mongo_connector.util import retry_until_ok from pymongo import MongoClient class OplogThread(threading.Thread): """OplogThread gathers the updates for a single oplog. """ def __init__(self, primary_conn, main_address, oplog_coll, is_sharded, doc_manager, oplog_progress_dict, namespace_set, auth_key, auth_username, repl_set=None, collection_dump=True, batch_size=DEFAULT_BATCH_SIZE, fields=None, dest_mapping={}, continue_on_error=False): """Initialize the oplog thread. """ super(OplogThread, self).__init__() self.batch_size = batch_size #The connection to the primary for this replicaSet. self.primary_connection = primary_conn #Boolean chooses whether to dump the entire collection if no timestamp # is present in the config file self.collection_dump = collection_dump #The mongos for sharded setups #Otherwise the same as primary_connection. #The value is set later on. self.main_connection = None #The connection to the oplog collection self.oplog = oplog_coll #Boolean describing whether the cluster is sharded or not self.is_sharded = is_sharded #A document manager for each target system. #These are the same for all threads. if type(doc_manager) == list: self.doc_managers = doc_manager else: self.doc_managers = [doc_manager] #Boolean describing whether or not the thread is running. self.running = True #Stores the timestamp of the last oplog entry read. self.checkpoint = None #A dictionary that stores OplogThread/timestamp pairs. #Represents the last checkpoint for a OplogThread. self.oplog_progress = oplog_progress_dict #The set of namespaces to process from the mongo cluster. self.namespace_set = namespace_set #The dict of source namespaces to destination namespaces self.dest_mapping = dest_mapping #Whether the collection dump gracefully handles exceptions self.continue_on_error = continue_on_error #If authentication is used, this is an admin password. self.auth_key = auth_key #This is the username used for authentication. self.auth_username = auth_username # Set of fields to export self.fields = fields logging.info('OplogThread: Initializing oplog thread') if is_sharded: self.main_connection = MongoClient(main_address) else: self.main_connection = MongoClient(main_address, replicaSet=repl_set) self.oplog = self.main_connection['local']['oplog.rs'] if auth_key is not None: #Authenticate for the whole system self.primary_connection['admin'].authenticate( auth_username, auth_key) self.main_connection['admin'].authenticate( auth_username, auth_key) if not self.oplog.find_one(): err_msg = 'OplogThread: No oplog for thread:' logging.warning('%s %s' % (err_msg, self.primary_connection)) @property def fields(self): return self._fields @fields.setter def fields(self, value): if value: self._fields = set(value) # Always include _id field self._fields.add('_id') else: self._fields = None def run(self): """Start the oplog worker. """ logging.debug("OplogThread: Run thread started") while self.running is True: logging.debug("OplogThread: Getting cursor") cursor, cursor_len = self.init_cursor() # we've fallen too far behind if cursor is None and self.checkpoint is not None: err_msg = "OplogThread: Last entry no longer in oplog" effect = "cannot recover!" logging.error('%s %s %s' % (err_msg, effect, self.oplog)) self.running = False continue if cursor_len == 0: logging.debug("OplogThread: Last entry is the one we " "already processed. Up to date. Sleeping.") time.sleep(1) continue logging.debug("OplogThread: Got the cursor, count is %d" % cursor_len) last_ts = None err = False remove_inc = 0 upsert_inc = 0 update_inc = 0 try: logging.debug("OplogThread: about to process new oplog " "entries") while cursor.alive and self.running: logging.debug("OplogThread: Cursor is still" " alive and thread is still running.") for n, entry in enumerate(cursor): logging.debug("OplogThread: Iterating through cursor," " document number in this cursor is %d" % n) # Break out if this thread should stop if not self.running: break # Don't replicate entries resulting from chunk moves if entry.get("fromMigrate"): continue # Take fields out of the oplog entry that # shouldn't be replicated. This may nullify # the document if there's nothing to do. if not self.filter_oplog_entry(entry): continue #sync the current oplog operation operation = entry['op'] ns = entry['ns'] if '.' not in ns: continue coll = ns.split('.', 1)[1] if coll.startswith("system."): continue # use namespace mapping if one exists ns = self.dest_mapping.get(entry['ns'], ns) for docman in self.doc_managers: try: logging.debug("OplogThread: Operation for this " "entry is %s" % str(operation)) # Remove if operation == 'd': entry['_id'] = entry['o']['_id'] entry['ns'] = ns entry['_ts'] = util.bson_ts_to_long( entry['ts']) docman.remove(entry) remove_inc += 1 # Insert elif operation == 'i': # Insert # Retrieve inserted document from # 'o' field in oplog record doc = entry.get('o') # Extract timestamp and namespace doc['_ts'] = util.bson_ts_to_long( entry['ts']) doc['ns'] = ns docman.upsert(doc) upsert_inc += 1 # Update elif operation == 'u': doc = {"_id": entry['o2']['_id'], "_ts": util.bson_ts_to_long( entry['ts']), "ns": ns} # 'o' field contains the update spec docman.update(doc, entry.get('o', {})) update_inc += 1 except errors.OperationFailed: logging.exception( "Unable to process oplog document %r" % entry) except errors.ConnectionFailed: logging.exception( "Connection failed while processing oplog " "document %r" % entry) if (remove_inc + upsert_inc + update_inc) % 1000 == 0: logging.debug( "OplogThread: Documents removed: %d, " "inserted: %d, updated: %d so far" % ( remove_inc, upsert_inc, update_inc)) logging.debug("OplogThread: Doc is processed.") last_ts = entry['ts'] # update timestamp per batch size # n % -1 (default for self.batch_size) == 0 for all n if n % self.batch_size == 1 and last_ts is not None: self.checkpoint = last_ts self.update_checkpoint() # update timestamp after running through oplog if last_ts is not None: logging.debug("OplogThread: updating checkpoint after" "processing new oplog entries") self.checkpoint = last_ts self.update_checkpoint() except (pymongo.errors.AutoReconnect, pymongo.errors.OperationFailure, pymongo.errors.ConfigurationError): logging.exception( "Cursor closed due to an exception. " "Will attempt to reconnect.") err = True if err is True and self.auth_key is not None: self.primary_connection['admin'].authenticate( self.auth_username, self.auth_key) self.main_connection['admin'].authenticate( self.auth_username, self.auth_key) err = False # update timestamp before attempting to reconnect to MongoDB, # after being join()'ed, or if the cursor closes if last_ts is not None: logging.debug("OplogThread: updating checkpoint after an " "Exception, cursor closing, or join() on this" "thread.") self.checkpoint = last_ts self.update_checkpoint() logging.debug("OplogThread: Sleeping. Documents removed: %d, " "upserted: %d, updated: %d" % (remove_inc, upsert_inc, update_inc)) time.sleep(2) def join(self): """Stop this thread from managing the oplog. """ logging.debug("OplogThread: exiting due to join call.") self.running = False threading.Thread.join(self) def filter_oplog_entry(self, entry): """Remove fields from an oplog entry that should not be replicated.""" if not self._fields: return entry def pop_excluded_fields(doc): for key in set(doc) - self._fields: doc.pop(key) # 'i' indicates an insert. 'o' field is the doc to be inserted. if entry['op'] == 'i': pop_excluded_fields(entry['o']) # 'u' indicates an update. 'o' field is the update spec. elif entry['op'] == 'u': pop_excluded_fields(entry['o'].get("$set", {})) pop_excluded_fields(entry['o'].get("$unset", {})) # not allowed to have empty $set/$unset, so remove if empty if "$set" in entry['o'] and not entry['o']['$set']: entry['o'].pop("$set") if "$unset" in entry['o'] and not entry['o']['$unset']: entry['o'].pop("$unset") if not entry['o']: return None return entry def get_namespace_regex(self): first_namespace = True namespace_regex = "^(" for namespace_candidate in self.namespace_set: if not first_namespace: namespace_regex += "|" if "." in namespace_candidate: namespace_regex += namespace_candidate else: namespace_regex += namespace_candidate + "\\..+" first_namespace = False namespace_regex += ")" logging.debug("OplogThread: Namespace regex: " + namespace_regex) return namespace_regex def get_oplog_cursor(self, timestamp=None): """Get a cursor to the oplog after the given timestamp, filtering entries not in the namespace set. If no timestamp is specified, returns a cursor to the entire oplog. """ query = {} if self.namespace_set: query['ns'] = {'$regex': self.get_namespace_regex()} if timestamp is None: cursor = self.oplog.find( query, tailable=True, await_data=True) else: query['ts'] = {'$gte': timestamp} cursor = self.oplog.find( query, tailable=True, await_data=True) # Applying 8 as the mask to the cursor enables OplogReplay cursor.add_option(8) return cursor def dump_collection(self): """Dumps collection into the target system. This method is called when we're initializing the cursor and have no configs i.e. when we're starting for the first time. """ dump_set = [] db_list = retry_until_ok(self.main_connection.database_names) for database in db_list: if database == "config" or database == "local": continue if self.namespace_set: found_matching_database_name = False for namespace_candidate in self.namespace_set: if "." in namespace_candidate: continue if namespace_candidate == database: found_matching_database_name = True break if not found_matching_database_name: continue coll_list = retry_until_ok( self.main_connection[database].collection_names) for coll in coll_list: if coll.startswith("system"): continue namespace = "%s.%s" % (database, coll) dump_set.append(namespace) if self.namespace_set: for namespace_candidate in self.namespace_set: if "." in namespace_candidate: dump_set.append(namespace_candidate) logging.debug("OplogThread: Dumping set of collections %s " % dump_set) timestamp = util.retry_until_ok(self.get_last_oplog_timestamp) logging.debug("OplogThread: get_last_oplog_timestamp: " + str(timestamp)) if timestamp is None: return None long_ts = util.bson_ts_to_long(timestamp) def docs_to_dump(): for namespace in dump_set: logging.info("OplogThread: dumping collection %s" % namespace) database, coll = namespace.split('.', 1) last_id = None attempts = 0 # Loop to handle possible AutoReconnect while attempts < 60: target_coll = self.main_connection[database][coll] if not last_id: cursor = util.retry_until_ok( target_coll.find, fields=self._fields, sort=[("_id", pymongo.ASCENDING)] ) else: cursor = util.retry_until_ok( target_coll.find, {"_id": {"$gt": last_id}}, fields=self._fields, sort=[("_id", pymongo.ASCENDING)] ) try: for doc in cursor: if not self.running: raise StopIteration doc["ns"] = self.dest_mapping.get( namespace, namespace) doc["_ts"] = long_ts last_id = doc["_id"] yield doc break except pymongo.errors.AutoReconnect: attempts += 1 time.sleep(1) def upsert_each(dm): num_inserted = 0 num_failed = 0 for num, doc in enumerate(docs_to_dump()): if num % 10000 == 0: logging.debug("Upserted %d docs." % num) try: dm.upsert(doc) num_inserted += 1 except Exception: if self.continue_on_error: logging.exception( "Could not upsert document: %r" % doc) num_failed += 1 else: raise logging.debug("Upserted %d docs" % num_inserted) if num_failed > 0: logging.error("Failed to upsert %d docs" % num_failed) def upsert_all(dm): try: dm.bulk_upsert(docs_to_dump()) except Exception as e: if self.continue_on_error: logging.exception("OplogThread: caught exception" " during bulk upsert, re-upserting" " documents serially") upsert_each(dm) else: raise def do_dump(dm, error_queue): try: # Bulk upsert if possible if hasattr(dm, "bulk_upsert"): logging.debug("OplogThread: Using bulk upsert function for " "collection dump") upsert_all(dm) else: logging.debug( "OplogThread: DocManager %s has no " "bulk_upsert method. Upserting documents " "serially for collection dump." % str(dm)) upsert_each(dm) except: # Likely exceptions: # pymongo.errors.OperationFailure, # mongo_connector.errors.ConnectionFailed # mongo_connector.errors.OperationFailed error_queue.put(sys.exc_info()) # Extra threads (if any) that assist with collection dumps dumping_threads = [] # Did the dump succeed for all target systems? dump_success = True # Holds any exceptions we can't recover from errors = queue.Queue() if len(self.doc_managers) == 1: do_dump(self.doc_managers[0], errors) else: # Slight performance gain breaking dump into separate # threads if > 1 replication target for dm in self.doc_managers: t = threading.Thread(target=do_dump, args=(dm, errors)) dumping_threads.append(t) t.start() # cleanup for t in dumping_threads: t.join() # Print caught exceptions try: while True: klass, value, trace = errors.get_nowait() dump_success = False traceback.print_exception(klass, value, trace) except queue.Empty: pass if not dump_success: err_msg = "OplogThread: Failed during dump collection" effect = "cannot recover!" logging.error('%s %s %s' % (err_msg, effect, self.oplog)) self.running = False return None return timestamp def get_last_oplog_timestamp(self): """Return the timestamp of the latest entry in the oplog. """ if not self.namespace_set: curr = self.oplog.find().sort( '$natural', pymongo.DESCENDING ).limit(1) else: curr = self.oplog.find( {'ns': {'$regex': self.get_namespace_regex()}} ).sort('$natural', pymongo.DESCENDING).limit(1) if curr.count(with_limit_and_skip=True) == 0: return None logging.debug("OplogThread: Last oplog entry has timestamp %d." % curr[0]['ts'].time) return curr[0]['ts'] def init_cursor(self): """Position the cursor appropriately. The cursor is set to either the beginning of the oplog, or wherever it was last left off. Returns the cursor and the number of documents left in the cursor. """ timestamp = self.read_last_checkpoint() if timestamp is None: if self.collection_dump: # dump collection and update checkpoint timestamp = self.dump_collection() if timestamp is None: return None, 0 else: # Collection dump disabled: # return cursor to beginning of oplog. cursor = self.get_oplog_cursor() self.checkpoint = self.get_last_oplog_timestamp() self.update_checkpoint() return cursor, retry_until_ok(cursor.count) self.checkpoint = timestamp self.update_checkpoint() for i in range(60): cursor = self.get_oplog_cursor(timestamp) cursor_len = retry_until_ok(cursor.count) if cursor_len == 0: # rollback, update checkpoint, and retry logging.debug("OplogThread: Initiating rollback from " "get_oplog_cursor") self.checkpoint = self.rollback() self.update_checkpoint() return self.init_cursor() # try to get the first oplog entry try: first_oplog_entry = next(cursor) except StopIteration: # It's possible for the cursor to become invalid # between the cursor.count() call and now time.sleep(1) continue # first entry should be last oplog entry processed cursor_ts_long = util.bson_ts_to_long( first_oplog_entry.get("ts")) given_ts_long = util.bson_ts_to_long(timestamp) if cursor_ts_long > given_ts_long: # first entry in oplog is beyond timestamp # we've fallen behind return None, 0 # first entry has been consumed return cursor, cursor_len - 1 else: raise errors.MongoConnectorError( "Could not initialize oplog cursor.") def update_checkpoint(self): """Store the current checkpoint in the oplog progress dictionary. """ with self.oplog_progress as oplog_prog: oplog_dict = oplog_prog.get_dict() oplog_dict[str(self.oplog)] = self.checkpoint logging.debug("OplogThread: oplog checkpoint updated to %s" % str(self.checkpoint)) def read_last_checkpoint(self): """Read the last checkpoint from the oplog progress dictionary. """ oplog_str = str(self.oplog) ret_val = None with self.oplog_progress as oplog_prog: oplog_dict = oplog_prog.get_dict() if oplog_str in oplog_dict.keys(): ret_val = oplog_dict[oplog_str] logging.debug("OplogThread: reading last checkpoint as %s " % str(ret_val)) return ret_val def rollback(self): """Rollback target system to consistent state. The strategy is to find the latest timestamp in the target system and the largest timestamp in the oplog less than the latest target system timestamp. This defines the rollback window and we just roll these back until the oplog and target system are in consistent states. """ # Find the most recently inserted document in each target system logging.debug("OplogThread: Initiating rollback sequence to bring " "system into a consistent state.") last_docs = [] for dm in self.doc_managers: dm.commit() last_docs.append(dm.get_last_doc()) # Of these documents, which is the most recent? last_inserted_doc = max(last_docs, key=lambda x: x["_ts"] if x else float("-inf")) # Nothing has been replicated. No need to rollback target systems if last_inserted_doc is None: return None # Find the oplog entry that touched the most recent document. # We'll use this to figure where to pick up the oplog later. target_ts = util.long_to_bson_ts(last_inserted_doc['_ts']) last_oplog_entry = util.retry_until_ok( self.oplog.find_one, {'ts': {'$lte': target_ts}}, sort=[('$natural', pymongo.DESCENDING)] ) logging.debug("OplogThread: last oplog entry is %s" % str(last_oplog_entry)) # The oplog entry for the most recent document doesn't exist anymore. # If we've fallen behind in the oplog, this will be caught later if last_oplog_entry is None: return None # rollback_cutoff_ts happened *before* the rollback rollback_cutoff_ts = last_oplog_entry['ts'] start_ts = util.bson_ts_to_long(rollback_cutoff_ts) # timestamp of the most recent document on any target system end_ts = last_inserted_doc['_ts'] for dm in self.doc_managers: rollback_set = {} # this is a dictionary of ns:list of docs # group potentially conflicted documents by namespace for doc in dm.search(start_ts, end_ts): if doc['ns'] in rollback_set: rollback_set[doc['ns']].append(doc) else: rollback_set[doc['ns']] = [doc] # retrieve these documents from MongoDB, either updating # or removing them in each target system for namespace, doc_list in rollback_set.items(): # Get the original namespace original_namespace = namespace for source_name, dest_name in self.dest_mapping.items(): if dest_name == namespace: original_namespace = source_name database, coll = original_namespace.split('.', 1) obj_id = bson.objectid.ObjectId bson_obj_id_list = [obj_id(doc['_id']) for doc in doc_list] to_update = util.retry_until_ok( self.main_connection[database][coll].find, {'_id': {'$in': bson_obj_id_list}}, fields=self._fields ) #doc list are docs in target system, to_update are #docs in mongo doc_hash = {} # hash by _id for doc in doc_list: doc_hash[bson.objectid.ObjectId(doc['_id'])] = doc to_index = [] def collect_existing_docs(): for doc in to_update: if doc['_id'] in doc_hash: del doc_hash[doc['_id']] to_index.append(doc) retry_until_ok(collect_existing_docs) #delete the inconsistent documents logging.debug("OplogThread: Rollback, removing inconsistent " "docs.") remov_inc = 0 for doc in doc_hash.values(): try: dm.remove(doc) remov_inc += 1 logging.debug("OplogThread: Rollback, removed %s " % str(doc)) except errors.OperationFailed: logging.warning( "Could not delete document during rollback: %s " "This can happen if this document was already " "removed by another rollback happening at the " "same time." % str(doc) ) logging.debug("OplogThread: Rollback, removed %d docs." % remov_inc) #insert the ones from mongo logging.debug("OplogThread: Rollback, inserting documents " "from mongo.") insert_inc = 0 fail_insert_inc = 0 for doc in to_index: doc['_ts'] = util.bson_ts_to_long(rollback_cutoff_ts) doc['ns'] = self.dest_mapping.get(namespace, namespace) try: insert_inc += 1 dm.upsert(doc) except errors.OperationFailed as e: fail_insert_inc += 1 logging.error("OplogThread: Rollback, Unable to " "insert %s with exception %s" % (doc, str(e))) logging.debug("OplogThread: Rollback, Successfully inserted %d " " documents and failed to insert %d" " documents. Returning a rollback cutoff time of %s " % (insert_inc, fail_insert_inc, str(rollback_cutoff_ts))) return rollback_cutoff_ts
#!/usr/bin/python # # Copyright (C) 2007 SIOS Technology, 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. """Contains objects used with Google Apps.""" __author__ = 'tmatsuo@sios.com (Takashi MATSUO)' try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: from elementtree import ElementTree import atom import gdata # XML namespaces which are often used in Google Apps entity. APPS_NAMESPACE = 'http://schemas.google.com/apps/2006' APPS_TEMPLATE = '{http://schemas.google.com/apps/2006}%s' class EmailList(atom.AtomBase): """The Google Apps EmailList element""" _tag = 'emailList' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['name'] = 'name' def __init__(self, name=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def EmailListFromString(xml_string): return atom.CreateClassFromXMLString(EmailList, xml_string) class Who(atom.AtomBase): """The Google Apps Who element""" _tag = 'who' _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['rel'] = 'rel' _attributes['email'] = 'email' def __init__(self, rel=None, email=None, extension_elements=None, extension_attributes=None, text=None): self.rel = rel self.email = email self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def WhoFromString(xml_string): return atom.CreateClassFromXMLString(Who, xml_string) class Login(atom.AtomBase): """The Google Apps Login element""" _tag = 'login' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['userName'] = 'user_name' _attributes['password'] = 'password' _attributes['suspended'] = 'suspended' _attributes['ipWhitelisted'] = 'ip_whitelisted' _attributes['hashFunctionName'] = 'hash_function_name' def __init__(self, user_name=None, password=None, suspended=None, ip_whitelisted=None, hash_function_name=None, extension_elements=None, extension_attributes=None, text=None): self.user_name = user_name self.password = password self.suspended = suspended self.ip_whitelisted = ip_whitelisted self.hash_function_name = hash_function_name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def LoginFromString(xml_string): return atom.CreateClassFromXMLString(Login, xml_string) class Quota(atom.AtomBase): """The Google Apps Quota element""" _tag = 'quota' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['limit'] = 'limit' def __init__(self, limit=None, extension_elements=None, extension_attributes=None, text=None): self.limit = limit self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def QuotaFromString(xml_string): return atom.CreateClassFromXMLString(Quota, xml_string) class Name(atom.AtomBase): """The Google Apps Name element""" _tag = 'name' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['familyName'] = 'family_name' _attributes['givenName'] = 'given_name' def __init__(self, family_name=None, given_name=None, extension_elements=None, extension_attributes=None, text=None): self.family_name = family_name self.given_name = given_name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def NameFromString(xml_string): return atom.CreateClassFromXMLString(Name, xml_string) class Nickname(atom.AtomBase): """The Google Apps Nickname element""" _tag = 'nickname' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['name'] = 'name' def __init__(self, name=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def NicknameFromString(xml_string): return atom.CreateClassFromXMLString(Nickname, xml_string) class NicknameEntry(gdata.GDataEntry): """A Google Apps flavor of an Atom Entry for Nickname""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}login' % APPS_NAMESPACE] = ('login', Login) _children['{%s}nickname' % APPS_NAMESPACE] = ('nickname', Nickname) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, login=None, nickname=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated) self.login = login self.nickname = nickname self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def NicknameEntryFromString(xml_string): return atom.CreateClassFromXMLString(NicknameEntry, xml_string) class NicknameFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Apps Nickname feed flavor of an Atom Feed""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [NicknameEntry]) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def NicknameFeedFromString(xml_string): return atom.CreateClassFromXMLString(NicknameFeed, xml_string) class UserEntry(gdata.GDataEntry): """A Google Apps flavor of an Atom Entry""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}login' % APPS_NAMESPACE] = ('login', Login) _children['{%s}name' % APPS_NAMESPACE] = ('name', Name) _children['{%s}quota' % APPS_NAMESPACE] = ('quota', Quota) # This child may already be defined in GDataEntry, confirm before removing. _children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link', [gdata.FeedLink]) _children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', Who) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, login=None, name=None, quota=None, who=None, feed_link=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated) self.login = login self.name = name self.quota = quota self.who = who self.feed_link = feed_link or [] self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def UserEntryFromString(xml_string): return atom.CreateClassFromXMLString(UserEntry, xml_string) class UserFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Apps User feed flavor of an Atom Feed""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [UserEntry]) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def UserFeedFromString(xml_string): return atom.CreateClassFromXMLString(UserFeed, xml_string) class EmailListEntry(gdata.GDataEntry): """A Google Apps EmailList flavor of an Atom Entry""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}emailList' % APPS_NAMESPACE] = ('email_list', EmailList) # Might be able to remove this _children entry. _children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link', [gdata.FeedLink]) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, email_list=None, feed_link=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated) self.email_list = email_list self.feed_link = feed_link or [] self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def EmailListEntryFromString(xml_string): return atom.CreateClassFromXMLString(EmailListEntry, xml_string) class EmailListFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Apps EmailList feed flavor of an Atom Feed""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [EmailListEntry]) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def EmailListFeedFromString(xml_string): return atom.CreateClassFromXMLString(EmailListFeed, xml_string) class EmailListRecipientEntry(gdata.GDataEntry): """A Google Apps EmailListRecipient flavor of an Atom Entry""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', Who) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, who=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated) self.who = who self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def EmailListRecipientEntryFromString(xml_string): return atom.CreateClassFromXMLString(EmailListRecipientEntry, xml_string) class EmailListRecipientFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Apps EmailListRecipient feed flavor of an Atom Feed""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [EmailListRecipientEntry]) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def EmailListRecipientFeedFromString(xml_string): return atom.CreateClassFromXMLString(EmailListRecipientFeed, xml_string)
""" Sysconfig - files in ``/etc/sysconfig/`` ======================================== This is a collection of parsers that all deal with the system's configuration files under the ``/etc/sysconfig/`` folder. Parsers included in this module are: CorosyncSysconfig - file ``/etc/sysconfig/corosync`` ---------------------------------------------------- ChronydSysconfig - file ``/etc/sysconfig/chronyd`` -------------------------------------------------- DirsrvSysconfig - file ``/etc/sysconfig/dirsrv`` ------------------------------------------------ DockerStorageSetupSysconfig - file ``/etc/sysconfig/docker-storage-setup`` -------------------------------------------------------------------------- DockerSysconfig - file ``/etc/sysconfig/docker`` ------------------------------------------------ DockerSysconfigStorage - file ``/etc/sysconfig/docker-storage`` --------------------------------------------------------------- ForemanTasksSysconfig - file ``/etc/sysconfig/foreman-tasks`` ------------------------------------------------------------- HttpdSysconfig - file ``/etc/sysconfig/httpd`` ---------------------------------------------- IrqbalanceSysconfig - file ``/etc/sysconfig/irqbalance`` -------------------------------------------------------- KdumpSysconfig - file ``/etc/sysconfig/kdump`` ---------------------------------------------- LibvirtGuestsSysconfig - file ``/etc/sysconfig/libvirt-guests`` --------------------------------------------------------------- MemcachedSysconfig - file ``/etc/sysconfig/memcached`` ------------------------------------------------------ MongodSysconfig - file ``/etc/sysconfig/mongod`` ------------------------------------------------ NetconsoleSysconfig -file ``/etc/sysconfig/netconsole`` ------------------------------------------------------- NetworkSysconfig -file ``/etc/sysconfig/network`` ------------------------------------------------- NtpdSysconfig - file ``/etc/sysconfig/ntpd`` -------------------------------------------- PrelinkSysconfig - file ``/etc/sysconfig/prelink`` -------------------------------------------------- SshdSysconfig - file ``/etc/sysconfig/sshd`` -------------------------------------------- PuppetserverSysconfig - file ``/etc/sysconfig/puppetserver`` ------------------------------------------------------------ Up2DateSysconfig - file ``/etc/sysconfig/rhn/up2date`` ------------------------------------------------------ VirtWhoSysconfig - file ``/etc/sysconfig/virt-who`` --------------------------------------------------- IfCFGStaticRoute - files ``/etc/sysconfig/network-scripts/route-*`` ------------------------------------------------------------------- GrubSysconfig - files ``/etc/sysconfig/grub`` --------------------------------------------- OracleasmSysconfig - files ``/etc/sysconfig/oracleasm`` ------------------------------------------------------- """ from insights import parser, SysconfigOptions, get_active_lines from insights.specs import Specs @parser(Specs.corosync) class CorosyncSysconfig(SysconfigOptions): """ This parser reads the ``/etc/sysconfig/corosync`` file. It uses the ``SysconfigOptions`` parser class to convert the file into a dictionary of options. It also provides the ``options`` property as a helper to retrieve the ``COROSYNC_OPTIONS`` variable. Sample Input:: # COROSYNC_INIT_TIMEOUT specifies number of seconds to wait for corosync # initialization (default is one minute). COROSYNC_INIT_TIMEOUT=60 # COROSYNC_OPTIONS specifies options passed to corosync command # (default is no options). # See "man corosync" for detailed descriptions of the options. COROSYNC_OPTIONS="" Examples: >>> 'COROSYNC_OPTIONS' in cs_syscfg True >>> cs_syscfg.options '' """ @property def options(self): """ (str): The value of the ``COROSYNC_OPTIONS`` variable.""" return self.data.get('COROSYNC_OPTIONS', '') @parser(Specs.sysconfig_chronyd) class ChronydSysconfig(SysconfigOptions): """ This parser analyzes the ``/etc/sysconfig/chronyd`` configuration file. Sample Input:: OPTIONS="-d" #HIDE="me" Examples: >>> 'OPTIONS' in chronyd_syscfg True >>> 'HIDE' in chronyd_syscfg False >>> chronyd_syscfg['OPTIONS'] '-d' """ pass @parser(Specs.dirsrv) class DirsrvSysconfig(SysconfigOptions): """ This parser parses the `dirsrv` service's start-up configuration ``/etc/sysconfig/dirsrv``. Sample Input:: #STARTPID_TIME=10 ; export STARTPID_TIME #PID_TIME=600 ; export PID_TIME KRB5CCNAME=/tmp/krb5cc_995 KRB5_KTNAME=/etc/dirsrv/ds.keytab Examples: >>> dirsrv_syscfg.get('KRB5_KTNAME') '/etc/dirsrv/ds.keytab' >>> 'PID_TIME' in dirsrv_syscfg False """ pass @parser(Specs.docker_storage_setup) class DockerStorageSetupSysconfig(SysconfigOptions): """ Parser for parsing ``/etc/sysconfig/docker-storage-setup`` Sample Input:: VG=vgtest AUTO_EXTEND_POOL=yes ##name = mydomain POOL_AUTOEXTEND_THRESHOLD=60 POOL_AUTOEXTEND_PERCENT=20 Examples: >>> dss_syscfg['VG'] # Pseudo-dict access 'vgtest' >>> 'name' in dss_syscfg False >>> dss_syscfg.get('POOL_AUTOEXTEND_THRESHOLD') '60' """ pass @parser(Specs.docker_sysconfig) class DockerSysconfig(SysconfigOptions): """ Parser for parsing the ``/etc/sysconfig/docker`` file using the standard ``SysconfigOptions`` parser class. The 'OPTIONS' variable is also provided in the ``options`` property as a convenience. Sample Input:: OPTIONS="--selinux-enabled" DOCKER_CERT_PATH="/etc/docker" Examples: >>> 'OPTIONS' in docker_syscfg True >>> docker_syscfg['OPTIONS'] '--selinux-enabled' >>> docker_syscfg.options '--selinux-enabled' >>> docker_syscfg['DOCKER_CERT_PATH'] '/etc/docker' """ @property def options(self): """ Return the value of the 'OPTIONS' variable, or '' if not defined. """ return self.data.get('OPTIONS', '') @parser(Specs.docker_storage) class DockerSysconfigStorage(SysconfigOptions): """ A Parser for /etc/sysconfig/docker-storage. Sample input:: DOCKER_STORAGE_OPTIONS="--storage-driver devicemapper --storage-opt dm.fs=xfs --storage-opt dm.thinpooldev=/dev/mapper/dockervg-docker--pool --storage-opt dm.use_deferred_removal=true --storage-opt dm.use_deferred_deletion=true" Examples: >>> 'DOCKER_STORAGE_OPTIONS' in docker_syscfg_storage True >>> docker_syscfg_storage["DOCKER_STORAGE_OPTIONS"] '--storage-driver devicemapper --storage-opt dm.fs=xfs --storage-opt dm.thinpooldev=/dev/mapper/dockervg-docker--pool --storage-opt dm.use_deferred_removal=true --storage-opt dm.use_deferred_deletion=true' >>> docker_syscfg_storage.storage_options '--storage-driver devicemapper --storage-opt dm.fs=xfs --storage-opt dm.thinpooldev=/dev/mapper/dockervg-docker--pool --storage-opt dm.use_deferred_removal=true --storage-opt dm.use_deferred_deletion=true' """ @property def storage_options(self): """ Return the value of the 'DOCKER_STORAGE_OPTIONS' variable, or '' if not defined. """ return self.data.get('DOCKER_STORAGE_OPTIONS', '') @parser(Specs.foreman_tasks_config) class ForemanTasksSysconfig(SysconfigOptions): """ Parse the ``/etc/sysconfig/foreman-tasks`` configuration file. Sample configuration file:: FOREMAN_USER=foreman BUNDLER_EXT_HOME=/usr/share/foreman RAILS_ENV=production FOREMAN_LOGGING=warn Examples: >>> ft_syscfg['RAILS_ENV'] 'production' >>> 'AUTO' in ft_syscfg False """ pass @parser(Specs.sysconfig_httpd) class HttpdSysconfig(SysconfigOptions): """ This parser analyzes the ``/etc/sysconfig/httpd`` configuration file. Sample Input:: HTTPD=/usr/sbin/httpd.worker # # To pass additional options (for instance, -D definitions) to the # httpd binary at startup, set OPTIONS here. # OPTIONS= Examples: >>> httpd_syscfg['HTTPD'] '/usr/sbin/httpd.worker' >>> httpd_syscfg.get('OPTIONS') '' >>> 'NOOP' in httpd_syscfg False """ pass @parser(Specs.sysconfig_irqbalance) class IrqbalanceSysconfig(SysconfigOptions): """ This parser analyzes the ``/etc/sysconfig/irqbalance`` configuration file. Sample Input:: #IRQBALANCE_ONESHOT=yes # IRQBALANCE_BANNED_CPUS=f8 IRQBALANCE_ARGS="-d" Examples: >>> irqb_syscfg['IRQBALANCE_BANNED_CPUS'] 'f8' >>> irqb_syscfg.get('IRQBALANCE_ARGS') # quotes will be stripped '-d' >>> irqb_syscfg.get('IRQBALANCE_ONESHOT') is None True >>> 'ONESHOT' in irqb_syscfg False """ pass @parser(Specs.sysconfig_kdump) class KdumpSysconfig(SysconfigOptions): """ This parser reads data from the ``/etc/sysconfig/kdump`` file. This parser sets the following properties for ease of access: * KDUMP_COMMANDLINE * KDUMP_COMMANDLINE_REMOVE * KDUMP_COMMANDLINE_APPEND * KDUMP_KERNELVER * KDUMP_IMG * KDUMP_IMG_EXT * KEXEC_ARGS These are set to the value of the named variable in the kdump sysconfig file, or '' if not found. """ KDUMP_KEYS = [ 'KDUMP_COMMANDLINE', 'KDUMP_COMMANDLINE_REMOVE', 'KDUMP_COMMANDLINE_APPEND', 'KDUMP_KERNELVER', 'KDUMP_IMG', 'KDUMP_IMG_EXT', 'KEXEC_ARGS', ] def parse_content(self, content): super(KdumpSysconfig, self).parse_content(content) for key in self.KDUMP_KEYS: setattr(self, key, self.data.get(key, '')) @parser(Specs.sysconfig_libvirt_guests) class LibvirtGuestsSysconfig(SysconfigOptions): """ This parser analyzes the ``/etc/sysconfig/libvirt-guests`` configuration file. Sample Input:: # URIs to check for running guests # example: URIS='default xen:/// vbox+tcp://host/system lxc:///' #URIS=default ON_BOOT=ignore Examples: >>> libvirt_guests_syscfg.get('ON_BOOT') 'ignore' """ pass @parser(Specs.sysconfig_memcached) class MemcachedSysconfig(SysconfigOptions): """ This parser analyzes the ``/etc/sysconfig/memcached`` configuration file. Sample Input:: PORT="11211" USER="memcached" # max connection 2048 MAXCONN="2048" # set ram size to 2048 - 2GiB CACHESIZE="4096" # disable UDP and listen to loopback ip 127.0.0.1, for network connection use real ip e.g., 10.0.0.5 OPTIONS="-U 0 -l 127.0.0.1" Examples: >>> memcached_syscfg.get('OPTIONS') '-U 0 -l 127.0.0.1' """ pass @parser(Specs.sysconfig_mongod) class MongodSysconfig(SysconfigOptions): """ A parser for analyzing the ``mongod`` service configuration file, like '/etc/sysconfig/mongod' and '/etc/opt/rh/rh-mongodb26/sysconfig/mongod'. Sample Input:: OPTIONS="--quiet -f /etc/mongod.conf" Examples: >>> mongod_syscfg.get('OPTIONS') '--quiet -f /etc/mongod.conf' >>> mongod_syscfg.get('NO_SUCH_OPTION') is None True >>> 'NOSUCHOPTION' in mongod_syscfg False """ pass @parser(Specs.netconsole) class NetconsoleSysconfig(SysconfigOptions): ''' Parse the ``/etc/sysconfig/netconsole`` file. Sample Input:: # The local port number that the netconsole module will use LOCALPORT=6666 Examples: >>> 'LOCALPORT' in netcs_syscfg True >>> 'DEV' in netcs_syscfg False ''' pass @parser(Specs.sysconfig_network) class NetworkSysconfig(SysconfigOptions): """ This parser parses the ``/etc/sysconfig/network`` configuration file Sample Input:: NETWORKING=yes HOSTNAME=rhel7-box GATEWAY=172.31.0.1 NM_BOND_VLAN_ENABLED=no Examples: >>> 'NETWORKING' in net_syscfg True >>> net_syscfg['GATEWAY'] '172.31.0.1' """ pass @parser(Specs.sysconfig_ntpd) class NtpdSysconfig(SysconfigOptions): """ A parser for analyzing the ``/etc/sysconfig/ntpd`` configuration file. Sample Input:: OPTIONS="-x -g" #HIDE="me" Examples: >>> 'OPTIONS' in ntpd_syscfg True >>> 'HIDE' in ntpd_syscfg False >>> ntpd_syscfg['OPTIONS'] '-x -g' """ pass @parser(Specs.sysconfig_prelink) class PrelinkSysconfig(SysconfigOptions): """ A parser for analyzing the ``/etc/sysconfig/prelink`` configuration file. Sample Input:: # Set this to no to disable prelinking altogether # (if you change this from yes to no prelink -ua # will be run next night to undo prelinking) PRELINKING=no # Options to pass to prelink # -m Try to conserve virtual memory by allowing overlapping # assigned virtual memory slots for libraries which # never appear together in one binary # -R Randomize virtual memory slot assignments for libraries. # This makes it slightly harder for various buffer overflow # attacks, since library addresses will be different on each # host using -R. PRELINK_OPTS=-mR Examples: >>> prelink_syscfg.get('PRELINKING') 'no' """ pass @parser(Specs.sysconfig_sshd) class SshdSysconfig(SysconfigOptions): """ A parser for analyzing the ``/etc/sysconfig/sshd`` configuration file. Sample Input:: # Configuration file for the sshd service. # The server keys are automatically generated if they are missing. # To change the automatic creation, adjust sshd.service options for # example using systemctl enable sshd-keygen@dsa.service to allow creation # of DSA key or systemctl mask sshd-keygen@rsa.service to disable RSA key # creation. # System-wide crypto policy: # To opt-out, uncomment the following line # CRYPTO_POLICY= CRYPTO_POLICY= Examples: >>> sshd_syscfg.get('CRYPTO_POLICY') '' >>> 'NONEXISTENT_VAR' in sshd_syscfg False >>> 'CRYPTO_POLICY' in sshd_syscfg True """ pass @parser(Specs.puppetserver_config) class PuppetserverSysconfig(SysconfigOptions): """ Parse the ``/etc/sysconfig/puppetserver`` configuration file. Sample configuration file:: USER="puppet" GROUP="puppet" INSTALL_DIR="/opt/puppetlabs/server/apps/puppetserver" CONFIG="/etc/puppetlabs/puppetserver/conf.d" START_TIMEOUT=300 Examples: >>> pps_syscfg['START_TIMEOUT'] '300' >>> 'AUTO' in pps_syscfg False """ pass @parser(Specs.up2date) class Up2DateSysconfig(SysconfigOptions): """ Class to parse the ``/etc/sysconfig/rhn/up2date`` Typical content example:: serverURL[comment]=Remote server URL #serverURL=https://rhnproxy.glb.tech.markit.partners serverURL=https://rhnproxy.glb.tech.markit.partners/XMLRPC Examples: >>> 'serverURL' in u2d_syscfg True >>> u2d_syscfg['serverURL'] 'https://rhnproxy.glb.tech.markit.partners/XMLRPC' """ def parse_content(self, content): up2date_info = {} for line in get_active_lines(content): if "[comment]" not in line and '=' in line: key, val = line.split('=') up2date_info[key.strip()] = val.strip() self.data = up2date_info @parser(Specs.sysconfig_virt_who) class VirtWhoSysconfig(SysconfigOptions): """ A parser for analyzing the ``/etc/sysconfig/virt-who`` configuration file. Sample Input:: # Register ESX machines using vCenter # VIRTWHO_ESX=0 # Register guests using RHEV-M VIRTWHO_RHEVM=1 # Options for RHEV-M mode VIRTWHO_RHEVM_OWNER= TEST_OPT="A TEST" Examples: >>> vwho_syscfg['VIRTWHO_RHEVM'] '1' >>> vwho_syscfg.get('VIRTWHO_RHEVM_OWNER') '' >>> vwho_syscfg.get('NO_SUCH_OPTION') is None True >>> 'NOSUCHOPTION' in vwho_syscfg False >>> vwho_syscfg.get('TEST_OPT') # Quotes are stripped 'A TEST' """ pass @parser(Specs.ifcfg_static_route) class IfCFGStaticRoute(SysconfigOptions): """ IfCFGStaticRoute is a parser for the static route network interface definition files in ``/etc/sysconfig/network-scripts``. These are pulled into the network scripts using ``source``, so they are mainly ``bash`` environment declarations of the form **KEY=value**. These are stored in the ``data`` property as a dictionary. Quotes surrounding the value Because this parser reads multiple files, the interfaces are stored as a list within the parser and need to be iterated through in order to find specific interfaces. Sample configuration from a static connection in file ``/etc/sysconfig/network-scripts/rute-test-net``:: ADDRESS0=10.65.223.0 NETMASK0=255.255.254.0 GATEWAY0=10.65.223.1 Examples: >>> conn_info['ADDRESS0'] '10.65.223.0' >>> conn_info.static_route_name 'test-net' Attributes: static_route_name (str): static route name """ def parse_content(self, content): self.static_route_name = self.file_name.split("route-", 1)[1] super(IfCFGStaticRoute, self).parse_content(content) @parser(Specs.sysconfig_grub) class GrubSysconfig(SysconfigOptions): """ Class to parse the ``/etc/sysconfig/grub`` ``/etc/sysconfig/grub`` is a symlink of ``/etc/default/grub`` file Typical content example:: GRUB_TIMEOUT=1 GRUB_DISTRIBUTOR="$(sed 's, release .*$,,g' /etc/system-release)" GRUB_DEFAULT=saved GRUB_DISABLE_SUBMENU=true GRUB_TERMINAL_OUTPUT="console" GRUB_CMDLINE_LINUX="console=ttyS0 console=ttyS0,115200n8 no_timer_check net.ifnames=0 crashkernel=auto" GRUB_DISABLE_RECOVERY="true" GRUB_ENABLE_BLSCFG=true Examples: >>> grub_syscfg.get('GRUB_ENABLE_BLSCFG') 'true' >>> 'NONEXISTENT_VAR' in grub_syscfg False >>> 'GRUB_ENABLE_BLSCFG' in grub_syscfg True """ pass @parser(Specs.sysconfig_oracleasm) class OracleasmSysconfig(SysconfigOptions): """ Class to parse the ``/etc/sysconfig/oracleasm`` Typical content example:: # # This is a configuration file for automatic loading of the Oracle # Automatic Storage Management library kernel driver. It is generated # By running /etc/init.d/oracleasm configure. Please use that method # to modify this file # # ORACLEASM_ENABELED: 'true' means to load the driver on boot. ORACLEASM_ENABLED=true # ORACLEASM_UID: Default user owning the /dev/oracleasm mount point. ORACLEASM_UID=oracle # ORACLEASM_GID: Default group owning the /dev/oracleasm mount point. ORACLEASM_GID=oinstall # ORACLEASM_SCANBOOT: 'true' means scan for ASM disks on boot. ORACLEASM_SCANBOOT=true # ORACLEASM_SCANORDER: Matching patterns to order disk scanning ORACLEASM_SCANORDER="dm" # ORACLEASM_SCANEXCLUDE: Matching patterns to exclude disks from scan ORACLEASM_SCANEXCLUDE="sd" Examples: >>> oracleasm_syscfg.get('ORACLEASM_SCANBOOT') 'true' >>> 'ORACLEASM_SCANORDER' in oracleasm_syscfg True >>> 'ORACLEASM_SCANEXCLUDE_1' in oracleasm_syscfg False """ pass
# This file is part of Indico. # Copyright (C) 2002 - 2019 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from sqlalchemy.dialects.postgresql import ARRAY from sqlalchemy.ext.declarative import declared_attr from sqlalchemy.ext.hybrid import Comparator, hybrid_method, hybrid_property from sqlalchemy.orm import joinedload, noload from indico.core.db.sqlalchemy import PyIntEnum, db from indico.core.db.sqlalchemy.util.models import get_simple_column_attrs from indico.core.permissions import get_available_permissions from indico.util.decorators import classproperty, strict_classproperty from indico.util.fossilize import Fossilizable, IFossil, fossilizes from indico.util.string import format_repr, return_ascii from indico.util.struct.enum import IndicoEnum class PrincipalType(int, IndicoEnum): user = 1 local_group = 2 multipass_group = 3 email = 4 network = 5 event_role = 6 def _make_check(type_, allow_emails, allow_networks, allow_event_roles, *cols): all_cols = {'user_id', 'local_group_id', 'mp_group_provider', 'mp_group_name'} if allow_emails: all_cols.add('email') if allow_networks: all_cols.add('ip_network_group_id') if allow_event_roles: all_cols.add('event_role_id') required_cols = all_cols & set(cols) forbidden_cols = all_cols - required_cols criteria = ['{} IS NULL'.format(col) for col in sorted(forbidden_cols)] criteria += ['{} IS NOT NULL'.format(col) for col in sorted(required_cols)] condition = 'type != {} OR ({})'.format(type_, ' AND '.join(criteria)) return db.CheckConstraint(condition, 'valid_{}'.format(type_.name)) def serialize_email_principal(email): """Serialize email principal to a simple dict""" return { '_type': 'Email', 'email': email.email, 'id': email.name, 'identifier': 'Email:{}'.format(email.email) } class IEmailPrincipalFossil(IFossil): def getId(self): pass getId.produce = lambda x: x.email def getIdentifier(self): pass getIdentifier.produce = lambda x: 'Email:{}'.format(x.email) def getEmail(self): pass getEmail.produce = lambda x: x.email class EmailPrincipal(Fossilizable): """Wrapper for email principals :param email: The email address. """ principal_type = PrincipalType.email is_network = False is_group = False is_single_person = True is_event_role = False principal_order = 0 fossilizes(IEmailPrincipalFossil) def __init__(self, email): self.email = email.lower() @property def name(self): return self.email @property def as_legacy(self): return self @property def user(self): from indico.modules.users import User return User.query.filter(~User.is_deleted, User.all_emails == self.email).first() def __eq__(self, other): return isinstance(other, EmailPrincipal) and self.email == other.email def __ne__(self, other): return not (self == other) def __hash__(self): return hash(self.email) def __contains__(self, user): if not user: return False return self.email in user.all_emails @return_ascii def __repr__(self): return format_repr(self, 'email') class PrincipalMixin(object): #: The name of the backref added to `User` and `LocalGroup`. #: For consistency, it is recommended to name the backref #: ``in_foo_acl`` with *foo* describing the ACL where this #: mixin is used. principal_backref_name = None #: The columns which should be included in the unique constraints. #: If set to ``None``, no unique constraints will be added. unique_columns = None #: Whether it should be allowed to add a user by email address. #: This is useful in places where no Indico user exists yet. #: Usually adding an email address to an ACL should result in #: an email being sent to the user, inviting him to create an #: account with that email address. allow_emails = False #: Whether it should be allowed to add an IP network. allow_networks = False #: Whether it should be allowed to add an event role. allow_event_roles = False @strict_classproperty @classmethod def __auto_table_args(cls): uniques = () if cls.unique_columns: uniques = [db.Index('ix_uq_{}_user'.format(cls.__tablename__), 'user_id', *cls.unique_columns, unique=True, postgresql_where=db.text('type = {}'.format(PrincipalType.user))), db.Index('ix_uq_{}_local_group'.format(cls.__tablename__), 'local_group_id', *cls.unique_columns, unique=True, postgresql_where=db.text('type = {}'.format(PrincipalType.local_group))), db.Index('ix_uq_{}_mp_group'.format(cls.__tablename__), 'mp_group_provider', 'mp_group_name', *cls.unique_columns, unique=True, postgresql_where=db.text('type = {}'.format(PrincipalType.multipass_group)))] if cls.allow_emails: uniques.append(db.Index('ix_uq_{}_email'.format(cls.__tablename__), 'email', *cls.unique_columns, unique=True, postgresql_where=db.text('type = {}'.format(PrincipalType.email)))) indexes = [db.Index(None, 'mp_group_provider', 'mp_group_name')] checks = [_make_check(PrincipalType.user, cls.allow_emails, cls.allow_networks, cls.allow_event_roles, 'user_id'), _make_check(PrincipalType.local_group, cls.allow_emails, cls.allow_networks, cls.allow_event_roles, 'local_group_id'), _make_check(PrincipalType.multipass_group, cls.allow_emails, cls.allow_networks, cls.allow_event_roles, 'mp_group_provider', 'mp_group_name')] if cls.allow_emails: checks.append(_make_check(PrincipalType.email, cls.allow_emails, cls.allow_networks, cls.allow_event_roles, 'email')) checks.append(db.CheckConstraint('email IS NULL OR email = lower(email)', 'lowercase_email')) if cls.allow_networks: checks.append(_make_check(PrincipalType.network, cls.allow_emails, cls.allow_networks, cls.allow_event_roles, 'ip_network_group_id')) if cls.allow_event_roles: checks.append(_make_check(PrincipalType.event_role, cls.allow_emails, cls.allow_networks, cls.allow_event_roles, 'event_role_id')) return tuple(uniques + indexes + checks) @declared_attr def type(cls): exclude_values = set() if not cls.allow_emails: exclude_values.add(PrincipalType.email) if not cls.allow_networks: exclude_values.add(PrincipalType.network) if not cls.allow_event_roles: exclude_values.add(PrincipalType.event_role) return db.Column( PyIntEnum(PrincipalType, exclude_values=(exclude_values or None)), nullable=False ) @declared_attr def user_id(cls): return db.Column( db.Integer, db.ForeignKey('users.users.id'), nullable=True, index=True ) @declared_attr def local_group_id(cls): return db.Column( db.Integer, db.ForeignKey('users.groups.id'), nullable=True, index=True ) @declared_attr def multipass_group_provider(cls): return db.Column( 'mp_group_provider', # otherwise the index name doesn't fit in 60 chars db.String, nullable=True ) @declared_attr def multipass_group_name(cls): return db.Column( 'mp_group_name', # otherwise the index name doesn't fit in 60 chars db.String, nullable=True ) @declared_attr def email(cls): if not cls.allow_emails: return return db.Column( db.String, nullable=True, index=True ) @declared_attr def ip_network_group_id(cls): if not cls.allow_networks: return return db.Column( db.Integer, db.ForeignKey('indico.ip_network_groups.id'), nullable=True, index=True ) @declared_attr def event_role_id(cls): if not cls.allow_event_roles: return return db.Column( db.Integer, db.ForeignKey('events.roles.id'), nullable=True, index=True ) @declared_attr def user(cls): assert cls.principal_backref_name return db.relationship( 'User', lazy=False, backref=db.backref( cls.principal_backref_name, cascade='all, delete', lazy='dynamic' ) ) @declared_attr def local_group(cls): assert cls.principal_backref_name return db.relationship( 'LocalGroup', lazy=False, backref=db.backref( cls.principal_backref_name, cascade='all, delete', lazy='dynamic' ) ) @declared_attr def ip_network_group(cls): if not cls.allow_networks: return assert cls.principal_backref_name return db.relationship( 'IPNetworkGroup', lazy=False, backref=db.backref( cls.principal_backref_name, cascade='all, delete', lazy='dynamic' ) ) @declared_attr def event_role(cls): if not cls.allow_event_roles: return assert cls.principal_backref_name return db.relationship( 'EventRole', lazy=False, backref=db.backref( cls.principal_backref_name, cascade='all, delete', lazy='dynamic' ) ) @hybrid_property def principal(self): from indico.modules.groups import GroupProxy if self.type == PrincipalType.user: return self.user elif self.type == PrincipalType.local_group: return self.local_group.proxy elif self.type == PrincipalType.multipass_group: return GroupProxy(self.multipass_group_name, self.multipass_group_provider) elif self.type == PrincipalType.email: return EmailPrincipal(self.email) elif self.type == PrincipalType.network: return self.ip_network_group elif self.type == PrincipalType.event_role: return self.event_role @principal.setter def principal(self, value): self.type = value.principal_type self.email = None self.user = None self.local_group = None self.multipass_group_provider = self.multipass_group_name = None self.ip_network_group = None self.event_role = None if self.type == PrincipalType.email: assert self.allow_emails self.email = value.email elif self.type == PrincipalType.network: assert self.allow_networks self.ip_network_group = value elif self.type == PrincipalType.event_role: assert self.allow_event_roles self.event_role = value elif self.type == PrincipalType.local_group: self.local_group = value.group elif self.type == PrincipalType.multipass_group: self.multipass_group_provider = value.provider self.multipass_group_name = value.name elif self.type == PrincipalType.user: self.user = value else: raise ValueError('Unexpected principal type: {}'.format(self.type)) @principal.comparator def principal(cls): return PrincipalComparator(cls) def get_emails(self): """Get a set of all unique emails associated with this principal. For users, this is just the primary email (or nothing for the system user). For groups it is the primary email address of each group members who have an Indico account. """ if self.type == PrincipalType.user and not self.user.is_system: return {self.user.email} elif self.type in (PrincipalType.local_group, PrincipalType.multipass_group): return {x.email for x in self.principal.get_members() if not x.is_system} return set() def merge_privs(self, other): """Merges the privileges of another principal :param other: Another principal object. """ # nothing to do here def current_data(self): return None @classmethod def merge_users(cls, target, source, relationship_attr): """Merges two users in the ACL. :param target: The target user of the merge. :param source: The user that is being merged into `target`. :param relationship_attr: The name of the relationship pointing to the object associated with the ACL entry. """ relationship = getattr(cls, relationship_attr) source_principals = set(getattr(source, cls.principal_backref_name).options(joinedload(relationship))) target_objects = {getattr(x, relationship_attr): x for x in getattr(target, cls.principal_backref_name).options(joinedload(relationship))} for principal in source_principals: existing = target_objects.get(getattr(principal, relationship_attr)) if existing is None: principal.user_id = target.id else: existing.merge_privs(principal) db.session.delete(principal) db.session.flush() @classmethod def replace_email_with_user(cls, user, relationship_attr): """ Replaces all email-based entries matching the user's email addresses with user-based entries. If the user is already in the ACL, the two entries are merged. :param user: A User object. :param relationship_attr: The name of the relationship pointing to the object associated with the ACL entry. :return: The set of objects where the user has been added to the ACL. """ assert cls.allow_emails updated = set() query = (cls .find(cls.email.in_(user.all_emails)) .options(noload('user'), noload('local_group'), joinedload(relationship_attr).load_only('id'))) for entry in query: parent = getattr(entry, relationship_attr) existing = (cls.query .with_parent(parent, 'acl_entries') .options(noload('user'), noload('local_group')) .filter_by(principal=user) .first()) if existing is None: entry.principal = user else: existing.merge_privs(entry) parent.acl_entries.remove(entry) updated.add(parent) db.session.flush() return updated class PrincipalPermissionsMixin(PrincipalMixin): #: The model for which we are a principal. May also be a string #: containing the model's class name. principal_for = None @strict_classproperty @classmethod def __auto_table_args(cls): checks = [db.CheckConstraint('read_access OR full_access OR array_length(permissions, 1) IS NOT NULL', 'has_privs')] if cls.allow_networks: # you can match a network acl entry without being logged in. # we never want that for anything but simple read access checks.append(db.CheckConstraint('type != {} OR (NOT full_access AND array_length(permissions, 1) IS NULL)' .format(PrincipalType.network), 'networks_read_only')) return tuple(checks) read_access = db.Column( db.Boolean, nullable=False, default=False ) full_access = db.Column( db.Boolean, nullable=False, default=False ) permissions = db.Column( ARRAY(db.String), nullable=False, default=[] ) @classproperty @classmethod def principal_for_obj(cls): if isinstance(cls.principal_for, basestring): return db.Model._decl_class_registry[cls.principal_for] else: return cls.principal_for @hybrid_method def has_management_permission(self, permission=None, explicit=False): """Checks whether a principal has a certain management permission. The check always succeeds if the user is a full manager; in that case the list of permissions is ignored. :param permission: The permission to check for or 'ANY' to check for any management permission. :param explicit: Whether to check for the permission itself even if the user has full management privileges. """ if permission is None: if explicit: raise ValueError('permission must be specified if explicit=True') return self.full_access elif not explicit and self.full_access: return True valid_permissions = get_available_permissions(self.principal_for_obj).viewkeys() current_permissions = set(self.permissions) & valid_permissions if permission == 'ANY': return bool(current_permissions) assert permission in valid_permissions, "invalid permission '{}' for object '{}'".format(permission, self.principal_for_obj) return permission in current_permissions @has_management_permission.expression def has_management_permission(cls, permission=None, explicit=False): if permission is None: if explicit: raise ValueError('permission must be specified if explicit=True') return cls.full_access valid_permissions = get_available_permissions(cls.principal_for_obj).viewkeys() if permission == 'ANY': crit = (cls.permissions.op('&&')(db.func.cast(valid_permissions, ARRAY(db.String)))) else: assert permission in valid_permissions, \ "invalid permission '{}' for object '{}'".format(permission, cls.principal_for_obj) crit = (cls.permissions.op('&&')(db.func.cast([permission], ARRAY(db.String)))) if explicit: return crit else: return cls.full_access | crit def merge_privs(self, other): self.read_access = self.read_access or other.read_access self.full_access = self.full_access or other.full_access self.permissions = sorted(set(self.permissions) | set(other.permissions)) @property def current_data(self): return {'permissions': set(self.permissions), 'read_access': self.read_access, 'full_access': self.full_access} class PrincipalComparator(Comparator): def __init__(self, cls): self.cls = cls def __clause_element__(self): # just in case raise NotImplementedError def __eq__(self, other): if other.principal_type == PrincipalType.email: criteria = [self.cls.email == other.email] elif other.principal_type == PrincipalType.network: criteria = [self.cls.ip_network_group_id == other.id] elif other.principal_type == PrincipalType.event_role: criteria = [self.cls.event_role_id == other.id] elif other.principal_type == PrincipalType.local_group: criteria = [self.cls.local_group_id == other.id] elif other.principal_type == PrincipalType.multipass_group: criteria = [self.cls.multipass_group_provider == other.provider, self.cls.multipass_group_name == other.name] elif other.principal_type == PrincipalType.user: criteria = [self.cls.user_id == other.id] else: raise ValueError('Unexpected object type {}: {}'.format(type(other), other)) return db.and_(self.cls.type == other.principal_type, *criteria) def clone_principals(cls, principals, event_role_map=None): """Clone a list of principals. :param cls: the principal type to use (a `PrincipalMixin` subclass) :param principals: a collection of these principals :param event_role_map: the mapping from old to new event roles. if omitted, event roles are skipped :return: A new set of principals that can be added to an object """ rv = set() assert all(isinstance(x, cls) for x in principals) attrs = get_simple_column_attrs(cls) | {'user', 'local_group', 'ip_network_group'} for old_principal in principals: event_role = None if old_principal.type == PrincipalType.event_role: if event_role_map is None: continue event_role = event_role_map[old_principal.event_role] principal = cls() principal.populate_from_dict({attr: getattr(old_principal, attr) for attr in attrs}) if event_role: principal.event_role = event_role rv.add(principal) return rv
# # Copyright 2015 Google Inc. # # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # #!/usr/bin/env python usage = ''' Write buildbot spec to outfile based on the bot name: $ python buildbot_spec.py outfile Test-Ubuntu-GCC-GCE-CPU-AVX2-x86-Debug Or run self-tests: $ python buildbot_spec.py test ''' import inspect import json import os import sys import builder_name_schema import dm_flags import nanobench_flags CONFIG_COVERAGE = 'Coverage' CONFIG_DEBUG = 'Debug' CONFIG_RELEASE = 'Release' def lineno(): caller = inspect.stack()[1] # Up one level to our caller. return inspect.getframeinfo(caller[0]).lineno # Since we don't actually start coverage until we're in the self-test, # some function def lines aren't reported as covered. Add them to this # list so that we can ignore them. cov_skip = [] cov_start = lineno()+1 # We care about coverage starting just past this def. def gyp_defines(builder_dict): gyp_defs = {} # skia_arch_type. if builder_dict['role'] == builder_name_schema.BUILDER_ROLE_BUILD: arch = builder_dict['target_arch'] elif builder_dict['role'] == builder_name_schema.BUILDER_ROLE_HOUSEKEEPER: arch = None else: arch = builder_dict['arch'] arch_types = { 'x86': 'x86', 'x86_64': 'x86_64', 'Arm7': 'arm', 'Arm64': 'arm64', 'Mips': 'mips32', 'Mips64': 'mips64', 'MipsDSP2': 'mips32', } if arch in arch_types: gyp_defs['skia_arch_type'] = arch_types[arch] # housekeeper: build shared lib. if builder_dict['role'] == builder_name_schema.BUILDER_ROLE_HOUSEKEEPER: gyp_defs['skia_shared_lib'] = '1' # skia_gpu. if builder_dict.get('cpu_or_gpu') == 'CPU': gyp_defs['skia_gpu'] = '0' # skia_warnings_as_errors. werr = False if builder_dict['role'] == builder_name_schema.BUILDER_ROLE_BUILD: if 'Win' in builder_dict.get('os', ''): if not ('GDI' in builder_dict.get('extra_config', '') or 'Exceptions' in builder_dict.get('extra_config', '')): werr = True elif ('Mac' in builder_dict.get('os', '') and 'Android' in builder_dict.get('extra_config', '')): werr = False else: werr = True gyp_defs['skia_warnings_as_errors'] = str(int(werr)) # True/False -> '1'/'0' # Win debugger. if 'Win' in builder_dict.get('os', ''): gyp_defs['skia_win_debuggers_path'] = 'c:/DbgHelp' # Qt SDK (Win). if 'Win' in builder_dict.get('os', ''): if builder_dict.get('os') == 'Win8': gyp_defs['qt_sdk'] = 'C:/Qt/Qt5.1.0/5.1.0/msvc2012_64/' else: gyp_defs['qt_sdk'] = 'C:/Qt/4.8.5/' # ANGLE. if builder_dict.get('extra_config') == 'ANGLE': gyp_defs['skia_angle'] = '1' if builder_dict.get('os', '') in ('Ubuntu', 'Linux'): gyp_defs['use_x11'] = '1' gyp_defs['chromeos'] = '0' # GDI. if builder_dict.get('extra_config') == 'GDI': gyp_defs['skia_gdi'] = '1' # Build with Exceptions on Windows. if ('Win' in builder_dict.get('os', '') and builder_dict.get('extra_config') == 'Exceptions'): gyp_defs['skia_win_exceptions'] = '1' # iOS. if (builder_dict.get('os') == 'iOS' or builder_dict.get('extra_config') == 'iOS'): gyp_defs['skia_os'] = 'ios' # Shared library build. if builder_dict.get('extra_config') == 'Shared': gyp_defs['skia_shared_lib'] = '1' # Build fastest Skia possible. if builder_dict.get('extra_config') == 'Fast': gyp_defs['skia_fast'] = '1' # PDF viewer in GM. if (builder_dict.get('os') == 'Mac10.8' and builder_dict.get('arch') == 'x86_64' and builder_dict.get('configuration') == 'Release'): gyp_defs['skia_run_pdfviewer_in_gm'] = '1' # Clang. if builder_dict.get('compiler') == 'Clang': gyp_defs['skia_clang_build'] = '1' # Valgrind. if 'Valgrind' in builder_dict.get('extra_config', ''): gyp_defs['skia_release_optimization_level'] = '1' # Link-time code generation just wastes time on compile-only bots. if (builder_dict.get('role') == builder_name_schema.BUILDER_ROLE_BUILD and builder_dict.get('compiler') == 'MSVC'): gyp_defs['skia_win_ltcg'] = '0' # Mesa. if (builder_dict.get('extra_config') == 'Mesa' or builder_dict.get('cpu_or_gpu_value') == 'Mesa'): gyp_defs['skia_mesa'] = '1' # VisualBench if builder_dict.get('extra_config') == 'VisualBench': gyp_defs['skia_use_sdl'] = '1' # skia_use_android_framework_defines. if builder_dict.get('extra_config') == 'Android_FrameworkDefs': gyp_defs['skia_use_android_framework_defines'] = '1' # Skia dump stats for perf tests and gpu if (builder_dict.get('cpu_or_gpu') == 'GPU' and builder_dict.get('role') == 'Perf'): gyp_defs['skia_dump_stats'] = '1' # CommandBuffer. if builder_dict.get('extra_config') == 'CommandBuffer': gyp_defs['skia_command_buffer'] = '1' # Vulkan. if builder_dict.get('extra_config') == 'Vulkan': gyp_defs['skia_vulkan'] = '1' return gyp_defs cov_skip.extend([lineno(), lineno() + 1]) def get_extra_env_vars(builder_dict): env = {} if builder_dict.get('configuration') == CONFIG_COVERAGE: # We have to use Clang 3.6 because earlier versions do not support the # compile flags we use and 3.7 and 3.8 hit asserts during compilation. env['CC'] = '/usr/bin/clang-3.6' env['CXX'] = '/usr/bin/clang++-3.6' elif builder_dict.get('compiler') == 'Clang': env['CC'] = '/usr/bin/clang' env['CXX'] = '/usr/bin/clang++' # SKNX_NO_SIMD, SK_USE_DISCARDABLE_SCALEDIMAGECACHE, etc. extra_config = builder_dict.get('extra_config', '') if extra_config.startswith('SK') and extra_config.isupper(): env['CPPFLAGS'] = '-D' + extra_config return env cov_skip.extend([lineno(), lineno() + 1]) def build_targets_from_builder_dict(builder_dict, do_test_steps, do_perf_steps): """Return a list of targets to build, depending on the builder type.""" if builder_dict['role'] in ('Test', 'Perf') and builder_dict['os'] == 'iOS': return ['iOSShell'] if builder_dict.get('extra_config') == 'Appurify': return ['VisualBenchTest_APK'] if 'SAN' in builder_dict.get('extra_config', ''): # 'most' does not compile under MSAN. return ['dm', 'nanobench'] t = [] if do_test_steps: t.append('dm') if do_perf_steps and builder_dict.get('extra_config') == 'VisualBench': t.append('visualbench') elif do_perf_steps: t.append('nanobench') if t: return t else: return ['most'] cov_skip.extend([lineno(), lineno() + 1]) def device_cfg(builder_dict): # Android. if 'Android' in builder_dict.get('extra_config', ''): if 'NoNeon' in builder_dict['extra_config']: return 'arm_v7' return { 'Arm64': 'arm64', 'x86': 'x86', 'x86_64': 'x86_64', 'Mips': 'mips', 'Mips64': 'mips64', 'MipsDSP2': 'mips_dsp2', }.get(builder_dict['target_arch'], 'arm_v7_neon') elif builder_dict.get('os') == 'Android': return { 'AndroidOne': 'arm_v7_neon', 'GalaxyS3': 'arm_v7_neon', 'GalaxyS4': 'arm_v7_neon', 'NVIDIA_Shield': 'arm64', 'Nexus10': 'arm_v7_neon', 'Nexus5': 'arm_v7_neon', 'Nexus6': 'arm_v7_neon', 'Nexus7': 'arm_v7_neon', 'Nexus7v2': 'arm_v7_neon', 'Nexus9': 'arm64', 'NexusPlayer': 'x86', }[builder_dict['model']] # iOS. if 'iOS' in builder_dict.get('os', ''): return { 'iPad4': 'iPad4,1', }[builder_dict['model']] return None cov_skip.extend([lineno(), lineno() + 1]) def product_board(builder_dict): if 'Android' in builder_dict.get('os', ''): return { 'AndroidOne': None, # TODO(borenet,kjlubick) 'GalaxyS3': 'smdk4x12', 'GalaxyS4': None, # TODO(borenet,kjlubick) 'NVIDIA_Shield': None, # TODO(borenet,kjlubick) 'Nexus10': 'manta', 'Nexus5': 'hammerhead', 'Nexus6': 'shamu', 'Nexus7': 'grouper', 'Nexus7v2': 'flo', 'Nexus9': 'flounder', 'NexusPlayer': 'fugu', }[builder_dict['model']] return None cov_skip.extend([lineno(), lineno() + 1]) def get_builder_spec(builder_name): builder_dict = builder_name_schema.DictForBuilderName(builder_name) env = get_extra_env_vars(builder_dict) gyp_defs = gyp_defines(builder_dict) gyp_defs_list = ['%s=%s' % (k, v) for k, v in gyp_defs.iteritems()] gyp_defs_list.sort() env['GYP_DEFINES'] = ' '.join(gyp_defs_list) rv = { 'builder_cfg': builder_dict, 'dm_flags': dm_flags.get_args(builder_name), 'env': env, 'nanobench_flags': nanobench_flags.get_args(builder_name), } device = device_cfg(builder_dict) if device: rv['device_cfg'] = device board = product_board(builder_dict) if board: rv['product.board'] = board role = builder_dict['role'] if role == builder_name_schema.BUILDER_ROLE_HOUSEKEEPER: configuration = CONFIG_RELEASE else: configuration = builder_dict.get( 'configuration', CONFIG_DEBUG) arch = (builder_dict.get('arch') or builder_dict.get('target_arch')) if ('Win' in builder_dict.get('os', '') and arch == 'x86_64'): configuration += '_x64' rv['configuration'] = configuration if configuration == CONFIG_COVERAGE: rv['do_compile_steps'] = False rv['do_test_steps'] = role == builder_name_schema.BUILDER_ROLE_TEST rv['do_perf_steps'] = (role == builder_name_schema.BUILDER_ROLE_PERF or (role == builder_name_schema.BUILDER_ROLE_TEST and configuration == CONFIG_DEBUG)) if rv['do_test_steps'] and 'Valgrind' in builder_name: rv['do_perf_steps'] = True if 'GalaxyS4' in builder_name: rv['do_perf_steps'] = False rv['build_targets'] = build_targets_from_builder_dict( builder_dict, rv['do_test_steps'], rv['do_perf_steps']) # Do we upload perf results? upload_perf_results = False if role == builder_name_schema.BUILDER_ROLE_PERF: upload_perf_results = True rv['upload_perf_results'] = upload_perf_results # Do we upload correctness results? skip_upload_bots = [ 'ASAN', 'Coverage', 'MSAN', 'TSAN', 'UBSAN', 'Valgrind', ] upload_dm_results = True for s in skip_upload_bots: if s in builder_name: upload_dm_results = False break rv['upload_dm_results'] = upload_dm_results return rv cov_end = lineno() # Don't care about code coverage past here. def self_test(): import coverage # This way the bots don't need coverage.py to be installed. args = {} cases = [ 'Build-Mac10.8-Clang-Arm7-Debug-Android', 'Build-Win-MSVC-x86-Debug', 'Build-Win-MSVC-x86-Debug-GDI', 'Build-Win-MSVC-x86-Debug-Exceptions', 'Build-Ubuntu-GCC-Arm7-Debug-Android_FrameworkDefs', 'Build-Ubuntu-GCC-Arm7-Debug-Android_NoNeon', 'Build-Ubuntu-GCC-x86_64-Release-Mesa', 'Build-Ubuntu-GCC-x86_64-Release-ANGLE', 'Housekeeper-PerCommit', 'Perf-Win8-MSVC-ShuttleB-GPU-HD4600-x86_64-Release-Trybot', 'Perf-Ubuntu-GCC-ShuttleA-GPU-GTX660-x86_64-Release-VisualBench', 'Test-Android-GCC-GalaxyS4-GPU-SGX544-Arm7-Debug', 'Perf-Android-GCC-Nexus5-GPU-Adreno330-Arm7-Release-Appurify', 'Test-Android-GCC-Nexus6-GPU-Adreno420-Arm7-Debug', 'Test-iOS-Clang-iPad4-GPU-SGX554-Arm7-Debug', 'Test-Mac-Clang-MacMini6.2-GPU-HD4000-x86_64-Debug-CommandBuffer', 'Test-Mac10.8-Clang-MacMini4.1-GPU-GeForce320M-x86_64-Release', 'Test-Ubuntu-Clang-GCE-CPU-AVX2-x86_64-Coverage', ('Test-Ubuntu-GCC-GCE-CPU-AVX2-x86_64-Release-' 'SK_USE_DISCARDABLE_SCALEDIMAGECACHE'), 'Test-Ubuntu-GCC-GCE-CPU-AVX2-x86_64-Release-SKNX_NO_SIMD', 'Test-Ubuntu-GCC-GCE-CPU-AVX2-x86_64-Release-Fast', 'Test-Ubuntu-GCC-GCE-CPU-AVX2-x86_64-Release-Shared', 'Test-Ubuntu-GCC-ShuttleA-GPU-GTX550Ti-x86_64-Release-Valgrind', 'Test-Win10-MSVC-ShuttleA-GPU-GTX660-x86_64-Debug-Vulkan', 'Test-Win8-MSVC-ShuttleB-GPU-HD4600-x86-Release-ANGLE', 'Test-Win8-MSVC-ShuttleA-CPU-AVX-x86_64-Debug', ] cov = coverage.coverage() cov.start() for case in cases: args[case] = get_builder_spec(case) cov.stop() this_file = os.path.basename(__file__) _, _, not_run, _ = cov.analysis(this_file) filtered = [line for line in not_run if line > cov_start and line < cov_end and line not in cov_skip] if filtered: print 'Lines not covered by test cases: ', filtered sys.exit(1) golden = this_file.replace('.py', '.json') with open(os.path.join(os.path.dirname(__file__), golden), 'w') as f: json.dump(args, f, indent=2, sort_keys=True) if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == 'test': self_test() sys.exit(0) if len(sys.argv) != 3: print usage sys.exit(1) with open(sys.argv[1], 'w') as out: json.dump(get_builder_spec(sys.argv[2]), out)
# Copyright 2013 Mirantis Inc. # Copyright 2013 Rackspace Hosting. # # 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 logging from django.core.urlresolvers import reverse from django import http from mox import IsA # noqa from horizon import exceptions from openstack_dashboard import api from openstack_dashboard.test import helpers as test from troveclient import common INDEX_URL = reverse('horizon:project:databases:index') LAUNCH_URL = reverse('horizon:project:databases:launch') DETAILS_URL = reverse('horizon:project:databases:detail', args=['id']) class DatabaseTests(test.TestCase): @test.create_stubs( {api.trove: ('instance_list', 'flavor_list')}) def test_index(self): # Mock database instances databases = common.Paginated(self.databases.list()) api.trove.instance_list(IsA(http.HttpRequest), marker=None)\ .AndReturn(databases) # Mock flavors api.trove.flavor_list(IsA(http.HttpRequest))\ .AndReturn(self.flavors.list()) self.mox.ReplayAll() res = self.client.get(INDEX_URL) self.assertTemplateUsed(res, 'project/databases/index.html') # Check the Host column displaying ip or hostname self.assertContains(res, '10.0.0.3') self.assertContains(res, 'trove.instance-2.com') @test.create_stubs( {api.trove: ('instance_list', 'flavor_list')}) def test_index_flavor_exception(self): # Mock database instances databases = common.Paginated(self.databases.list()) api.trove.instance_list(IsA(http.HttpRequest), marker=None)\ .AndReturn(databases) # Mock flavors api.trove.flavor_list(IsA(http.HttpRequest))\ .AndRaise(self.exceptions.trove) self.mox.ReplayAll() res = self.client.get(INDEX_URL) self.assertTemplateUsed(res, 'project/databases/index.html') self.assertMessageCount(res, error=1) @test.create_stubs( {api.trove: ('instance_list',)}) def test_index_list_exception(self): # Mock database instances api.trove.instance_list(IsA(http.HttpRequest), marker=None)\ .AndRaise(self.exceptions.trove) self.mox.ReplayAll() res = self.client.get(INDEX_URL) self.assertTemplateUsed(res, 'project/databases/index.html') self.assertMessageCount(res, error=1) @test.create_stubs( {api.trove: ('instance_list', 'flavor_list')}) def test_index_pagination(self): # Mock database instances databases = self.databases.list() last_record = databases[1] databases = common.Paginated(databases, next_marker="foo") api.trove.instance_list(IsA(http.HttpRequest), marker=None)\ .AndReturn(databases) # Mock flavors api.trove.flavor_list(IsA(http.HttpRequest))\ .AndReturn(self.flavors.list()) self.mox.ReplayAll() res = self.client.get(INDEX_URL) self.assertTemplateUsed(res, 'project/databases/index.html') self.assertContains( res, 'marker=' + last_record.id) @test.create_stubs( {api.trove: ('instance_list', 'flavor_list')}) def test_index_flavor_list_exception(self): # Mocking instances. databases = common.Paginated(self.databases.list()) api.trove.instance_list( IsA(http.HttpRequest), marker=None, ).AndReturn(databases) # Mocking flavor list with raising an exception. api.trove.flavor_list( IsA(http.HttpRequest), ).AndRaise(self.exceptions.trove) self.mox.ReplayAll() res = self.client.get(INDEX_URL) self.assertTemplateUsed(res, 'project/databases/index.html') self.assertMessageCount(res, error=1) @test.create_stubs({ api.trove: ('flavor_list', 'backup_list', 'datastore_list', 'datastore_version_list', 'instance_list'), api.neutron: ('network_list',)}) def test_launch_instance(self): api.trove.flavor_list(IsA(http.HttpRequest)).AndReturn( self.flavors.list()) api.trove.backup_list(IsA(http.HttpRequest)).AndReturn( self.database_backups.list()) api.trove.instance_list(IsA(http.HttpRequest)).AndReturn( self.databases.list()) # Mock datastores api.trove.datastore_list(IsA(http.HttpRequest)).AndReturn( self.datastores.list()) # Mock datastore versions api.trove.datastore_version_list(IsA(http.HttpRequest), IsA(str)).\ AndReturn(self.datastore_versions.list()) api.neutron.network_list(IsA(http.HttpRequest), tenant_id=self.tenant.id, shared=False).AndReturn( self.networks.list()[:1]) api.neutron.network_list(IsA(http.HttpRequest), shared=True).AndReturn( self.networks.list()[1:]) self.mox.ReplayAll() res = self.client.get(LAUNCH_URL) self.assertTemplateUsed(res, 'project/databases/launch.html') @test.create_stubs({api.trove: ('flavor_list',)}) def test_launch_instance_exception_on_flavors(self): trove_exception = self.exceptions.nova api.trove.flavor_list(IsA(http.HttpRequest)).AndRaise(trove_exception) self.mox.ReplayAll() toSuppress = ["openstack_dashboard.dashboards.project.databases." "workflows.create_instance", "horizon.workflows.base"] # Suppress expected log messages in the test output loggers = [] for cls in toSuppress: logger = logging.getLogger(cls) loggers.append((logger, logger.getEffectiveLevel())) logger.setLevel(logging.CRITICAL) try: with self.assertRaises(exceptions.Http302): self.client.get(LAUNCH_URL) finally: # Restore the previous log levels for (log, level) in loggers: log.setLevel(level) @test.create_stubs({ api.trove: ('flavor_list', 'backup_list', 'instance_create', 'datastore_list', 'datastore_version_list', 'instance_list'), api.neutron: ('network_list',)}) def test_create_simple_instance(self): api.trove.flavor_list(IsA(http.HttpRequest)).AndReturn( self.flavors.list()) api.trove.backup_list(IsA(http.HttpRequest)).AndReturn( self.database_backups.list()) api.trove.instance_list(IsA(http.HttpRequest)).AndReturn( self.databases.list()) # Mock datastores api.trove.datastore_list(IsA(http.HttpRequest))\ .AndReturn(self.datastores.list()) # Mock datastore versions api.trove.datastore_version_list(IsA(http.HttpRequest), IsA(str))\ .AndReturn(self.datastore_versions.list()) api.neutron.network_list(IsA(http.HttpRequest), tenant_id=self.tenant.id, shared=False).AndReturn( self.networks.list()[:1]) api.neutron.network_list(IsA(http.HttpRequest), shared=True).AndReturn( self.networks.list()[1:]) nics = [{"net-id": self.networks.first().id, "v4-fixed-ip": ''}] # Actual create database call api.trove.instance_create( IsA(http.HttpRequest), IsA(unicode), IsA(int), IsA(unicode), databases=None, datastore=IsA(unicode), datastore_version=IsA(unicode), restore_point=None, replica_of=None, users=None, nics=nics).AndReturn(self.databases.first()) self.mox.ReplayAll() post = { 'name': "MyDB", 'volume': '1', 'flavor': 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'network': self.networks.first().id, 'datastore': 'mysql,5.5', } res = self.client.post(LAUNCH_URL, post) self.assertRedirectsNoFollow(res, INDEX_URL) @test.create_stubs({ api.trove: ('flavor_list', 'backup_list', 'instance_create', 'datastore_list', 'datastore_version_list', 'instance_list'), api.neutron: ('network_list',)}) def test_create_simple_instance_exception(self): trove_exception = self.exceptions.nova api.trove.flavor_list(IsA(http.HttpRequest)).AndReturn( self.flavors.list()) api.trove.backup_list(IsA(http.HttpRequest)).AndReturn( self.database_backups.list()) api.trove.instance_list(IsA(http.HttpRequest)).AndReturn( self.databases.list()) # Mock datastores api.trove.datastore_list(IsA(http.HttpRequest))\ .AndReturn(self.datastores.list()) # Mock datastore versions api.trove.datastore_version_list(IsA(http.HttpRequest), IsA(str))\ .AndReturn(self.datastore_versions.list()) api.neutron.network_list(IsA(http.HttpRequest), tenant_id=self.tenant.id, shared=False).AndReturn( self.networks.list()[:1]) api.neutron.network_list(IsA(http.HttpRequest), shared=True).AndReturn( self.networks.list()[1:]) nics = [{"net-id": self.networks.first().id, "v4-fixed-ip": ''}] # Actual create database call api.trove.instance_create( IsA(http.HttpRequest), IsA(unicode), IsA(int), IsA(unicode), databases=None, datastore=IsA(unicode), datastore_version=IsA(unicode), restore_point=None, replica_of=None, users=None, nics=nics).AndRaise(trove_exception) self.mox.ReplayAll() post = { 'name': "MyDB", 'volume': '1', 'flavor': 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'network': self.networks.first().id, 'datastore': 'mysql,5.5', } res = self.client.post(LAUNCH_URL, post) self.assertRedirectsNoFollow(res, INDEX_URL) @test.create_stubs( {api.trove: ('instance_get', 'flavor_get',)}) def _test_details(self, database, with_designate=False): api.trove.instance_get(IsA(http.HttpRequest), IsA(unicode))\ .AndReturn(database) api.trove.flavor_get(IsA(http.HttpRequest), IsA(str))\ .AndReturn(self.flavors.first()) self.mox.ReplayAll() res = self.client.get(DETAILS_URL) self.assertTemplateUsed(res, 'project/databases/detail.html') if with_designate: self.assertContains(res, database.hostname) else: self.assertContains(res, database.ip[0]) def test_details_with_ip(self): database = self.databases.first() self._test_details(database, with_designate=False) def test_details_with_hostname(self): database = self.databases.list()[1] self._test_details(database, with_designate=True) @test.create_stubs( {api.trove: ('instance_get', 'flavor_get', 'users_list', 'user_list_access', 'user_delete')}) def test_user_delete(self): database = self.databases.first() user = self.database_users.first() user_db = self.database_user_dbs.first() database_id = database.id # Instead of using the user's ID, the api uses the user's name. BOOO! user_id = user.name # views.py: DetailView.get_data api.trove.instance_get(IsA(http.HttpRequest), IsA(unicode))\ .AndReturn(database) api.trove.flavor_get(IsA(http.HttpRequest), IsA(str))\ .AndReturn(self.flavors.first()) # tabs.py: UserTab.get_user_data api.trove.users_list(IsA(http.HttpRequest), database_id).AndReturn([user]) api.trove.user_list_access(IsA(http.HttpRequest), database_id, user_id).AndReturn([user_db]) # tables.py: DeleteUser.delete api.trove.user_delete(IsA(http.HttpRequest), database_id, user_id).AndReturn(None) self.mox.ReplayAll() details_url = reverse('horizon:project:databases:detail', args=[database_id]) url = details_url + '?tab=instance_details__users_tab' action_string = u"users__delete__%s" % user_id form_data = {'action': action_string} res = self.client.post(url, form_data) self.assertRedirectsNoFollow(res, url) @test.create_stubs({ api.trove: ('instance_get', 'instance_resize_volume')}) def test_resize_volume(self): database = self.databases.first() database_id = database.id database_size = database.volume.get('size') # views.py: DetailView.get_data api.trove.instance_get(IsA(http.HttpRequest), IsA(unicode))\ .AndReturn(database) # forms.py: ResizeVolumeForm.handle api.trove.instance_resize_volume(IsA(http.HttpRequest), database_id, IsA(int)).AndReturn(None) self.mox.ReplayAll() url = reverse('horizon:project:databases:resize_volume', args=[database_id]) post = { 'instance_id': database_id, 'orig_size': database_size, 'new_size': database_size + 1, } res = self.client.post(url, post) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, INDEX_URL) @test.create_stubs({api.trove: ('instance_get', )}) def test_resize_volume_bad_value(self): database = self.databases.first() database_id = database.id database_size = database.volume.get('size') # views.py: DetailView.get_data api.trove.instance_get(IsA(http.HttpRequest), IsA(unicode))\ .AndReturn(database) self.mox.ReplayAll() url = reverse('horizon:project:databases:resize_volume', args=[database_id]) post = { 'instance_id': database_id, 'orig_size': database_size, 'new_size': database_size, } res = self.client.post(url, post) self.assertContains( res, "New size for volume must be greater than current size.") @test.create_stubs( {api.trove: ('instance_get', 'flavor_list')}) def test_resize_instance_get(self): database = self.databases.first() # views.py: DetailView.get_data api.trove.instance_get(IsA(http.HttpRequest), database.id)\ .AndReturn(database) api.trove.flavor_list(IsA(http.HttpRequest)).\ AndReturn(self.database_flavors.list()) self.mox.ReplayAll() url = reverse('horizon:project:databases:resize_instance', args=[database.id]) res = self.client.get(url) self.assertTemplateUsed(res, 'project/databases/resize_instance.html') option = '<option value="%s">%s</option>' for flavor in self.database_flavors.list(): if flavor.id == database.flavor['id']: self.assertNotContains(res, option % (flavor.id, flavor.name)) else: self.assertContains(res, option % (flavor.id, flavor.name)) @test.create_stubs( {api.trove: ('instance_get', 'flavor_list', 'instance_resize')}) def test_resize_instance(self): database = self.databases.first() # views.py: DetailView.get_data api.trove.instance_get(IsA(http.HttpRequest), database.id)\ .AndReturn(database) api.trove.flavor_list(IsA(http.HttpRequest)).\ AndReturn(self.database_flavors.list()) old_flavor = self.database_flavors.list()[0] new_flavor = self.database_flavors.list()[1] api.trove.instance_resize(IsA(http.HttpRequest), database.id, new_flavor.id).AndReturn(None) self.mox.ReplayAll() url = reverse('horizon:project:databases:resize_instance', args=[database.id]) post = { 'instance_id': database.id, 'old_flavor_name': old_flavor.name, 'old_flavor_id': old_flavor.id, 'new_flavor': new_flavor.id } res = self.client.post(url, post) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, INDEX_URL) @test.create_stubs({ api.trove: ('flavor_list', 'backup_list', 'instance_create', 'datastore_list', 'datastore_version_list', 'instance_list', 'instance_get'), api.neutron: ('network_list',)}) def test_create_replica_instance(self): api.trove.flavor_list(IsA(http.HttpRequest)).AndReturn( self.flavors.list()) api.trove.backup_list(IsA(http.HttpRequest)).AndReturn( self.database_backups.list()) api.trove.instance_list(IsA(http.HttpRequest)).AndReturn( self.databases.list()) api.trove.datastore_list(IsA(http.HttpRequest))\ .AndReturn(self.datastores.list()) api.trove.datastore_version_list(IsA(http.HttpRequest), IsA(str))\ .AndReturn(self.datastore_versions.list()) api.neutron.network_list(IsA(http.HttpRequest), tenant_id=self.tenant.id, shared=False).\ AndReturn(self.networks.list()[:1]) api.neutron.network_list(IsA(http.HttpRequest), shared=True).\ AndReturn(self.networks.list()[1:]) nics = [{"net-id": self.networks.first().id, "v4-fixed-ip": ''}] api.trove.instance_get(IsA(http.HttpRequest), IsA(unicode))\ .AndReturn(self.databases.first()) # Actual create database call api.trove.instance_create( IsA(http.HttpRequest), IsA(unicode), IsA(int), IsA(unicode), databases=None, datastore=IsA(unicode), datastore_version=IsA(unicode), restore_point=None, replica_of=self.databases.first().id, users=None, nics=nics).AndReturn(self.databases.first()) self.mox.ReplayAll() post = { 'name': "MyDB", 'volume': '1', 'flavor': 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'network': self.networks.first().id, 'datastore': 'mysql,5.5', 'initial_state': 'master', 'master': self.databases.first().id } res = self.client.post(LAUNCH_URL, post) self.assertRedirectsNoFollow(res, INDEX_URL)
# autotracker-bottomup - the quite a few times more ultimate audio experience # by Ben "GreaseMonkey" Russell, 2011. Public domain. # # # # BUGS: # - sometimes gets stuck in an infinite loop. attempted to alleviate it but it doesn't work. # - i think it sometimes jumps further than an octave in some situations # oh and: # - has moments where it sounds bad. if you can fix this for good, let me know! import sys, struct, random import math # tunables. SMP_FREQ = 44100 SMP_16BIT = True # IT format constants. leave these alone. IT_FLAG_STEREO = 0x01 IT_FLAG_VOL0MIX = 0x02 # absolutely useless since 1.04. IT_FLAG_INSTR = 0x04 IT_FLAG_LINEAR = 0x08 IT_FLAG_OLDEFF = 0x10 # don't enable this, it's not well documented. IT_FLAG_COMPATGXX = 0x20 # don't enable this, it's not well documented. IT_FLAG_PWHEEL = 0x40 # MIDI-related, don't use IT_FLAG_USEMIDI = 0x80 # undocumented MIDI crap, don't use IT_SPECIAL_MESSAGE = 0x01 # MIDI-related, don't use IT_SPECIAL_UNK1 = 0x02 # undocumented MIDI crap, don't use IT_SPECIAL_UNK2 = 0x04 # undocumented MIDI crap, don't use IT_SPECIAL_HASMIDI = 0x08 # undocumented MIDI crap, don't use IT_SAMPLE_EXISTS = 0x01 IT_SAMPLE_16BIT = 0x02 IT_SAMPLE_STEREO = 0x04 # don't use, it's a modplugism. IT_SAMPLE_IT214 = 0x08 # not supported yet - don't use. IT_SAMPLE_LOOP = 0x10 IT_SAMPLE_SUS = 0x20 # mikmod doesn't like this, so be wary. IT_SAMPLE_LOOPBIDI = 0x40 IT_SAMPLE_SUSBIDI = 0x80 # IT_CONVERT_* refers to the sample conversion flags. # this is a VERY internal feature and not widely implemented. # please ensure you ONLY use IT_CONVERT_SIGNED for normal samples. # EXCEPTION: IT_CONVERT_DELTA + IT_SAMPLE_IT214 = IT215 compression. IT_CONVERT_SIGNED = 0x01 IT_CONVERT_BIGEND = 0x02 IT_CONVERT_DELTA = 0x04 IT_CONVERT_BYTEDELT = 0x08 IT_CONVERT_TXWAVE = 0x10 IT_CONVERT_STEREO = 0x20 # anyhow, here's some code. enjoy. IT_BASEFLG_SAMPLE = ( IT_SAMPLE_EXISTS | (IT_SAMPLE_16BIT if SMP_16BIT else 0) ) ########################## # # # IT MODULE HANDLING # # # ########################## # NOTE: Currently only writes data. class ITFile: def __init__(self): self.name = "autotracker-bu module" self.flags = IT_FLAG_STEREO self.highlight = 0x1004 self.ordlist = [] self.inslist = [] self.smplist = [] self.patlist = [] self.chnpan = [32 for i in xrange(64)] self.chnvol = [64 for i in xrange(64)] self.version = 0x0217 self.vercompat = 0x0200 self.flags = ( IT_FLAG_STEREO | IT_FLAG_VOL0MIX # in the exceptionally rare case it may help... | IT_FLAG_LINEAR ) self.special = ( IT_SPECIAL_MESSAGE ) self.gvol = 128 self.mvol = 48 self.tempo = random.randint(90,160) self.speed = 3 self.pitchwheel = 0 self.pansep = 128 self.message = ( "Generated with Autotracker-Bu\n" + "2011 Ben \"GreaseMonkey\" Russell - Public domain\n" ) def enqueue_ptr(self, call): self.ptrq.append((self.fp.tell(),call)) self.write("00PS") def save(self, fname): self.fp = open(fname,"wb") self.message_fixed = self.message.replace("\n\r","\n").replace("\n","\r") + "\x00\x00" self.ptrq = [] self.doheader(self) while self.ptrq: pos, f = self.ptrq.pop(0) t = self.fp.tell() self.fp.seek(pos) self.write(struct.pack("<I",t)) self.fp.seek(t) f(self) self.fp.close() def w_msg(self, fp): fp.write(self.message_fixed) def doheader(self, fp): ordlist = self.ordlist[:] if (not ordlist) or ordlist[-1] != 0xFF: ordlist.append(0xFF) fp.write("IMPM") fp.write_padded(25, self.name) fp.write(struct.pack("<HHHHHHHHH" ,self.highlight ,len(ordlist),len(self.inslist),len(self.smplist),len(self.patlist) ,self.version,self.vercompat,self.flags,self.special )) fp.write(struct.pack("<BBBBBBH" ,self.gvol,self.mvol,self.speed,self.tempo ,self.pansep,self.pitchwheel,len(self.message_fixed) )) fp.enqueue_ptr(self.w_msg) fp.write("AtBu") fp.write(''.join(chr(v) for v in self.chnpan)) fp.write(''.join(chr(v) for v in self.chnvol)) fp.write(''.join(chr(v) for v in ordlist)) l = self.inslist + self.smplist + self.patlist for i in xrange(len(l)): self.enqueue_ptr(l[i].write) fp.write(struct.pack("<HI",0,0)) def write(self, data): self.fp.write(data) def write_padded(self, length, s, addnull = True): if len(s) < length: s += "\x00"*(length-len(s)) else: s = s[:length] assert len(s) == length, "STUPID! write_padded gave wrong length!" self.write(s) if addnull: self.write("\x00") def write_sample_array(self, data): # TODO: allow for a compressor / proper saturator if SMP_16BIT: for v in data: d = max(-0x8000,min(0x7FFF,int(v * 0x7FFF))) self.write(struct.pack("<h", d)) else: for v in data: d = max(-0x80,min(0x7F,int(v * 0x7F))) self.write(struct.pack("<b",d)) def smp_add(self, smp): self.smplist.append(smp) idx = len(self.smplist) return idx def pat_add(self, pat): idx = len(self.patlist) self.patlist.append(pat) return idx def ord_add(self, order): self.ordlist.append(order) class Sample: name = "feed me with a sample :)" flags = 0 boost = 1.0 fname = "AUTOTRKR.BU" gvol = 64 vol = 64 defpan = 32 # NOTE: set top bit (0x80) to actually use default pan convert = IT_CONVERT_SIGNED lpbeg = 0 lpend = 0 freq = SMP_FREQ susbeg = 0 susend = 0 vibspeed = 0 vibdepth = 0 vibrate = 0 vibtype = 0 def __init__(self, name = None, gvol = None, *args, **kwargs): if name != None: self.name = name if gvol != None: self.gvol = gvol self.data = self.generate(*args, **kwargs) self.length = len(self.data) self.amplify() def write(self, fp): fp.write("IMPS") fp.write_padded(12, self.fname) fp.write(struct.pack("<BBB", self.gvol, self.flags, self.vol)) fp.write_padded(25, self.name) fp.write(struct.pack("<BB", self.convert, self.defpan)) fp.write(struct.pack("<IIIIII" ,self.length, self.lpbeg, self.lpend, self.freq ,self.susbeg, self.susend)) fp.enqueue_ptr(self.write_data) fp.write(struct.pack("<BBBB", self.vibspeed, self.vibdepth, self.vibrate, self.vibtype)) def write_data(self, fp): fp.write_sample_array(self.data) def amplify(self): l = -0.0000000001 h = 0.0000000001 for v in self.data:#[len(self.data)//32:]: if v < l: l = v if v > h: h = v amp = self.boost / max(-l,h) #print amp for i in xrange(len(self.data)): self.data[i] *= amp def generate(self, *args, **kwargs): return [] class Pattern: def __init__(self, rows): self.rows = rows assert rows >= 4, "too few rows" # note, this is just so modplug doesn't whinge. IT can handle 1-row patterns. assert rows <= 200, "too many rows" # on the other hand, IT chunders if you have more than 200 rows. self.data = [[[253,0,255,0,0] for j in xrange(64)] for i in xrange(rows)] # these are the defaults... # - note = 253 (0xFD) # - instrument = 0 # - volume = 255 (0xFF) # - effect type = 0 # - effect parameter = 0 def write(self, fp): self.dopack() fp.write(struct.pack("<HH", len(self.packbuf), len(self.data))) fp.write("AtBu") fp.write(''.join(chr(v) for v in self.packbuf)) def dopack(self): self.packbuf = [] lc = [[253,0,255,0,0] for j in xrange(64)] lm = [0x00 for j in xrange(64)] for l in self.data: for i in xrange(64): c = l[i] m = 0x00 if c[0] != 253: m |= 0x10 if c[0] == lc[i][0] else 0x01 if c[1] != 0: m |= 0x20 if c[1] == lc[i][1] else 0x02 if c[2] != 255: m |= 0x40 if c[2] == lc[i][2] else 0x04 if c[3] != 0 or c[4] != 0: m |= 0x80 if c[3] == lc[i][3] and c[4] == lc[i][4] else 0x08 v = i+1 if m != lm[i]: v |= 0x80 self.packbuf.append(v) if v & 0x80: self.packbuf.append(m) lm[i] = m if m & 0x01: self.packbuf.append(c[0]) lc[i][0] = c[0] if m & 0x02: self.packbuf.append(c[1]) lc[i][1] = c[1] if m & 0x04: self.packbuf.append(c[2]) lc[i][2] = c[2] if m & 0x08: self.packbuf.append(c[3]) self.packbuf.append(c[4]) lc[i][3] = c[3] lc[i][4] = c[4] self.packbuf.append(0) ######################### # # # BLEEPS 'N' BLOOPS # # # ######################### # YES! We actually have an almost decent sample synth! class Sample_KS(Sample): name = "Karplus-Strong synth" flags = IT_BASEFLG_SAMPLE | IT_SAMPLE_LOOP boost = 1.0 def generate(self, freq, decay, filtn, length_sec, nfrqmul = 1.0, filt0 = 1.0, filtf = 1.0, filtdc = 0.01): # generate waveform delay = int(SMP_FREQ/freq) noise = [0 for i in xrange(delay)] nfrqctr = 1.0 nfrqval = 0.0 intlen = int(SMP_FREQ*length_sec) assert intlen >= delay, "KS sample length cannot be less than its period" # DC filter dq = 0.0 # prefilter with filt0 qn = 0.0 q = 0.0 dl = -0.001 dh = 0.001 nvolcur = 1.0 nvoldec = 1.0 / (decay * SMP_FREQ) nlfsr = random.randint(1,0x7FFF) # generate up to "length" samples qf = 0.0 #noise[-1] l = [] i = 0 for j in xrange(intlen): #ov = noise[i] if nvolcur > 0.0: if nfrqctr >= 1.0: #nfrqval = random.random()*2.0-1.0 nfrqval = (1.0 if (nlfsr & 1) else -1.0) * 1.0 # skip a value to balance it a bit better if nlfsr == 1: nlfsr = 0x4000 if nlfsr & 1: nlfsr = (nlfsr>>1) ^ 0x6000 else: nlfsr >>= 1 nfrqctr -= 1.0 nfrqctr += nfrqmul qn = (nfrqval * nvolcur - qn) * filt0 + qn nvolcur -= nvoldec noise[i] += qn ov = q = noise[i] = (noise[i] - q) * filtn + q qf = (ov - qf) * filtf + qf dq += (qf - dq) * filtdc l.append(qf - dq) i = (i+1) % delay # set stuff self.lpend = intlen self.lpbeg = intlen - delay # return return l class Sample_Kicker(Sample): name = "Kicker" flags = IT_BASEFLG_SAMPLE boost = 1.8 def generate(self): vol_noise = 0.8 vol_sine = 1.2 vol_noise_decay = 1.0 / (SMP_FREQ * 0.01) vol_sine_decay = 1.0 / (SMP_FREQ * 0.2) q_noise = 0.0 kickmul = math.pi*2.0*150.0/SMP_FREQ offs_sine = 0.0 offs_sine_speed = kickmul offs_sine_decay = 0.9995 intlen = int(SMP_FREQ*0.25) l = [] for j in xrange(intlen): sv = max(-0.7,min(0.7,math.sin(offs_sine))) offs_sine += offs_sine_speed offs_sine_speed *= offs_sine_decay nv = (random.random()*2.0-1.0) q_noise += (nv - q_noise) * 0.1 nv = q_noise l.append(nv*vol_noise + sv*vol_sine) vol_noise -= vol_noise_decay if vol_noise < 0.0: vol_noise = 0.0 vol_sine -= vol_sine_decay if vol_sine < 0.0: vol_sine = 0.0 return l class Sample_NoiseHit(Sample): name = "Noise hit generator" flags = IT_BASEFLG_SAMPLE boost = 1.0 def generate(self, decay, filtl = 1.0, filth = 0.0): vol_noise = 1.0 vol_noise_decay = 1.0 / (SMP_FREQ * decay) ql = 0.0 qh = 0.0 intlen = int(SMP_FREQ*decay) l = [] for j in xrange(intlen): nv = (random.random()*2.0-1.0) ql += (nv - ql) * filtl qh += (nv - qh) * filth nv = ql - qh l.append(nv*vol_noise) vol_noise -= vol_noise_decay if vol_noise < 0.0: vol_noise = 0.0 return l class Sample_Hoover(Sample): name = "Hoover" flags = IT_BASEFLG_SAMPLE | IT_SAMPLE_LOOP boost = 1.0 def generate(self, freq): oscfrq = [ int(freq*(v + v*(random.random()*2.0-1.0)*0.002))/float(SMP_FREQ) for v in [0.25, 0.5, 1.0, 2.0] ] oscvibspeed = [float(random.randint(1,5))*2.0*math.pi/SMP_FREQ for i in xrange(4)] oscvibdepth = [0.5,0.4,0.2,0.2] oscoffs = [random.random() for i in xrange(4)] oscviboffs = [random.random() for i in xrange(4)] oscvol = [1.0, 1.0, 1.0, 0.55] attack = 0.03 atkvol = 0.0 atkspd = 1.0/(attack*SMP_FREQ) intlen = int(SMP_FREQ*(attack+1.0)) l = [] for i in xrange(intlen): v = 0.0 for j in xrange(4): ov = oscoffs[j]*2.0-1.0 vib = math.sin(oscviboffs[j])*oscvibdepth[j] oscoffs[j] += oscfrq[j] * (2.0**(vib/12.0)) if oscoffs[j] > 1.0: oscoffs[j] %= 1.0 oscviboffs[j] += oscvibspeed[j] v += oscvol[j]*ov atkvol += atkspd if atkvol > 1.0: atkvol = 1.0 l.append(v*atkvol) self.lpend = intlen self.lpbeg = int(intlen - SMP_FREQ*1.0 + 0.5) return l ########################## # # # RANDOCHORD FACTORY # # # ########################## class Key: def __init__(self): pass def get_base_note(self): return 60 def has_note(self, n): return True class Key_GenericOctave(Key): MASK = [True]*12 def __init__(self, basenote): self.basenote = basenote def get_base_note(self): return self.basenote def has_note(self, n): return self.MASK[(n-self.basenote)%12] class Key_Major(Key_GenericOctave): MASK = [ True,False, True,False, True, True,False, True,False, True,False, True, ] class Key_Minor(Key_GenericOctave): MASK = [ True,False, True, True,False, True,False, True, True,False, True,False, ] class Key_Major_Pentatonic(Key_GenericOctave): MASK = [ True,False, True,False, True, False,False, True,False, True,False, False, ] class Key_Minor_Pentatonic(Key_GenericOctave): MASK = [ True,False, False, True,False, True,False, True, False,False, True,False, ] class Strategy: def __init__(self, *args, **kwargs): self.setup(*args,**kwargs) self.gens = [] self.chused = 0 def setup(self, *args, **kwargs): self.key = Key_GenericOctave(60) def gen_add(self, gen): self.gens.append((self.chused,gen)) self.chused += gen.size() def get_key(self): return self.key class Strategy_Main(Strategy): def setup(self, basenote, keytype, patsize, blocksize, *args, **kwargs): self.basenote = basenote self.keytype = keytype self.patsize = patsize self.blocksize = blocksize self.key = keytype(basenote) self.pats = [] self.rspeed = 2**random.randint(2,3) self.rhythm = [3]+[0]*(self.rspeed-1)+[1]+[0]*(self.rspeed-1) self.rhythm *= (self.patsize//len(self.rhythm)) self.pat_idx = 0 self.newkseq() def newkseq(self): self.kseq = random.choice({ Key_Minor: [ [(0,Key_Minor),(-4,Key_Major),(5,Key_Major),(-2,Key_Major)], [(0,Key_Minor),(-2,Key_Major),(-4,Key_Major),(-5,Key_Minor)], ], Key_Major: [ [(0,Key_Major),(-5,Key_Major),(-3,Key_Minor),(5,Key_Major)], [(0,Key_Major),(0,Key_Major),(-7,Key_Minor),(-5,Key_Major)], ], }[self.keytype]) self.kseq2 = random.choice({ Key_Minor: [ [(3,Key_Major),(0,Key_Minor),(-4,Key_Major),(-2,Key_Major)], [(-4,Key_Major),(-2,Key_Major),(0,Key_Minor),(-2,Key_Major)], ], Key_Major: [ [(2,Key_Minor),(0,Key_Major),(-3,Key_Minor),(0,Key_Major)], [(-3,Key_Minor),(-5,Key_Major),(-7,Key_Major),(-5,Key_Major)], ], }[self.keytype]) def get_pattern(self): pat = Pattern(self.patsize) kseq = self.kseq2[:] if self.pat_idx % 8 >= 4 else self.kseq[:] for i in xrange(0,self.patsize,self.blocksize): k,kt = kseq.pop(0) kchord = kt(self.basenote+k) for chn,gen in self.gens: gen.apply_notes(chn, pat, self, self.rhythm, i, self.blocksize, self.key, kchord) kseq.append(k) self.pats.append(pat) self.pat_idx += 1 return pat def get_key(self): return self.key class Generator: def __init__(self, *args, **kwargs): pass def size(self): return 1 def apply_notes(self, chn, pat, strat, rhythm, bbeg, blen, kroot, kchord): pass class Generator_Bass(Generator): def __init__(self, smp, *args, **kwargs): self.smp = smp def size(self): return 1 def apply_notes(self, chn, pat, strat, rhythm, bbeg, blen, kroot, kchord): base = kchord.get_base_note() leadin = 0 for row in xrange(bbeg, bbeg+blen, 1): if rhythm[row]&1: n = base-12 if random.random() < 0.5 else base pat.data[row][chn] = [n, self.smp, 255, 0, 0] if leadin != 0 and random.random() < 0.4: gran = 2 count = 1 #if random.random() < 0.2: # gran = 1 if leadin > gran*2 and random.random() < 0.4: count += 1 if leadin > gran*3 and random.random() < 0.4: count += 1 for j in xrange(count): pat.data[row-(j+1)*gran][chn] = [ base+12 if random.random() < 0.5 else base ,self.smp ,0xFF ,ord('S')-ord('A')+1 ,0xC0 + random.randint(1,2) ] if random.random() < 0.2: pat.data[row][chn][0] += 12 if random.random() < 0.4: pat.data[row][chn][3] = ord('S')-ord('A')+1 pat.data[row][chn][4] = 0xC0 + random.randint(1,2) else: pat.data[row+2][chn] = [254, self.smp, 255, 0, 0] leadin = 0 else: leadin += 1 class Generator_AmbientMelody(Generator): MOTIF_PROSPECTS = [ # 1-steps [1], [2], [3], # 2-steps [1,3], [2,3], [2,4], # niceties [5,7], [5,12], [7,12], [7], [5], [12], # 3-chords [3,7], [4,7], # 4-chords [3,7,10], [3,7,11], [4,7,10], [4,7,11], # turns and stuff [1,0], [2,0], [1,-1,0], [1,-2,0], [2,-1,0], [2,-2,0], ] def __init__(self, smp, *args, **kwargs): self.smp = smp self.beatrow = 2**random.randint(2,3) self.lq = 60 self.ln = -1 self.mq = [] self.nq = [] def size(self): return 1 def apply_notes(self, chn, pat, strat, rhythm, bbeg, blen, kroot, kchord): base = kchord.get_base_note() if bbeg == 0: self.lq = base self.ln = -1 self.mq = [] self.nq = [] pat.data[bbeg][chn] = [self.lq, self.smp, 255, 0, 0] self.nq.append(bbeg) #self.ln = self.lq stabbing = False row = bbeg while row < bbeg+blen: if pat.data[row][chn][0] != 253: self.nq.append(row) row += self.beatrow continue q = 60 if self.mq: if stabbing or random.random() < 0.9: n = self.mq.pop(0) self.ln = n pat.data[row][chn] = [n, self.smp, 255, 0, 0] self.nq.append(row) if not self.mq: self.lq = n if random.random() < 0.2 or stabbing: row += self.beatrow // 2 stabbing = not stabbing else: row += self.beatrow else: row += self.beatrow elif row-bbeg >= 2*self.beatrow and random.random() < 0.3: backstep = random.randint(3,min(10,row//(self.beatrow//2)))*(self.beatrow//2) print "back", row, backstep for i in xrange(backstep): if row-bbeg >= blen: break pat.data[row][chn] = pat.data[row-backstep][chn][:] n = pat.data[row][chn][0] if n != 253: self.ln = self.lq = n row += 1 else: if len(self.nq) > 5: self.nq = self.nq[-5:] while True: kk = False while True: rbi = random.choice(self.nq) rbn = pat.data[rbi][chn][0] if self.ln != -1 and abs(rbn-self.ln) > 12: continue break m = None print rbn for j in xrange(20): m = random.choice(self.MOTIF_PROSPECTS) down = random.random() < (8.0+(self.ln-base))/8.0 if self.ln != -1 else 0.5 print m,rbn,down,base if down: m = [rbn-v for v in m] else: m = [rbn+v for v in m] if self.ln == m[0]: continue k = True for v in m: if not (kchord.has_note(v) and kroot.has_note(v)): k = False break if k: kk = True break if kk: break if rbn != self.ln: m = [rbn] + m print m self.mq += m # repeat at same row class Generator_Drums(Generator): def __init__(self, s_kick, s_hhc, s_hho, s_snare, *args, **kwargs): self.s_kick = s_kick self.s_hhc = s_hhc self.s_hho = s_hho self.s_snare = s_snare self.beatrow = 2**random.randint(1,2) def size(self): return 3 def apply_notes(self, chn, pat, strat, rhythm, bbeg, blen, kroot, kchord): for row in xrange(bbeg,bbeg+blen,self.beatrow): vol = 255 smp = self.s_hhc if not (rhythm[row]&2): if (row&8): vol = 48 if (row&4): vol = 32 if (row&2): vol = 16 if (row&1): vol = 8 if random.random() < 0.2: smp = self.s_hho pat.data[row][chn] = [60, smp, vol, 0, 0] for row in xrange(bbeg,bbeg+blen,2): if random.random() < 0.1 and not rhythm[row]&1: pat.data[row][chn+1] = [60,self.s_kick,255,0,0] did_kick = False for row in xrange(bbeg,bbeg+blen,1): if rhythm[row]&1: if did_kick: pat.data[row][chn+2] = [60,self.s_snare,255,0,0] else: if random.random() < 0.1: pat.data[row+2][chn+1] = [60,self.s_kick,255,0,0] else: pat.data[row][chn+1] = [60,self.s_kick,255,0,0] did_kick = not did_kick ################# # # # BOOTSTRAP # # # ################# MIDDLE_C = 220.0 * (2.0 ** (3.0 / 12.0)) print "Creating module" itf = ITFile() print "Generating samples" # these could do with some work, they're a bit crap ATM --GM # note: commented a couple out as they use a fair whack of space and are unused. SMP_GUITAR = itf.smp_add(Sample_KS(name = "KS Guitar", freq = MIDDLE_C/2, decay = 0.005, nfrqmul = 1.0, filt0 = 0.1, filtn = 0.6, filtf = 0.0004, length_sec = 1.0)) SMP_BASS = itf.smp_add(Sample_KS(name = "KS Bass", freq = MIDDLE_C/4, decay = 0.005, nfrqmul = 0.5, filt0 = 0.2, filtn = 0.2, filtf = 0.005, length_sec = 0.7)) #SMP_PIANO = itf.smp_add(Sample_KS(name = "KS Piano", freq = MIDDLE_C, decay = 0.07, nfrqmul = 0.02, filtdc = 0.1, filt0 = 0.09, filtn = 0.6, filtf = 0.4, length_sec = 1.0)) #SMP_HOOVER = itf.smp_add(Sample_Hoover(name = "Hoover", freq = MIDDLE_C)) SMP_KICK = itf.smp_add(Sample_Kicker(name = "Kick")) SMP_HHC = itf.smp_add(Sample_NoiseHit(name = "NH Hihat Closed", gvol = 32, decay = 0.03, filtl = 0.99, filth = 0.20)) SMP_HHO = itf.smp_add(Sample_NoiseHit(name = "NH Hihat Open", gvol = 32, decay = 0.5, filtl = 0.99, filth = 0.20)) SMP_SNARE = itf.smp_add(Sample_NoiseHit(name = "NH Snare", decay = 0.12, filtl = 0.15, filth = 0.149)) print "Generating patterns" strat = Strategy_Main(random.randint(50,50+12-1)+12, Key_Minor if random.random() < 0.6 else Key_Major, 128, 32) strat.gen_add(Generator_Drums(s_kick = SMP_KICK, s_snare = SMP_SNARE, s_hhc = SMP_HHC, s_hho = SMP_HHO)) strat.gen_add(Generator_AmbientMelody(smp = SMP_GUITAR)) strat.gen_add(Generator_Bass(smp = SMP_BASS)) for i in xrange(6): itf.ord_add(itf.pat_add(strat.get_pattern())) print "Saving" # pick a random name RN_NOUNS = [ ("cat","cats"),("kitten","kittens"), ("dog","dogs"),("puppy","puppies"), ("elf","elves"),("knight","knights"), ("wizard","wizards"),("witch","witches"),("leprechaun","leprechauns"), ("dwarf","dwarves"),("golem","golems"),("troll","trolls"), ("city","cities"),("castle","castles"),("town","towns"),("village","villages"), ("journey","journeys"),("flight","flights"),("place","places"), ("bird","birds"), ("ocean","oceans"),("sea","seas"), ("boat","boats"),("ship","ships"), ("whale","whales"), ("brother","brothers"),("sister","sisters"), ("viking","vikings"),("ghost","ghosts"), ("garden","gardens"),("park","parks"), ("forest","forests"),("ogre","ogres"), ("sweet","sweets"),("candy","candies"), ("hand","hands"),("foot","feet"),("arm","arms"),("leg","legs"), ("body","bodies"),("head","heads"),("wing","wings"), ("gorilla","gorillas"),("ninja","ninjas"),("bear","bears"), ("vertex","vertices"),("matrix","matrices"),("simplex","simplices"), ("shape","shapes"), ("apple","apples"),("pear","pears"),("banana","bananas"), ("orange","oranges"), ("demoscene","demoscenes"), ("sword","swords"),("shield","shields"),("gun","guns"),("cannon","cannons"), ("report","reports"),("sign","signs"),("year","years"),("age","ages"), ("blood","bloods"),("breed","breeds"),("monument","monuments"), ("cheese","cheeses"),("horse","horses"),("sheep","sheep"),("fish","fish"), ("dock","docks"),("tube","tubes"),("road","roads"),("path","paths"), ("tunnel","tunnels"),("retort","retorts"), ("toaster","toasters"),("goat","goats"), ("tofu","tofus"),("vine","vines"),("branch","branches"), ] RN_ADJECTIVES = [ "tense","grand","pleasing","absurd","offensive","crazed", "magic","lovely","tired","lively","tasty","jealous", "red","orange","yellow","green","blue","purple","pink","brown", "white","black","cheap","blazed","biased","sweet", "invisible","hidden","secret","long","short","tall","broken", "random","fighting","hunting","eating","drinking","drunk", "weary","walking","running","flying","strong","weak", "woeful","tearful","rich","poor","awoken","sacred", ] RN_VERBS = [ # TODO ] RN_PATTERNS = [ "the (n[0])'s (n[0,1])", "(N[0])'s (n[0,1])", "(n[0,1]) of (N[0,1])", "on the (n[0])'s (n[0,1])", "(n[0,1]) of the (n[0,1])", "the (a) (n[0,1])", "(A) (n[0])", "(a) (n[1])", "(a) and (a)", "(N[0,1]) and (N[0,1])", ] def randoname(): pat = random.choice(RN_PATTERNS) while "(" in pat: ps, po, pp = pat.partition("(") p, pc, pn = pp.partition(")") assert pc == ")", "expected ')' in name pattern" p = random.choice(p.split("|")) if p.startswith("n") or p.startswith("N"): idx = random.choice(eval(p[1:])) w = random.choice(RN_NOUNS)[idx] if idx in [0] and p.startswith("N"): if w[0] in "aeiouAEIOU": p = "an " + w else: p = "a " + w else: p = w elif p.startswith("a") or p.startswith("A"): w = random.choice(RN_ADJECTIVES) if p.startswith("A"): if w[0] in "aeiouAEIOU": p = "an " + w else: p = "a " + w else: p = w else: raise Exception("invalid name pattern type") pat = ps + p + pn return pat name = randoname() itf.name = name fname = "bu-%s.it" % name.replace(" ","-").replace("'","") if len(sys.argv) > 1: fname = sys.argv[1] itf.save(fname) print "Done" print "Saved as \"%s\"" % fname
"""Support for the Philips Hue sensors as a platform.""" import asyncio from datetime import timedelta import logging from time import monotonic import async_timeout from homeassistant.components import hue from homeassistant.exceptions import NoEntitySpecifiedError from homeassistant.helpers.event import async_track_point_in_utc_time from homeassistant.util.dt import utcnow CURRENT_SENSORS = 'current_sensors' SENSOR_MANAGER_FORMAT = '{}_sensor_manager' _LOGGER = logging.getLogger(__name__) def _device_id(aiohue_sensor): # Work out the shared device ID, as described below device_id = aiohue_sensor.uniqueid if device_id and len(device_id) > 23: device_id = device_id[:23] return device_id async def async_setup_entry(hass, config_entry, async_add_entities, binary=False): """Set up the Hue sensors from a config entry.""" bridge = hass.data[hue.DOMAIN][config_entry.data['host']] hass.data[hue.DOMAIN].setdefault(CURRENT_SENSORS, {}) sm_key = SENSOR_MANAGER_FORMAT.format(config_entry.data['host']) manager = hass.data[hue.DOMAIN].get(sm_key) if manager is None: manager = SensorManager(hass, bridge) hass.data[hue.DOMAIN][sm_key] = manager manager.register_component(binary, async_add_entities) await manager.start() class SensorManager: """Class that handles registering and updating Hue sensor entities. Intended to be a singleton. """ SCAN_INTERVAL = timedelta(seconds=5) sensor_config_map = {} def __init__(self, hass, bridge): """Initialize the sensor manager.""" import aiohue from .binary_sensor import HuePresence, PRESENCE_NAME_FORMAT from .sensor import ( HueLightLevel, HueTemperature, LIGHT_LEVEL_NAME_FORMAT, TEMPERATURE_NAME_FORMAT) self.hass = hass self.bridge = bridge self._component_add_entities = {} self._started = False self.sensor_config_map.update({ aiohue.sensors.TYPE_ZLL_LIGHTLEVEL: { "binary": False, "name_format": LIGHT_LEVEL_NAME_FORMAT, "class": HueLightLevel, }, aiohue.sensors.TYPE_ZLL_TEMPERATURE: { "binary": False, "name_format": TEMPERATURE_NAME_FORMAT, "class": HueTemperature, }, aiohue.sensors.TYPE_ZLL_PRESENCE: { "binary": True, "name_format": PRESENCE_NAME_FORMAT, "class": HuePresence, }, }) def register_component(self, binary, async_add_entities): """Register async_add_entities methods for components.""" self._component_add_entities[binary] = async_add_entities async def start(self): """Start updating sensors from the bridge on a schedule.""" # but only if it's not already started, and when we've got both # async_add_entities methods if self._started or len(self._component_add_entities) < 2: return self._started = True _LOGGER.info('Starting sensor polling loop with %s second interval', self.SCAN_INTERVAL.total_seconds()) async def async_update_bridge(now): """Will update sensors from the bridge.""" await self.async_update_items() async_track_point_in_utc_time( self.hass, async_update_bridge, utcnow() + self.SCAN_INTERVAL) await async_update_bridge(None) async def async_update_items(self): """Update sensors from the bridge.""" import aiohue api = self.bridge.api.sensors try: start = monotonic() with async_timeout.timeout(4): await api.update() except (asyncio.TimeoutError, aiohue.AiohueException) as err: _LOGGER.debug('Failed to fetch sensor: %s', err) if not self.bridge.available: return _LOGGER.error('Unable to reach bridge %s (%s)', self.bridge.host, err) self.bridge.available = False return finally: _LOGGER.debug('Finished sensor request in %.3f seconds', monotonic() - start) if not self.bridge.available: _LOGGER.info('Reconnected to bridge %s', self.bridge.host) self.bridge.available = True new_sensors = [] new_binary_sensors = [] primary_sensor_devices = {} current = self.hass.data[hue.DOMAIN][CURRENT_SENSORS] # Physical Hue motion sensors present as three sensors in the API: a # presence sensor, a temperature sensor, and a light level sensor. Of # these, only the presence sensor is assigned the user-friendly name # that the user has given to the device. Each of these sensors is # linked by a common device_id, which is the first twenty-three # characters of the unique id (then followed by a hyphen and an ID # specific to the individual sensor). # # To set up neat values, and assign the sensor entities to the same # device, we first, iterate over all the sensors and find the Hue # presence sensors, then iterate over all the remaining sensors - # finding the remaining ones that may or may not be related to the # presence sensors. for item_id in api: if api[item_id].type != aiohue.sensors.TYPE_ZLL_PRESENCE: continue primary_sensor_devices[_device_id(api[item_id])] = api[item_id] # Iterate again now we have all the presence sensors, and add the # related sensors with nice names where appropriate. for item_id in api: existing = current.get(api[item_id].uniqueid) if existing is not None: self.hass.async_create_task( existing.async_maybe_update_ha_state()) continue primary_sensor = None sensor_config = self.sensor_config_map.get(api[item_id].type) if sensor_config is None: continue base_name = api[item_id].name primary_sensor = primary_sensor_devices.get( _device_id(api[item_id])) if primary_sensor is not None: base_name = primary_sensor.name name = sensor_config["name_format"].format(base_name) current[api[item_id].uniqueid] = sensor_config["class"]( api[item_id], name, self.bridge, primary_sensor=primary_sensor) if sensor_config['binary']: new_binary_sensors.append(current[api[item_id].uniqueid]) else: new_sensors.append(current[api[item_id].uniqueid]) async_add_sensor_entities = self._component_add_entities.get(False) async_add_binary_entities = self._component_add_entities.get(True) if new_sensors and async_add_sensor_entities: async_add_sensor_entities(new_sensors) if new_binary_sensors and async_add_binary_entities: async_add_binary_entities(new_binary_sensors) class GenericHueSensor: """Representation of a Hue sensor.""" should_poll = False def __init__(self, sensor, name, bridge, primary_sensor=None): """Initialize the sensor.""" self.sensor = sensor self._name = name self._primary_sensor = primary_sensor self.bridge = bridge async def _async_update_ha_state(self, *args, **kwargs): raise NotImplementedError @property def primary_sensor(self): """Return the primary sensor entity of the physical device.""" return self._primary_sensor or self.sensor @property def device_id(self): """Return the ID of the physical device this sensor is part of.""" return self.unique_id[:23] @property def unique_id(self): """Return the ID of this Hue sensor.""" return self.sensor.uniqueid @property def name(self): """Return a friendly name for the sensor.""" return self._name @property def available(self): """Return if sensor is available.""" return self.bridge.available and (self.bridge.allow_unreachable or self.sensor.config['reachable']) @property def swupdatestate(self): """Return detail of available software updates for this device.""" return self.primary_sensor.raw.get('swupdate', {}).get('state') async def async_maybe_update_ha_state(self): """Try to update Home Assistant with current state of entity. But if it's not been added to hass yet, then don't throw an error. """ try: await self._async_update_ha_state() except (RuntimeError, NoEntitySpecifiedError): _LOGGER.debug( "Hue sensor update requested before it has been added.") @property def device_info(self): """Return the device info. Links individual entities together in the hass device registry. """ return { 'identifiers': { (hue.DOMAIN, self.device_id) }, 'name': self.primary_sensor.name, 'manufacturer': self.primary_sensor.manufacturername, 'model': ( self.primary_sensor.productname or self.primary_sensor.modelid), 'sw_version': self.primary_sensor.swversion, 'via_hub': (hue.DOMAIN, self.bridge.api.config.bridgeid), } class GenericZLLSensor(GenericHueSensor): """Representation of a Hue-brand, physical sensor.""" @property def device_state_attributes(self): """Return the device state attributes.""" return { "battery_level": self.sensor.battery }
try: set except NameError: from sets import Set as set from django import template from django.core.paginator import Paginator, InvalidPage from django.conf import settings register = template.Library() DEFAULT_PAGINATION = getattr(settings, 'PAGINATION_DEFAULT_PAGINATION', 20) DEFAULT_WINDOW = getattr(settings, 'PAGINATION_DEFAULT_WINDOW', 4) DEFAULT_ORPHANS = getattr(settings, 'PAGINATION_DEFAULT_ORPHANS', 0) def do_autopaginate(parser, token): """ Splits the arguments to the autopaginate tag and formats them correctly. """ split = token.split_contents() as_index = None context_var = None for i, bit in enumerate(split): if bit == 'as': as_index = i break if as_index is not None: try: context_var = split[as_index + 1] except IndexError: raise template.TemplateSyntaxError("Context variable assignment " +\ "must take the form of {%% %r object.example_set.all ... as " +\ "context_var_name %%}" % split[0]) del split[as_index:as_index + 2] if len(split) == 2: return AutoPaginateNode(split[1]) elif len(split) == 3: return AutoPaginateNode(split[1], paginate_by=split[2], context_var=context_var) elif len(split) == 4: try: orphans = int(split[3]) except ValueError: raise template.TemplateSyntaxError(u'Got %s, but expected integer.' % split[3]) return AutoPaginateNode(split[1], paginate_by=split[2], orphans=orphans, context_var=context_var) else: raise template.TemplateSyntaxError('%r tag takes one required ' + \ 'argument and one optional argument' % split[0]) class AutoPaginateNode(template.Node): """ Emits the required objects to allow for Digg-style pagination. First, it looks in the current context for the variable specified, and using that object, it emits a simple ``Paginator`` and the current page object into the context names ``paginator`` and ``page_obj``, respectively. It will then replace the variable specified with only the objects for the current page. .. note:: It is recommended to use *{% paginate %}* after using the autopaginate tag. If you choose not to use *{% paginate %}*, make sure to display the list of available pages, or else the application may seem to be buggy. """ def __init__(self, queryset_var, paginate_by=DEFAULT_PAGINATION, orphans=DEFAULT_ORPHANS, context_var=None): self.queryset_var = template.Variable(queryset_var) if isinstance(paginate_by, int): self.paginate_by = paginate_by else: self.paginate_by = template.Variable(paginate_by) self.orphans = orphans self.context_var = context_var def render(self, context): key = self.queryset_var.var value = self.queryset_var.resolve(context) if isinstance(self.paginate_by, int): paginate_by = self.paginate_by else: paginate_by = self.paginate_by.resolve(context) paginator = Paginator(value, paginate_by, self.orphans) try: page_obj = paginator.page(context['request'].page) except InvalidPage: context[key] = [] context['invalid_page'] = True return u'' if self.context_var is not None: context[self.context_var] = page_obj.object_list else: context[key] = page_obj.object_list context['paginator'] = paginator context['page_obj'] = page_obj return u'' def paginate(context, window=DEFAULT_WINDOW): """ Renders the ``pagination/pagination.html`` template, resulting in a Digg-like display of the available pages, given the current page. If there are too many pages to be displayed before and after the current page, then elipses will be used to indicate the undisplayed gap between page numbers. Requires one argument, ``context``, which should be a dictionary-like data structure and must contain the following keys: ``paginator`` A ``Paginator`` or ``QuerySetPaginator`` object. ``page_obj`` This should be the result of calling the page method on the aforementioned ``Paginator`` or ``QuerySetPaginator`` object, given the current page. This same ``context`` dictionary-like data structure may also include: ``getvars`` A dictionary of all of the **GET** parameters in the current request. This is useful to maintain certain types of state, even when requesting a different page. """ try: paginator = context['paginator'] page_obj = context['page_obj'] page_range = paginator.page_range # First and last are simply the first *n* pages and the last *n* pages, # where *n* is the current window size. first = set(page_range[:window]) last = set(page_range[-window:]) # Now we look around our current page, making sure that we don't wrap # around. current_start = page_obj.number-1-window if current_start < 0: current_start = 0 current_end = page_obj.number-1+window if current_end < 0: current_end = 0 current = set(page_range[current_start:current_end]) pages = [] # If there's no overlap between the first set of pages and the current # set of pages, then there's a possible need for elusion. if len(first.intersection(current)) == 0: first_list = list(first) first_list.sort() second_list = list(current) second_list.sort() pages.extend(first_list) diff = second_list[0] - first_list[-1] # If there is a gap of two, between the last page of the first # set and the first page of the current set, then we're missing a # page. if diff == 2: pages.append(second_list[0] - 1) # If the difference is just one, then there's nothing to be done, # as the pages need no elusion and are correct. elif diff == 1: pass # Otherwise, there's a bigger gap which needs to be signaled for # elusion, by pushing a None value to the page list. else: pages.append(None) pages.extend(second_list) else: unioned = list(first.union(current)) unioned.sort() pages.extend(unioned) # If there's no overlap between the current set of pages and the last # set of pages, then there's a possible need for elusion. if len(current.intersection(last)) == 0: second_list = list(last) second_list.sort() diff = second_list[0] - pages[-1] # If there is a gap of two, between the last page of the current # set and the first page of the last set, then we're missing a # page. if diff == 2: pages.append(second_list[0] - 1) # If the difference is just one, then there's nothing to be done, # as the pages need no elusion and are correct. elif diff == 1: pass # Otherwise, there's a bigger gap which needs to be signaled for # elusion, by pushing a None value to the page list. else: pages.append(None) pages.extend(second_list) else: differenced = list(last.difference(current)) differenced.sort() pages.extend(differenced) to_return = { 'pages': pages, 'page_obj': page_obj, 'paginator': paginator, 'is_paginated': paginator.count > paginator.per_page, } if 'request' in context: getvars = context['request'].GET.copy() if 'page' in getvars: del getvars['page'] if len(getvars.keys()) > 0: to_return['getvars'] = "&%s" % getvars.urlencode() else: to_return['getvars'] = '' return to_return except KeyError, AttributeError: return {} register.inclusion_tag('pagination/pagination.html', takes_context=True)(paginate) register.tag('autopaginate', do_autopaginate)
#!/usr/bin/env python2.7 import logging import sys import math import numpy as np import scipy from sklearn.cluster import MiniBatchKMeans, KMeans from sklearn.metrics import euclidean_distances import datetime #import good_data # 40'000: Submission 2952, score: 740.608811745 => 12 minutes # 55'000: Submission: 2953, score: 739.711630341 => 20 minutes # 65'000: Submission: 2954, score: 739.300944969 => 20 minutes # 65'000: Submission: 2957, score: 739.690196805 => 15 minutes, magic * 2 # 65'000: Submission: 2958, score: 738.644914845 => 19 minutes, magic / 2 # 75'000: Submission: 2955, score: 738.478742513 => 19 minutes # 85'000: Submission: 2956, score: FAILED => FAILED # 95'000: Submission: 2959, score: FAILED => FAILED #100'000: Submission: 2960, score: FAILED => FAILED # 80'000: Submission: 2961, score: 738.669749628 => 25 minutes class Helper: def __init__(self): pass @staticmethod def dist_func(center, point): return euclidean_distances(center, point, squared=True) class ClusterCenter(): def __init__(self, center): self.center = center self.points = [] self.dist_sum = None def add_point(self, point): self.points.append(point) self.dist_sum = None def dist_point_sum(self): if self.dist_sum is None: self.dist_sum = 0.0 for point in self: self.dist_sum += Helper.dist_func(self.center, point) return self.dist_sum def __len__(self): return len(self.points) def __getitem__(self, item): return self.points[item] def get_half_farthest_points(self): dist_points = [[Helper.dist_func(self.center, p), p] for p in self.points] sorted_dist_points = sorted(dist_points, key=lambda dist_point: dist_point[0]) to_keep = len(self.points) / 2 return [dist_point[1] for dist_point in sorted_dist_points][0:to_keep] class DataPoint(): def __init__(self, point, cluster): self.point = point self.cluster = cluster self.cluster.add_point(point) self.q = None self.dp_sum = None def calc_sampling_weight(self): if self.q is None: # Formula slide 33, dm-09 center_dist_ratio = 1.0 if Helper.dist_func(self.cluster.center, self.point) != 0.0: center_dist_ratio = Helper.dist_func(self.cluster.center, self.point) / self.cluster.dist_point_sum() self.q = np.ceil( (5.0 / len(self.cluster)) + center_dist_ratio ) return self.q def calc_sampling_probability(self): return self.calc_sampling_weight() / self.dp_sum def calc_weight(self, out_per_mapper): return 1.0 / self.calc_sampling_weight() / out_per_mapper class Mapper: def __init__(self): total_rows_in_reducer, mappers = [8000, 15] if "--local" in sys.argv else [75000, 300] self.no_clusters = 200 self.out_per_mapper = total_rows_in_reducer / mappers self.written = 0 self.num_per_mapper = 6667 self.avg_cluster_size = None self.keep_ratio = None self.cluster_centers = None self.cluster_center_points = None self.data_points = None def run(self): self.data = self.read_input() self.num_per_mapper = len(self.data) self.avg_cluster_size = float(self.num_per_mapper) / float(self.no_clusters) self.keep_ratio = float(self.out_per_mapper) / float(self.num_per_mapper) np.random.shuffle(self.data) self.cluster_center_points = self.build_coresets() self.cluster_centers = [ClusterCenter(c) for c in self.cluster_center_points] self.sample_points() #logging.warn("Written %i" % self.written) #logging.warn(self.out_per_mapper) def read_input(self): reader = sys.stdin if "--read_from_file" in sys.argv: index = int(sys.argv[1]) return np.load("../../../1-data/training.npz")['arr_0'][ ((index - 1) * self.num_per_mapper):(index * self.num_per_mapper)] arr = [] for line in reader: arr.append(np.fromstring(line, dtype=np.float64, sep=' ')) return np.array(arr) def write_feature(self, row, weight): print("1\t%f\t%s" % (weight, " ".join(map(str, row)))) self.written += 1 def can_write_more_features(self): return self.written < self.out_per_mapper def cluster_center(self, cluster_index): return self.cluster_centers[cluster_index] def build_coresets(self): # The number of elements to take into the coreset at each iteration # should be 10 * d * k * ln(1/epsilon) = 10 * 750 * 200 * ln(1/0.1) = HUGE!? # Hmm... # From: http://www.mit.edu/~michaf/Code/SVDCoresetAlg.m: "Should be equal to k / epsilon^2" # k / epsilon^2 # for epsilon = 0.99: 200/(0.99)^2 = 205 # for epsilon = 0.5: 200/(0.5)^2 = 800 # for epsilon = 0.4: 200/(0.4)^2 = 1250 # for epsilon = 0.3: 200/(0.3)^2 = 2223 # for epsilon = 0.2: 200/(0.2)^2 = 5000 # for epsilon = 0.1: 200/(0.1)^2 = 20000 # for epsilon = 0.05: 200/(0.05)^2 = 80000 # => to have at most 60'000 dp's at the reducer, chose at most 200 per mapper => gives an epsilon = 0.99?? # => have to merge coresets at the reducer! # TODO: use higher value here, and merge coresets at reducer magic_constant = int(self.out_per_mapper / np.log2(len(self.data)) + 1) # self.data is shuffled already => it's ok to take the first n points for uniform sampling dat = self.data.tolist() coreset = [] while len(dat) > 0: coreset_part = dat[0:magic_constant] coreset += coreset_part dat = np.delete(dat, range(0, min(magic_constant, len(dat))), axis=0) dat = self.remove_half_nearest_points(coreset_part, dat) return coreset def sample_points(self): k = KMeans(n_clusters=self.no_clusters) k.cluster_centers_ = np.array(self.cluster_center_points) assigned_clusters = k.predict(np.array(self.data)) self.cluster_centers = [ClusterCenter(c) for c in self.cluster_center_points] self.data_points = [DataPoint(self.data[i], self.cluster_centers[assigned_clusters[i]]) for i in range(len(self.data))] dp_sum = np.sum([dp.calc_sampling_weight() for dp in self.data_points]) / self.out_per_mapper for dp in self.data_points: dp.dp_sum = dp_sum #logging.warn("Tot!") #logging.warn(sum([dp.calc_sampling_probability() for dp in self.data_points])) #logging.error(len(self.data_points)) while self.can_write_more_features(): np.random.shuffle(self.data_points) for dp in self.data_points: if not self.can_write_more_features(): return dp.dp_sum = dp_sum if np.random.sample() < dp.calc_sampling_probability(): self.write_feature(dp.point, dp.calc_weight(self.out_per_mapper)) def remove_half_nearest_points(self, center_points, data): k = KMeans(n_clusters=self.no_clusters) k.cluster_centers_ = np.array(center_points) assigned_clusters = k.predict(np.array(data)) clusters = [ClusterCenter(c) for c in center_points] for i in range(0, len(assigned_clusters)): clusters[assigned_clusters[i]].add_point(data[i]) ret = [] for c in clusters: ret += c.get_half_farthest_points() return ret if __name__ == "__main__": m = Mapper() m.run()
from itertools import chain import inspect from brushfire.core.query import BrushfireQuerySet from brushfire.core.exceptions import * from django.apps import apps from django.db import models from django.db.models.base import subclass_exception from django.db.models.options import Options from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned from django.utils import six import logging logger = logging.getLogger('brushfire.core') ################################################################################ # # Fields # ################################################################################ class BooleanField(models.BooleanField): pass # Numeric Fields class IntegerField(models.IntegerField): pass class FloatField(models.FloatField): pass class LongField(models.IntegerField): pass class DoubleField(models.FloatField): pass class TrieIntegerField(models.IntegerField): pass class TrieFloatField(models.FloatField): pass class TrieLongField(models.IntegerField): pass class TrieDoubleField(models.FloatField): pass # Date Fields class DateField(models.DateTimeField): pass class TrieDateField(models.DateTimeField): pass # Character Fields class TextField(models.TextField): pass class CharField(models.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 0xFFFFFFFF if kwargs.get('max_length', None) is None else kwargs['max_length'] super(CharField, self).__init__(*args, **kwargs) class StringField(CharField): pass class TextGeneralField(TextField):pass class TextEnField(TextField):pass class TextWsField(TextField):pass class NgramField(TextField):pass class EdgeNgramField(TextField):pass ################################################################################ # # Classes # ################################################################################ class BrushfireManager(object): use_for_related_fields = True def __init__(self, model): logging.debug("Configuring BrushfireManager for model %s", model) super(BrushfireManager, self).__init__() self.model = model setattr(model, 'objects', self) def get_query_set(self): logger.debug("Called get_query_set(), returning BrushfireQuerySet(self.model)") return BrushfireQuerySet(self.model) def __getattr__(self, name): """ Automatically proxy all method calls to the queryset. Allows Model.objects.{filter,get,all,none,order_by,etc}() without explicitly defining them all """ try: return self.__dict__[name] except KeyError: return getattr(self.get_query_set(), name) class BrushfireModelBase(type): def __new__(cls, name, bases, attrs): new_class = super(BrushfireModelBase, cls).__new__(cls, name, bases, attrs) parents = [b for b in bases if isinstance(b, BrushfireModelBase)] module = attrs.pop('__module__') attr_meta = attrs.pop('Meta', None) if not attr_meta: meta = getattr(new_class, 'Meta', None) else: meta = attr_meta app_config = apps.get_containing_app_config(module) setattr(new_class, 'objects', BrushfireManager(new_class)) if getattr(meta, 'app_label', None): label = meta.app_label elif app_config: label = app_config.label else: label = '__NONE__' new_class.add_to_class('_meta', Options(meta, **{'app_label':label})) new_class.add_to_class( 'DoesNotExist', subclass_exception( str('DoesNotExist'), (ObjectDoesNotExist,), module, attached_to=new_class)) new_class.add_to_class( 'MultipleObjectsReturned', subclass_exception( str('MultipleObjectsReturned'), (MultipleObjectsReturned,), module, attached_to=new_class)) if new_class._meta.proxy: raise BrushfireException, "BrushfireModels proxies not allowed." # add attributes to class for obj_name, obj in attrs.items(): new_class.add_to_class(obj_name, obj) new_fields = chain( new_class._meta.local_fields, new_class._meta.local_many_to_many, new_class._meta.virtual_fields ) field_names = {f.name for f in new_fields} new_class._meta.concrete_model = new_class # Do the appropriate setup for any model parents. for base in parents: if not hasattr(base, '_meta'): # Things without _meta aren't functional models, so they're # uninteresting parents. continue parent_fields = base._meta.local_fields + base._meta.local_many_to_many # Check for clashes between locally declared fields and those # on the base classes (we cannot handle shadowed fields at the # moment). for field in parent_fields: if field.name in field_names: raise FieldError( 'Local field %r in class %r clashes ' 'with field of similar name from ' 'base class %r' % (field.name, name, base.__name__) ) # Inherit virtual fields (like GenericForeignKey) from the parent # class for field in base._meta.virtual_fields: if base._meta.abstract and field.name in field_names: raise FieldError( 'Local field %r in class %r clashes ' 'with field of similar name from ' 'abstract base class %r' % (field.name, name, base.__name__) ) new_class.add_to_class(field.name, copy.deepcopy(field)) # Keep this stuff last new_class._prepare() # ModelBase calls this, not sure what it does or if we need it here. Need to investigate further. #new_class._meta.apps.register_model(new_class._meta.app_label, new_class) return new_class def add_to_class(cls, name, value): if not inspect.isclass(value) and hasattr(value, 'contribute_to_class'): value.contribute_to_class(cls, name) else: setattr(cls, name, value) def _prepare(cls): cls._meta._prepare(cls) class BrushfireModel(six.with_metaclass(BrushfireModelBase)): _deferred = False score = IntegerField() # These aren't inherited for some reason? It breaks the new migration commands class Meta: abstract = True # Stop Django from creating a BrushfireModel table managed = False # Stop Django from creating tables for subclasses @classmethod def check(cls, **kwargs): return [] def _get_pk_val(self, meta=None): if not meta: meta = self._meta return getattr(self, meta.pk.attname) def _set_pk_val(self, value): return setattr(self, self._meta.pk.attname, value) pk = property(_get_pk_val, _set_pk_val) def __init__(self, *args, **kwargs): for k,v in kwargs.items(): setattr(self, k, v)
# # Copyright (c) 2008-2015 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response from nssrc.com.citrix.netscaler.nitro.service.options import options from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util class dnsaddrec(base_resource) : """ Configuration for address type record resource. """ def __init__(self) : self._hostname = "" self._ipaddress = "" self._ttl = 0 self._type = "" self._vservername = "" self._authtype = "" self.___count = 0 @property def hostname(self) : """Domain name.<br/>Minimum length = 1. """ try : return self._hostname except Exception as e: raise e @hostname.setter def hostname(self, hostname) : """Domain name.<br/>Minimum length = 1 """ try : self._hostname = hostname except Exception as e: raise e @property def ipaddress(self) : """One or more IPv4 addresses to assign to the domain name.<br/>Minimum length = 1. """ try : return self._ipaddress except Exception as e: raise e @ipaddress.setter def ipaddress(self, ipaddress) : """One or more IPv4 addresses to assign to the domain name.<br/>Minimum length = 1 """ try : self._ipaddress = ipaddress except Exception as e: raise e @property def ttl(self) : """Time to Live (TTL), in seconds, for the record. TTL is the time for which the record must be cached by DNS proxies. The specified TTL is applied to all the resource records that are of the same record type and belong to the specified domain name. For example, if you add an address record, with a TTL of 36000, to the domain name example.com, the TTLs of all the address records of example.com are changed to 36000. If the TTL is not specified, the NetScaler appliance uses either the DNS zone's minimum TTL or, if the SOA record is not available on the appliance, the default value of 3600.<br/>Default value: 3600<br/>Maximum length = 2147483647. """ try : return self._ttl except Exception as e: raise e @ttl.setter def ttl(self, ttl) : """Time to Live (TTL), in seconds, for the record. TTL is the time for which the record must be cached by DNS proxies. The specified TTL is applied to all the resource records that are of the same record type and belong to the specified domain name. For example, if you add an address record, with a TTL of 36000, to the domain name example.com, the TTLs of all the address records of example.com are changed to 36000. If the TTL is not specified, the NetScaler appliance uses either the DNS zone's minimum TTL or, if the SOA record is not available on the appliance, the default value of 3600.<br/>Default value: 3600<br/>Maximum length = 2147483647 """ try : self._ttl = ttl except Exception as e: raise e @property def type(self) : """The address record type. The type can take 3 values: ADNS - If this is specified, all of the authoritative address records will be displayed. PROXY - If this is specified, all of the proxy address records will be displayed. ALL - If this is specified, all of the address records will be displayed.<br/>Possible values = ALL, ADNS, PROXY. """ try : return self._type except Exception as e: raise e @type.setter def type(self, type) : """The address record type. The type can take 3 values: ADNS - If this is specified, all of the authoritative address records will be displayed. PROXY - If this is specified, all of the proxy address records will be displayed. ALL - If this is specified, all of the address records will be displayed.<br/>Possible values = ALL, ADNS, PROXY """ try : self._type = type except Exception as e: raise e @property def vservername(self) : """Vitual server name. """ try : return self._vservername except Exception as e: raise e @property def authtype(self) : """Authentication type.<br/>Possible values = ALL, ADNS, PROXY. """ try : return self._authtype except Exception as e: raise e def _get_nitro_response(self, service, response) : """ converts nitro response into object and returns the object array in case of get request. """ try : result = service.payload_formatter.string_to_resource(dnsaddrec_response, response, self.__class__.__name__) if(result.errorcode != 0) : if (result.errorcode == 444) : service.clear_session(self) if result.severity : if (result.severity == "ERROR") : raise nitro_exception(result.errorcode, str(result.message), str(result.severity)) else : raise nitro_exception(result.errorcode, str(result.message), str(result.severity)) return result.dnsaddrec except Exception as e : raise e def _get_object_name(self) : """ Returns the value of object identifier argument """ try : if (self.hostname) : return str(self.hostname) return None except Exception as e : raise e @classmethod def add(cls, client, resource) : """ Use this API to add dnsaddrec. """ try : if type(resource) is not list : addresource = dnsaddrec() addresource.hostname = resource.hostname addresource.ipaddress = resource.ipaddress addresource.ttl = resource.ttl return addresource.add_resource(client) else : if (resource and len(resource) > 0) : addresources = [ dnsaddrec() for _ in range(len(resource))] for i in range(len(resource)) : addresources[i].hostname = resource[i].hostname addresources[i].ipaddress = resource[i].ipaddress addresources[i].ttl = resource[i].ttl result = cls.add_bulk_request(client, addresources) return result except Exception as e : raise e @classmethod def delete(cls, client, resource) : """ Use this API to delete dnsaddrec. """ try : if type(resource) is not list : deleteresource = dnsaddrec() if type(resource) != type(deleteresource): deleteresource.hostname = resource else : deleteresource.hostname = resource.hostname deleteresource.ipaddress = resource.ipaddress return deleteresource.delete_resource(client) else : if type(resource[0]) != cls : if (resource and len(resource) > 0) : deleteresources = [ dnsaddrec() for _ in range(len(resource))] for i in range(len(resource)) : deleteresources[i].hostname = resource[i] else : if (resource and len(resource) > 0) : deleteresources = [ dnsaddrec() for _ in range(len(resource))] for i in range(len(resource)) : deleteresources[i].hostname = resource[i].hostname deleteresources[i].ipaddress = resource[i].ipaddress result = cls.delete_bulk_request(client, deleteresources) return result except Exception as e : raise e @classmethod def get(cls, client, name="", option_="") : """ Use this API to fetch all the dnsaddrec resources that are configured on netscaler. """ try : if not name : obj = dnsaddrec() response = obj.get_resources(client, option_) else : if type(name) != cls : if type(name) is not list : obj = dnsaddrec() obj.hostname = name response = obj.get_resource(client, option_) else : if name and len(name) > 0 : response = [dnsaddrec() for _ in range(len(name))] obj = [dnsaddrec() for _ in range(len(name))] for i in range(len(name)) : obj[i] = dnsaddrec() obj[i].hostname = name[i] response[i] = obj[i].get_resource(client, option_) return response except Exception as e : raise e @classmethod def get_args(cls, client, args) : """ Use this API to fetch all the dnsaddrec resources that are configured on netscaler. # This uses dnsaddrec_args which is a way to provide additional arguments while fetching the resources. """ try : obj = dnsaddrec() option_ = options() option_.args = nitro_util.object_to_string_withoutquotes(args) response = obj.get_resources(client, option_) return response except Exception as e : raise e @classmethod def get_filtered(cls, client, filter_) : """ Use this API to fetch filtered set of dnsaddrec resources. filter string should be in JSON format.eg: "port:80,servicetype:HTTP". """ try : obj = dnsaddrec() option_ = options() option_.filter = filter_ response = obj.getfiltered(client, option_) return response except Exception as e : raise e @classmethod def count(cls, client) : """ Use this API to count the dnsaddrec resources configured on NetScaler. """ try : obj = dnsaddrec() option_ = options() option_.count = True response = obj.get_resources(client, option_) if response : return response[0].__dict__['___count'] return 0 except Exception as e : raise e @classmethod def count_filtered(cls, client, filter_) : """ Use this API to count filtered the set of dnsaddrec resources. Filter string should be in JSON format.eg: "port:80,servicetype:HTTP". """ try : obj = dnsaddrec() option_ = options() option_.count = True option_.filter = filter_ response = obj.getfiltered(client, option_) if response : return response[0].__dict__['___count'] return 0 except Exception as e : raise e class Authtype: ALL = "ALL" ADNS = "ADNS" PROXY = "PROXY" class Type: ALL = "ALL" ADNS = "ADNS" PROXY = "PROXY" class dnsaddrec_response(base_response) : def __init__(self, length=1) : self.dnsaddrec = [] self.errorcode = 0 self.message = "" self.severity = "" self.sessionid = "" self.dnsaddrec = [dnsaddrec() for _ in range(length)]
"""This package provides DockerImage for examining docker_build outputs.""" import abc import cStringIO import gzip import httplib import json import os import string import subprocess import sys import tarfile import tempfile from containerregistry.client import docker_creds from containerregistry.client import docker_name from containerregistry.client.v1 import docker_http import httplib2 # pylint: disable=unused-import class DockerImage(object): """Interface for implementations that interact with Docker images.""" __metaclass__ = abc.ABCMeta # For enforcing that methods are overriden. @abc.abstractmethod def top(self): """The layer id of the topmost layer.""" @abc.abstractmethod def repositories(self): """The json blob of tags, loaded as a dict.""" pass def parent(self, layer_id): """The layer of id of the parent of the provided layer, or None. Args: layer_id: the id of the layer whose parentage we're asking Returns: The identity of the parent layer, or None if the root. """ metadata = json.loads(self.json(layer_id)) if 'parent' not in metadata: return None return metadata['parent'] @abc.abstractmethod def json(self, layer_id): """The JSON metadata of the provided layer. Args: layer_id: the id of the layer whose metadata we're asking Returns: The raw json string of the layer. """ pass @abc.abstractmethod def layer(self, layer_id): """The layer.tar.gz blob of the provided layer id. Args: layer_id: the id of the layer for whose layer blob we're asking Returns: The raw blob string of the layer. """ pass @abc.abstractmethod def ancestry(self, layer_id): """The ancestry of the given layer, base layer first. Args: layer_id: the id of the layer whose ancestry we're asking Returns: The list of ancestor IDs, base first, layer_id last. """ pass # __enter__ and __exit__ allow use as a context manager. @abc.abstractmethod def __enter__(self): pass @abc.abstractmethod def __exit__(self, unused_type, unused_value, unused_traceback): pass # Gzip injects a timestamp into its output, which makes its output and digest # non-deterministic. To get reproducible pushes, freeze time. # This approach is based on the following StackOverflow answer: # http://stackoverflow.com/ # questions/264224/setting-the-gzip-timestamp-from-python class _FakeTime(object): def time(self): return 1225856967.109 gzip.time = _FakeTime() class FromTarball(DockerImage): """This decodes the image tarball output of docker_build for upload. The format is similar to 'docker save', however, we also leverage useful 'top' file to avoid searching for the graph entrypoint. """ def __init__(self, tarball, compresslevel=9): self._tarball = tarball self._compresslevel = compresslevel def _content(self, name): # tarfile is inherently single-threaded: # https://mail.python.org/pipermail/python-bugs-list/2015-March/265999.html # so instead of locking, just open the tarfile for each file # we want to read. with tarfile.open(name=self._tarball, mode='r') as tar: return tar.extractfile('./' + name).read() def top(self): """Override.""" return self._content('top').strip() def repositories(self): """Override.""" return json.loads(self._content('repositories')) def json(self, layer_id): """Override.""" return self._content(layer_id + '/json') # Large, do not memoize. def layer(self, layer_id): """Override.""" buf = cStringIO.StringIO() f = gzip.GzipFile(mode='wb', compresslevel=self._compresslevel, fileobj=buf) try: f.write(self._content(layer_id + '/layer.tar')) finally: f.close() return buf.getvalue() def ancestry(self, layer_id): """Override.""" p = self.parent(layer_id) if not p: return [layer_id] return [layer_id] + self.ancestry(p) # __enter__ and __exit__ allow use as a context manager. def __enter__(self): # Check that the file exists. with tarfile.open(name=self._tarball, mode='r'): return self def __exit__(self, unused_type, unused_value, unused_traceback): pass class FromRegistry(DockerImage): """This accesses a docker image hosted on a registry (non-local).""" def __init__(self, name, basic_creds, transport): self._name = name self._creds = basic_creds self._transport = transport # Set up in __enter__ self._tags = None self._response = {} def top(self): """Override.""" assert isinstance(self._name, docker_name.Tag) return self._tags[self._name.tag] def repositories(self): """Override.""" return {self._name.repository: self._tags} def tags(self): """Lists the tags present in the remote repository.""" return self.raw_tags().keys() def raw_tags( self ): """Dictionary of tag to image id.""" return self._tags def _content(self, suffix): if suffix not in self._response: _, self._response[suffix] = docker_http.Request( self._transport, '{scheme}://{endpoint}/v1/images/{suffix}'.format( scheme=docker_http.Scheme(self._endpoint), endpoint=self._endpoint, suffix=suffix), self._creds, [httplib.OK]) return self._response[suffix] def json(self, layer_id): """Override.""" # GET server1/v1/images/IMAGEID/json return self._content(layer_id + '/json') # Large, do not memoize. def layer(self, layer_id): """Override.""" # GET server1/v1/images/IMAGEID/layer return self._content(layer_id + '/layer') def ancestry(self, layer_id): """Override.""" # GET server1/v1/images/IMAGEID/ancestry return json.loads(self._content(layer_id + '/ancestry')) # __enter__ and __exit__ allow use as a context manager. def __enter__(self): # This initiates the pull by issuing: # GET H:P/v1/repositories/R/images resp, unused_content = docker_http.Request( self._transport, '{scheme}://{registry}/v1/repositories/{repository_name}/images'.format( scheme=docker_http.Scheme(self._name.registry), registry=self._name.registry, repository_name=self._name.repository), self._creds, [httplib.OK]) # The response should have an X-Docker-Token header, which # we should extract and annotate subsequent requests with: # Authorization: Token {extracted value} self._creds = docker_creds.Token(resp['x-docker-token']) self._endpoint = resp['x-docker-endpoints'] # TODO(user): Consider also supporting cookies, which are # used by Quay.io for authenticated sessions. # Next, fetch the set of tags in this repository. # GET server1/v1/repositories/R/tags resp, content = docker_http.Request( self._transport, '{scheme}://{endpoint}/v1/repositories/{repository_name}/tags'.format( scheme=docker_http.Scheme(self._endpoint), endpoint=self._endpoint, repository_name=self._name.repository), self._creds, [httplib.OK]) self._tags = json.loads(content) return self def __exit__(self, unused_type, unused_value, unused_traceback): pass class Random(DockerImage): """This generates an image with Random properties. We ensure basic consistency of the generated docker image. """ def __init__(self, sample, num_layers=5, layer_byte_size=64): # Generate the image. self._ancestry = [] self._layers = {} for _ in range(0, num_layers): # Avoid repetitions. while True: layer_id = self._next_id(sample) if layer_id not in self._ancestry: self._ancestry += [layer_id] self._layers[layer_id] = self._next_layer(sample, layer_byte_size) break def top(self): """Override.""" return self._ancestry[0] def repositories(self): """Override.""" return { 'random/image': { 'latest': self.top(), } } def json(self, layer_id): """Override.""" metadata = {'id': layer_id} ancestry = self.ancestry(layer_id) if len(ancestry) != 1: metadata['parent'] = ancestry[1] return json.dumps(metadata, sort_keys=True) def layer(self, layer_id): """Override.""" return self._layers[layer_id] def ancestry(self, layer_id): """Override.""" assert layer_id in self._ancestry index = self._ancestry.index(layer_id) return self._ancestry[index:] def _next_id( self, sample ): return sample('0123456789abcdef', 64) def _next_layer( self, sample, layer_byte_size ): buf = cStringIO.StringIO() # TODO(user): Consider doing something more creative... with tarfile.open(fileobj=buf, mode='w:gz') as tar: # Linux optimization, use dd for data file creation. if sys.platform.startswith('linux') and layer_byte_size >= 1024 * 1024: mb = layer_byte_size / (1024 * 1024) tempdir = tempfile.mkdtemp() data_filename = os.path.join(tempdir, 'a.bin') if os.path.exists(data_filename): os.remove(data_filename) process = subprocess.Popen(['dd', 'if=/dev/urandom', 'of=%s' % data_filename, 'bs=1M', 'count=%d' % mb]) process.wait() with open(data_filename, 'rb') as fd: info = tar.gettarinfo(name=data_filename) tar.addfile(info, fileobj=fd) os.remove(data_filename) os.rmdir(tempdir) else: data = sample(string.printable, layer_byte_size) info = tarfile.TarInfo(name='./' + self._next_id(sample)) info.size = len(data) tar.addfile(info, fileobj=cStringIO.StringIO(data)) return buf.getvalue() # __enter__ and __exit__ allow use as a context manager. def __enter__(self): return self def __exit__(self, unused_type, unused_value, unused_traceback): pass
import logging from logging import Logger from typing import Optional import sqlalchemy from sqlalchemy import ( Table, Column, Integer, String, DateTime, Index, and_, desc, MetaData, ) from sqlalchemy.engine import Engine from sqlalchemy.sql.sqltypes import Boolean from slack_sdk.oauth.installation_store.installation_store import InstallationStore from slack_sdk.oauth.installation_store.models.bot import Bot from slack_sdk.oauth.installation_store.models.installation import Installation class SQLAlchemyInstallationStore(InstallationStore): default_bots_table_name: str = "slack_bots" default_installations_table_name: str = "slack_installations" client_id: str engine: Engine metadata: MetaData installations: Table @classmethod def build_installations_table(cls, metadata: MetaData, table_name: str) -> Table: return sqlalchemy.Table( table_name, metadata, Column("id", Integer, primary_key=True, autoincrement=True), Column("client_id", String(32), nullable=False), Column("app_id", String(32), nullable=False), Column("enterprise_id", String(32)), Column("enterprise_name", String(200)), Column("enterprise_url", String(200)), Column("team_id", String(32)), Column("team_name", String(200)), Column("bot_token", String(200)), Column("bot_id", String(32)), Column("bot_user_id", String(32)), Column("bot_scopes", String(1000)), Column("bot_refresh_token", String(200)), # added in v3.8.0 Column("bot_token_expires_at", DateTime), # added in v3.8.0 Column("user_id", String(32), nullable=False), Column("user_token", String(200)), Column("user_scopes", String(1000)), Column("user_refresh_token", String(200)), # added in v3.8.0 Column("user_token_expires_at", DateTime), # added in v3.8.0 Column("incoming_webhook_url", String(200)), Column("incoming_webhook_channel", String(200)), Column("incoming_webhook_channel_id", String(200)), Column("incoming_webhook_configuration_url", String(200)), Column("is_enterprise_install", Boolean, default=False, nullable=False), Column("token_type", String(32)), Column( "installed_at", DateTime, nullable=False, default=sqlalchemy.sql.func.now(), ), Index( f"{table_name}_idx", "client_id", "enterprise_id", "team_id", "user_id", "installed_at", ), ) @classmethod def build_bots_table(cls, metadata: MetaData, table_name: str) -> Table: return Table( table_name, metadata, Column("id", Integer, primary_key=True, autoincrement=True), Column("client_id", String(32), nullable=False), Column("app_id", String(32), nullable=False), Column("enterprise_id", String(32)), Column("enterprise_name", String(200)), Column("team_id", String(32)), Column("team_name", String(200)), Column("bot_token", String(200)), Column("bot_id", String(32)), Column("bot_user_id", String(32)), Column("bot_scopes", String(1000)), Column("bot_refresh_token", String(200)), # added in v3.8.0 Column("bot_token_expires_at", DateTime), # added in v3.8.0 Column("is_enterprise_install", Boolean, default=False, nullable=False), Column( "installed_at", DateTime, nullable=False, default=sqlalchemy.sql.func.now(), ), Index( f"{table_name}_idx", "client_id", "enterprise_id", "team_id", "installed_at", ), ) def __init__( self, client_id: str, engine: Engine, bots_table_name: str = default_bots_table_name, installations_table_name: str = default_installations_table_name, logger: Logger = logging.getLogger(__name__), ): self.metadata = sqlalchemy.MetaData() self.bots = self.build_bots_table( metadata=self.metadata, table_name=bots_table_name ) self.installations = self.build_installations_table( metadata=self.metadata, table_name=installations_table_name ) self.client_id = client_id self._logger = logger self.engine = engine def create_tables(self): self.metadata.create_all(self.engine) @property def logger(self) -> Logger: return self._logger def save(self, installation: Installation): with self.engine.begin() as conn: i = installation.to_dict() i["client_id"] = self.client_id i_column = self.installations.c installations_rows = conn.execute( sqlalchemy.select([i_column.id]) .where( and_( i_column.client_id == self.client_id, i_column.enterprise_id == installation.enterprise_id, i_column.team_id == installation.team_id, i_column.installed_at == i.get("installed_at"), ) ) .limit(1) ) installations_row_id: Optional[str] = None for row in installations_rows: installations_row_id = row["id"] if installations_row_id is None: conn.execute(self.installations.insert(), i) else: update_statement = ( self.installations.update() .where(i_column.id == installations_row_id) .values(**i) ) conn.execute(update_statement, i) # bots self.save_bot(installation.to_bot()) def save_bot(self, bot: Bot): with self.engine.begin() as conn: # bots b = bot.to_dict() b["client_id"] = self.client_id b_column = self.bots.c bots_rows = conn.execute( sqlalchemy.select([b_column.id]) .where( and_( b_column.client_id == self.client_id, b_column.enterprise_id == bot.enterprise_id, b_column.team_id == bot.team_id, b_column.installed_at == b.get("installed_at"), ) ) .limit(1) ) bots_row_id: Optional[str] = None for row in bots_rows: bots_row_id = row["id"] if bots_row_id is None: conn.execute(self.bots.insert(), b) else: update_statement = ( self.bots.update().where(b_column.id == bots_row_id).values(**b) ) conn.execute(update_statement, b) def find_bot( self, *, enterprise_id: Optional[str], team_id: Optional[str], is_enterprise_install: Optional[bool] = False, ) -> Optional[Bot]: if is_enterprise_install or team_id is None: team_id = None c = self.bots.c query = ( self.bots.select() .where( and_( c.client_id == self.client_id, c.enterprise_id == enterprise_id, c.team_id == team_id, ) ) .order_by(desc(c.installed_at)) .limit(1) ) with self.engine.connect() as conn: result: object = conn.execute(query) for row in result: return Bot( app_id=row["app_id"], enterprise_id=row["enterprise_id"], enterprise_name=row["enterprise_name"], team_id=row["team_id"], team_name=row["team_name"], bot_token=row["bot_token"], bot_id=row["bot_id"], bot_user_id=row["bot_user_id"], bot_scopes=row["bot_scopes"], bot_refresh_token=row["bot_refresh_token"], bot_token_expires_at=row["bot_token_expires_at"], is_enterprise_install=row["is_enterprise_install"], installed_at=row["installed_at"], ) return None def find_installation( self, *, enterprise_id: Optional[str], team_id: Optional[str], user_id: Optional[str] = None, is_enterprise_install: Optional[bool] = False, ) -> Optional[Installation]: if is_enterprise_install or team_id is None: team_id = None c = self.installations.c where_clause = and_(c.enterprise_id == enterprise_id, c.team_id == team_id) if user_id is not None: where_clause = and_( c.client_id == self.client_id, c.enterprise_id == enterprise_id, c.team_id == team_id, c.user_id == user_id, ) query = ( self.installations.select() .where(where_clause) .order_by(desc(c.installed_at)) .limit(1) ) with self.engine.connect() as conn: result: object = conn.execute(query) for row in result: return Installation( app_id=row["app_id"], enterprise_id=row["enterprise_id"], enterprise_name=row["enterprise_name"], enterprise_url=row["enterprise_url"], team_id=row["team_id"], team_name=row["team_name"], bot_token=row["bot_token"], bot_id=row["bot_id"], bot_user_id=row["bot_user_id"], bot_scopes=row["bot_scopes"], bot_refresh_token=row["bot_refresh_token"], bot_token_expires_at=row["bot_token_expires_at"], user_id=row["user_id"], user_token=row["user_token"], user_scopes=row["user_scopes"], user_refresh_token=row["user_refresh_token"], user_token_expires_at=row["user_token_expires_at"], # Only the incoming webhook issued in the latest installation is set in this logic incoming_webhook_url=row["incoming_webhook_url"], incoming_webhook_channel=row["incoming_webhook_channel"], incoming_webhook_channel_id=row["incoming_webhook_channel_id"], incoming_webhook_configuration_url=row[ "incoming_webhook_configuration_url" ], is_enterprise_install=row["is_enterprise_install"], token_type=row["token_type"], installed_at=row["installed_at"], ) return None def delete_bot( self, *, enterprise_id: Optional[str], team_id: Optional[str] ) -> None: table = self.bots c = table.c with self.engine.begin() as conn: deletion = table.delete().where( and_( c.client_id == self.client_id, c.enterprise_id == enterprise_id, c.team_id == team_id, ) ) conn.execute(deletion) def delete_installation( self, *, enterprise_id: Optional[str], team_id: Optional[str], user_id: Optional[str] = None, ) -> None: table = self.installations c = table.c with self.engine.begin() as conn: if user_id is not None: deletion = table.delete().where( and_( c.client_id == self.client_id, c.enterprise_id == enterprise_id, c.team_id == team_id, c.user_id == user_id, ) ) conn.execute(deletion) else: deletion = table.delete().where( and_( c.client_id == self.client_id, c.enterprise_id == enterprise_id, c.team_id == team_id, ) ) conn.execute(deletion)
# 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. # ============================================================================== """Tests for SparseSoftmaxCrossEntropyWithLogits op.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import time import numpy as np from tensorflow.core.protobuf import config_pb2 from tensorflow.python.client import session from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors_impl from tensorflow.python.framework import ops as ops_lib from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import gen_nn_ops from tensorflow.python.ops import gradient_checker from tensorflow.python.ops import gradients_impl from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import sparse_ops from tensorflow.python.ops import variables import tensorflow.python.ops.nn_grad # pylint: disable=unused-import from tensorflow.python.platform import app from tensorflow.python.platform import test class SparseXentTest(test.TestCase): def _npXent(self, features, labels): features = np.reshape(features, [-1, features.shape[-1]]) labels = np.reshape(labels, [-1]) batch_dim = 0 class_dim = 1 batch_size = features.shape[batch_dim] e = np.exp(features - np.reshape( np.amax( features, axis=class_dim), [batch_size, 1])) probs = e / np.reshape(np.sum(e, axis=class_dim), [batch_size, 1]) labels_mat = np.zeros_like(probs).astype(probs.dtype) labels_mat[np.arange(batch_size), labels] = 1.0 bp = (probs - labels_mat) l = -np.sum(labels_mat * np.log(probs + 1.0e-20), axis=1) return l, bp def _testXent(self, np_features, np_labels): np_loss, np_backprop = self._npXent(np_features, np_labels) with self.cached_session(use_gpu=True) as sess: loss, backprop = gen_nn_ops.sparse_softmax_cross_entropy_with_logits( np_features, np_labels) tf_loss, tf_backprop = self.evaluate([loss, backprop]) self.assertAllCloseAccordingToType(np_loss, tf_loss) self.assertAllCloseAccordingToType(np_backprop, tf_backprop) def testSingleClass(self): for label_dtype in np.int32, np.int64: with self.cached_session(use_gpu=True) as sess: loss, backprop = gen_nn_ops.sparse_softmax_cross_entropy_with_logits( np.array([[1.], [-1.], [0.]]).astype(np.float32), np.array([0, 0, 0]).astype(label_dtype)) tf_loss, tf_backprop = self.evaluate([loss, backprop]) self.assertAllClose([0.0, 0.0, 0.0], tf_loss) self.assertAllClose([[0.0], [0.0], [0.0]], tf_backprop) @test_util.run_deprecated_v1 @test_util.disable_xla("XLA cannot assert inside of a kernel.") def testInvalidLabel(self): features = [[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 2., 3., 4.], [1., 2., 3., 4.]] labels = [4, 3, 0, -1] if test.is_built_with_gpu_support() and test.is_gpu_available(): with self.session(use_gpu=True) as sess: loss, backprop = ( gen_nn_ops.sparse_softmax_cross_entropy_with_logits( features, labels)) tf_loss, tf_backprop = self.evaluate([loss, backprop]) self.assertAllClose( [[np.nan] * 4, [0.25, 0.25, 0.25, -0.75], [-0.968, 0.087, 0.237, 0.6439], [np.nan] * 4], tf_backprop, rtol=1e-3, atol=1e-3) self.assertAllClose( [np.nan, 1.3862, 3.4420, np.nan], tf_loss, rtol=1e-3, atol=1e-3) with self.session(use_gpu=False) as sess: loss, backprop = ( gen_nn_ops.sparse_softmax_cross_entropy_with_logits(features, labels)) with self.assertRaisesOpError("Received a label value of"): self.evaluate([loss, backprop]) def testNpXent(self): # We create 2 batches of logits for testing. # batch 0 is the boring uniform distribution: 1, 1, 1, 1, with target 3. # batch 1 has a bit of difference: 1, 2, 3, 4, with target 0. features = [[1., 1., 1., 1.], [1., 2., 3., 4.]] labels = [3, 0] # For batch 0, we expect the uniform distribution: 0.25, 0.25, 0.25, 0.25 # With a hard target 3, the backprop is [0.25, 0.25, 0.25, -0.75] # The loss for this batch is -log(0.25) = 1.386 # # For batch 1, we have: # exp(0) = 1 # exp(1) = 2.718 # exp(2) = 7.389 # exp(3) = 20.085 # SUM = 31.192 # So we have as probabilities: # exp(0) / SUM = 0.032 # exp(1) / SUM = 0.087 # exp(2) / SUM = 0.237 # exp(3) / SUM = 0.644 # With a hard 1, the backprop is [0.032 - 1.0 = -0.968, 0.087, 0.237, 0.644] # The loss for this batch is [1.0 * -log(0.25), 1.0 * -log(0.032)] # = [1.3862, 3.4420] np_loss, np_backprop = self._npXent(np.array(features), np.array(labels)) self.assertAllClose( np.array([[0.25, 0.25, 0.25, -0.75], [-0.968, 0.087, 0.237, 0.6439]]), np_backprop, rtol=1.e-3, atol=1.e-3) self.assertAllClose( np.array([1.3862, 3.4420]), np_loss, rtol=1.e-3, atol=1.e-3) def testShapeMismatch(self): with self.session(use_gpu=True): with self.assertRaisesRegexp(ValueError, ".*Rank mismatch:*"): nn_ops.sparse_softmax_cross_entropy_with_logits( labels=[[0, 2]], logits=[[0., 1.], [2., 3.], [2., 3.]]) def testScalar(self): with self.session(use_gpu=True): with self.assertRaisesRegexp(ValueError, ".*Logits cannot be scalars*"): nn_ops.sparse_softmax_cross_entropy_with_logits( labels=constant_op.constant(0), logits=constant_op.constant(1.0)) @test_util.run_deprecated_v1 def testLabelsPlaceholderScalar(self): with self.session(use_gpu=True): labels = array_ops.placeholder(np.int32) y = nn_ops.sparse_softmax_cross_entropy_with_logits( labels=labels, logits=[[7.]]) with self.assertRaisesOpError("labels must be 1-D"): y.eval(feed_dict={labels: 0}) def testVector(self): with self.session(use_gpu=True): loss = nn_ops.sparse_softmax_cross_entropy_with_logits( labels=constant_op.constant(0), logits=constant_op.constant([1.0])) self.assertAllClose(0.0, self.evaluate(loss)) def testFloat(self): for label_dtype in np.int32, np.int64: self._testXent( np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float32), np.array([3, 0]).astype(label_dtype)) def testDouble(self): for label_dtype in np.int32, np.int64: self._testXent( np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float64), np.array([0, 3]).astype(label_dtype)) def testHalf(self): for label_dtype in np.int32, np.int64: self._testXent( np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float16), np.array([3, 0]).astype(label_dtype)) def testEmpty(self): self._testXent(np.zeros((0, 3)), np.zeros((0,), dtype=np.int32)) @test_util.run_deprecated_v1 def testGradient(self): with self.session(use_gpu=True): l = constant_op.constant([3, 0, 1], name="l") f = constant_op.constant( [0.1, 0.2, 0.3, 0.4, 0.1, 0.4, 0.9, 1.6, 0.1, 0.8, 2.7, 6.4], shape=[3, 4], dtype=dtypes.float64, name="f") x = nn_ops.sparse_softmax_cross_entropy_with_logits( labels=l, logits=f, name="xent") err = gradient_checker.compute_gradient_error(f, [3, 4], x, [3]) print("cross entropy gradient err = ", err) self.assertLess(err, 5e-8) @test_util.run_deprecated_v1 def testSecondGradient(self): images_placeholder = array_ops.placeholder(dtypes.float32, shape=(3, 2)) labels_placeholder = array_ops.placeholder(dtypes.int32, shape=(3)) weights = variables.Variable(random_ops.truncated_normal([2], stddev=1.0)) weights_with_zeros = array_ops.stack([array_ops.zeros([2]), weights], axis=1) logits = math_ops.matmul(images_placeholder, weights_with_zeros) cross_entropy = nn_ops.sparse_softmax_cross_entropy_with_logits( labels=labels_placeholder, logits=logits) loss = math_ops.reduce_mean(cross_entropy) # Taking ths second gradient should fail, since it is not # yet supported. with self.assertRaisesRegexp(LookupError, "explicitly disabled"): _ = gradients_impl.hessians(loss, [weights]) def _testHighDim(self, features, labels): np_loss, np_backprop = self._npXent(np.array(features), np.array(labels)) # manually reshape loss np_loss = np.reshape(np_loss, np.array(labels).shape) with self.cached_session(use_gpu=True) as sess: loss = nn_ops.sparse_softmax_cross_entropy_with_logits( labels=labels, logits=features) backprop = loss.op.inputs[0].op.outputs[1] tf_loss, tf_backprop = self.evaluate([loss, backprop]) self.assertAllCloseAccordingToType(np_loss, tf_loss) self.assertAllCloseAccordingToType(np_backprop, tf_backprop) @test_util.run_deprecated_v1 def testHighDim(self): features = [[[1., 1., 1., 1.]], [[1., 2., 3., 4.]]] labels = [[3], [0]] self._testHighDim(features, labels) @test_util.run_deprecated_v1 def testHighDim2(self): features = [[[1., 1., 1., 1.], [2., 2., 2., 2.]], [[1., 2., 3., 4.], [5., 6., 7., 8.]]] labels = [[3, 2], [0, 3]] self._testHighDim(features, labels) @test_util.run_deprecated_v1 def testScalarHandling(self): with self.session(use_gpu=False) as sess: with self.assertRaisesRegexp(errors_impl.InvalidArgumentError, ".*labels must be 1-D.*"): labels = array_ops.placeholder(dtypes.int32, shape=[None, 1]) logits = array_ops.placeholder(dtypes.float32, shape=[None, 3]) ce = nn_ops.sparse_softmax_cross_entropy_with_logits( labels=array_ops.squeeze(labels), logits=logits) labels_v2 = np.zeros((1, 1), dtype=np.int32) logits_v2 = np.random.randn(1, 3) sess.run([ce], feed_dict={labels: labels_v2, logits: logits_v2}) def _sparse_vs_dense_xent_benchmark_dense(labels, logits): labels = array_ops.identity(labels) logits = array_ops.identity(logits) with ops_lib.device("/cpu:0"): # Sparse-to-dense must be on CPU batch_size = array_ops.shape(logits)[0] num_entries = array_ops.shape(logits)[1] length = batch_size * num_entries labels += num_entries * math_ops.range(batch_size) target = sparse_ops.sparse_to_dense(labels, array_ops.stack([length]), 1.0, 0.0) target = array_ops.reshape(target, array_ops.stack([-1, num_entries])) crossent = nn_ops.softmax_cross_entropy_with_logits( labels=target, logits=logits, name="SequenceLoss/CrossEntropy") crossent_sum = math_ops.reduce_sum(crossent) grads = gradients_impl.gradients([crossent_sum], [logits])[0] return (crossent_sum, grads) def _sparse_vs_dense_xent_benchmark_sparse(labels, logits): # Using sparse_softmax_cross_entropy_with_logits labels = labels.astype(np.int64) labels = array_ops.identity(labels) logits = array_ops.identity(logits) crossent = nn_ops.sparse_softmax_cross_entropy_with_logits( logits, labels, name="SequenceLoss/CrossEntropy") crossent_sum = math_ops.reduce_sum(crossent) grads = gradients_impl.gradients([crossent_sum], [logits])[0] return (crossent_sum, grads) def sparse_vs_dense_xent_benchmark(batch_size, num_entries, use_gpu): config = config_pb2.ConfigProto() config.allow_soft_placement = True config.gpu_options.per_process_gpu_memory_fraction = 0.3 labels = np.random.randint(num_entries, size=batch_size).astype(np.int32) logits = np.random.randn(batch_size, num_entries).astype(np.float32) def _timer(sess, ops): # Warm in for _ in range(20): sess.run(ops) # Timing run start = time.time() for _ in range(20): sess.run(ops) end = time.time() return (end - start) / 20.0 # Average runtime per iteration # Using sparse_to_dense and softmax_cross_entropy_with_logits with session.Session(config=config) as sess: if not use_gpu: with ops_lib.device("/cpu:0"): ops = _sparse_vs_dense_xent_benchmark_dense(labels, logits) else: ops = _sparse_vs_dense_xent_benchmark_dense(labels, logits) delta_dense = _timer(sess, ops) # Using sparse_softmax_cross_entropy_with_logits with session.Session(config=config) as sess: if not use_gpu: with test_util.device("/cpu:0"): ops = _sparse_vs_dense_xent_benchmark_sparse(labels, logits) else: ops = _sparse_vs_dense_xent_benchmark_sparse(labels, logits) delta_sparse = _timer(sess, ops) print("%d \t %d \t %s \t %f \t %f \t %f" % (batch_size, num_entries, use_gpu, delta_dense, delta_sparse, delta_sparse / delta_dense)) def main(_): print("Sparse Xent vs. SparseToDense + Xent") print("batch \t depth \t gpu \t dt(dense) \t dt(sparse) " "\t dt(sparse)/dt(dense)") for use_gpu in (False, True): for batch_size in (32, 64, 128): for num_entries in (100, 1000, 10000): sparse_vs_dense_xent_benchmark(batch_size, num_entries, use_gpu) sparse_vs_dense_xent_benchmark(32, 100000, use_gpu) sparse_vs_dense_xent_benchmark(8, 1000000, use_gpu) if __name__ == "__main__": if "--benchmarks" in sys.argv: sys.argv.remove("--benchmarks") app.run() else: test.main()
import math import operator from .titanic import ndarray from .fpbench import fpcparser from .arithmetic import mpmf, ieee754, evalctx, analysis from .arithmetic.mpmf import Interpreter from .sweep import search eqn_core = '''(FPCore lorenz-3d ((xyz 3)) :precision {fn_prec} (let ([sigma 10] [beta 8/3] [rho 28] [x (ref xyz 0)] [y (ref xyz 1)] [z (ref xyz 2)]) (array (* sigma (- y x)) (- (* x (- rho z)) y) (- (* x y) (* beta z)) ))) ''' rk_core = ('''(FPCore vec-scale ((A n) x) (tensor ([i (# n)]) (* (ref A i) x))) (FPCore vec-add ((A n) (B m)) :pre (== n m) (tensor ([i (# n)]) (+ (ref A i) (ref B i)))) ''' + eqn_core + '''(FPCore rk4-3d ((xyz 3) h) :precision {rk_prec} (let* ([k1 (! :precision {k1_prec} (vec-scale ({target_fn} xyz) h))] [k2 (! :precision {k2_prec} (vec-scale ({target_fn} (vec-add xyz (vec-scale k1 1/2))) h))] [k3 (! :precision {k3_prec} (vec-scale ({target_fn} (vec-add xyz (vec-scale k2 1/2))) h))] [k4 (! :precision {k4_prec} (vec-scale ({target_fn} (vec-add xyz k3)) h))]) (tensor ([i (# 3)]) (+ (ref xyz i) (* 1/6 (+ (+ (+ (ref k1 i) (* (ref k2 i) 2)) (* (ref k3 i) 2)) (ref k4 i))))))) (FPCore main ((initial-conditions 3) h steps) (tensor* ([step steps]) ([xyz initial-conditions ({step_fn} xyz h)]) xyz)) ''') rk_args = '''(array -12 -8.5 35) 1/64 240 ''' import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def mkplot(data, name='fig.png', title='Some chaotic attractor'): fig = plt.figure(figsize=(12, 9), dpi=80) ax = Axes3D(fig) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') ax.set_title(title) ax.plot(data[0], data[1], data[2], color='blue', lw=1) plt.savefig(name) # .0002, 68500: # 0.6281892410761881 1.1362559216491108 11.931824372016203 # 0.0945572632908741 0.1616933534076016 -0.6410587355265847 # .02, 685: # 0.7275905023319384 1.3081569466209049 12.058504949154397 # 0.10792263132676083 0.1859532584808219 -0.6437818982542893 # real_state = (0.6281892410761881, 1.1362559216491108, 11.931824372016203) # real_derivative = (0.0945572632908741, 0.1616933534076016, -0.6410587355265847) # alg_state = (0.7275905023319384, 1.3081569466209049, 12.058504949154397) # alg_derivative = (0.10792263132676083, 0.1859532584808219, -0.6437818982542893) # new: # 1/16, 189: ref_state = (16.157760096498592, 19.29168560322699, 34.45572835102259) ref_dstate = (31.339255067284, -123.60179554721446, 219.82848556462386) def avg_abserr(a1, a2): count = 0 err = 0 for e1, e2 in zip(a1, a2): if math.isfinite(e1) and math.isfinite(e2): err += abs(float(e2) - float(e1)) count += 1 else: return math.inf return err / count def run_rk(cores, args): evaltor = Interpreter() als = analysis.BitcostAnalysis() evaltor.analyses = [als] main = cores[-1] for core in cores: evaltor.register_function(core) if core.ident and core.ident.lower() == 'main': main = core result_array = evaltor.interpret(main, args) return evaltor, als, result_array rk_ebits = 8 def eval_rk(als, result_array, fn_prec): last = [e for e in result_array[-1]] formatted = eqn_core.format(fn_prec=f'(float {rk_ebits} {fn_prec + rk_ebits!s})') eqn = fpcparser.compile1(formatted) evaltor = Interpreter() dlast = evaltor.interpret(eqn, [ndarray.NDArray(last)]) return ( als.bits_requested, avg_abserr([float(str(x)) for x in last], ref_state), avg_abserr([float(str(x)) for x in dlast], ref_dstate), ) def setup_rk(fn_prec, rk_prec, k1_prec, k2_prec, k3_prec, k4_prec): formatted = rk_core.format( target_fn = 'lorenz-3d', step_fn = 'rk4-3d', fn_prec = f'(float {rk_ebits} {fn_prec + rk_ebits!s})', rk_prec = f'(float {rk_ebits} {rk_prec + rk_ebits!s})', k1_prec = f'(float {rk_ebits} {k1_prec + rk_ebits!s})', k2_prec = f'(float {rk_ebits} {k2_prec + rk_ebits!s})', k3_prec = f'(float {rk_ebits} {k3_prec + rk_ebits!s})', k4_prec = f'(float {rk_ebits} {k4_prec + rk_ebits!s})', ) cores = fpcparser.compile(formatted) args = fpcparser.read_exprs(rk_args) return cores, args def describe_rk(fn_prec, rk_prec, k1_prec, k2_prec, k3_prec, k4_prec): formatted = rk_core.format( target_fn = 'lorenz-3d', step_fn = 'rk4-3d', fn_prec = f'(float {rk_ebits} {fn_prec + rk_ebits!s})', rk_prec = f'(float {rk_ebits} {rk_prec + rk_ebits!s})', k1_prec = f'(float {rk_ebits} {k1_prec + rk_ebits!s})', k2_prec = f'(float {rk_ebits} {k2_prec + rk_ebits!s})', k3_prec = f'(float {rk_ebits} {k3_prec + rk_ebits!s})', k4_prec = f'(float {rk_ebits} {k4_prec + rk_ebits!s})', ) print(formatted) def rk_stage(fn_prec, rk_prec, k1_prec, k2_prec, k3_prec, k4_prec): cores, args = setup_rk(fn_prec, rk_prec, k1_prec, k2_prec, k3_prec, k4_prec) evaltor, als, result_array = run_rk(cores, args) return eval_rk(als, result_array, fn_prec) def rk_plot(fn_prec, rk_prec, k1_prec, k2_prec, k3_prec, k4_prec, name=None): cores, args = setup_rk(fn_prec, rk_prec, k1_prec, k2_prec, k3_prec, k4_prec) evaltor, als, result_array = run_rk(cores, args) results = [[], [], []] for x,y,z in result_array: r_x, r_y, r_z = results r_x.append(float(str(x))) r_y.append(float(str(y))) r_z.append(float(str(z))) title = f'fn={fn_prec!s}, rk={rk_prec!s}, k1={k1_prec!s}, k2={k2_prec!s}, k3={k3_prec!s}, k4={k4_prec!s}' if name is None: mkplot(results, name=title, title=title) else: mkplot(results, name=name, title=title) def init_prec(): return 16 def neighbor_prec(x): nearby = 2 for neighbor in range(x-nearby, x+nearby+1): if 1 <= neighbor <= 24 and neighbor != x: yield neighbor rk_inits = (init_prec,) * 6 rk_neighbors = (neighbor_prec,) * 6 rk_metrics = (operator.lt,) * 3 filtered_metrics = (operator.lt, operator.lt, None) def run_random(): frontier = search.sweep_random_init(rk_stage, rk_inits, rk_neighbors, rk_metrics) filtered_frontier = search.filter_frontier(frontier, filtered_metrics) sorted_frontier = sorted(filtered_frontier, key=lambda x: x[1][0]) for data, measures in sorted_frontier: print('\t'.join(str(m) for m in measures)) for data, measures in sorted_frontier: rk_plot(*data) lo_frontier = [ ((7, 8, 7, 6, 8, 6), (572496, 0.14302797157119254, 0.828087840083158)), ((6, 6, 6, 9, 4, 5), (539461, 0.6963279715711925, 5.971421173416491)), ((6, 3, 3, 5, 4, 6), (496429, 7.987994638237859, 1.3539103120407165)), ((4, 2, 3, 1, 2, 2), (439938, 3.230990973765907, 2.161421173416491)), ((3, 2, 2, 1, 1, 2), (426708, 5.654661304904526, 17.494754506749825)), ((4, 2, 2, 1, 1, 2), (435024, 2.134669663188198, 7.828087840083158)), ((1, 2, 1, 1, 1, 2), (408942, 10.98799463823786, 12.16142117341649)), ((2, 3, 2, 1, 1, 2), (427255, 1.6786720284288075, 14.505245493250174)), ((1, 2, 1, 1, 1, 1), (406863, 10.134669663188198, 16.161421173416493)), ((3, 1, 1, 1, 1, 1), (414632, 5.769009026234094, 20.842115970309813)), ((2, 1, 1, 1, 1, 1), (406316, 6.365330336811802, 28.171912159916843)), ((3, 3, 3, 3, 1, 2), (444265, 1.4356756929007604, 6.342115970309813)), ((1, 1, 1, 3, 1, 1), (405560, 6.365330336811802, 31.171912159916843)), ((1, 1, 1, 1, 1, 1), (398000, 6.6786720284288075, 37.17191215991684)), ((1, 2, 1, 3, 1, 1), (414423, 10.987994638237879, 12.16142117341469)), ((3, 4, 3, 3, 1, 2), (453128, 0.8019946382378592, 2.161421173416491)), ((1, 3, 1, 3, 1, 1), (423286, 10.987994638237774, 12.161421173415816)), ((1, 3, 1, 4, 1, 1), (427066, 7.237994638237859, 15.324550696356853)), ] hi_frontier = [ ((16, 17, 15, 16, 17, 16), (828789, 0.0003949715711923929, 0.0018840296901861582)), ((15, 16, 14, 16, 13, 16), (795356, 0.001372028428806941, 0.007002636976479219)), ((14, 17, 13, 15, 16, 16), (802329, 0.00040361548223385074, 0.0026106963568537367)), ((14, 17, 13, 14, 16, 16), (798549, 0.0021740262340933145, 0.006157840083157377)), ((10, 13, 10, 11, 14, 14), (703373, 0.01164235956742754, 0.06061597030981206)), ((12, 13, 11, 10, 14, 14), (717359, 0.006742359567426452, 0.02444364537404997)), ((14, 13, 11, 10, 14, 14), (733991, 0.0011279715711927836, 0.011417363023520958)), ((8, 9, 8, 10, 12, 11), (631444, 0.02800536176214045, 0.07144930364314621)), ((8, 9, 8, 10, 12, 9), (627286, 0.2159423595674265, 0.7344211734164915)), ((6, 9, 6, 8, 11, 10), (599125, 0.6030053617621408, 2.8254493036431456)), ((8, 9, 6, 6, 10, 11), (606496, 0.18639463823785876, 1.1414211734164912)), ((6, 9, 6, 9, 10, 8), (594967, 0.6393243070992402, 1.9127563546259505)), ((4, 2, 3, 1, 2, 2), (439938, 3.230990973765907, 2.161421173416491)), ((3, 2, 2, 1, 1, 2), (426708, 5.654661304904526, 17.494754506749825)), ((4, 2, 2, 1, 1, 2), (435024, 2.134669663188198, 7.828087840083158)), ((1, 2, 1, 1, 1, 2), (408942, 10.98799463823786, 12.16142117341649)), ((2, 3, 2, 1, 1, 2), (427255, 1.6786720284288075, 14.505245493250174)), ((1, 2, 1, 1, 1, 1), (406863, 10.134669663188198, 16.161421173416493)), ((3, 1, 1, 1, 1, 1), (414632, 5.769009026234094, 20.842115970309813)), ((2, 1, 1, 1, 1, 1), (406316, 6.365330336811802, 28.171912159916843)), ((3, 3, 3, 3, 1, 2), (444265, 1.4356756929007604, 6.342115970309813)), ((1, 1, 1, 3, 1, 1), (405560, 6.365330336811802, 31.171912159916843)), ((1, 1, 1, 1, 1, 1), (398000, 6.6786720284288075, 37.17191215991684)), ((1, 2, 1, 3, 1, 1), (414423, 10.987994638237879, 12.16142117341469)), ((3, 4, 3, 3, 1, 2), (453128, 0.8019946382378592, 2.161421173416491)), ((1, 3, 1, 3, 1, 1), (423286, 10.987994638237774, 12.161421173415816)), ((1, 3, 1, 4, 1, 1), (427066, 7.237994638237859, 15.324550696356853)), ] """New: sweep from 12 prec improvement stopped at generation 37: [ ((8, 10, 8, 12, 10, 11), (812840, 0.13860094809806492, 3.144684971768868)), ((8, 10, 8, 12, 10, 13), (818120, 0.02839905190193548, 0.46965798514855805)), ((6, 10, 6, 12, 12, 11), (798440, 0.6220657185686029, 10.355315028231132)), ((4, 5, 4, 4, 8, 4), (642060, 0.468391350249392, 14.697008681518108)), ((4, 5, 2, 4, 6, 4), (629580, 1.83123911623433, 35.521981694897796)), ((2, 5, 2, 1, 8, 6), (608940, 2.9979057829009967, 37.18864836156447)), ((1, 4, 1, 4, 4, 2), (570320, 11.81023911623433, 144.92317872637412)), ((3, 6, 3, 4, 4, 2), (616840, 2.968391350249392, 56.25651205970744)), ((1, 4, 1, 4, 4, 1), (567680, 12.33123466623433, 146.25651205970743)), ((3, 8, 3, 4, 4, 2), (639360, 1.287905782900997, 18.256512059707443)), ((3, 6, 3, 6, 4, 2), (626440, 2.0683913502493922, 35.36367534818478)), ((1, 4, 1, 1, 1, 4), (546800, 17.331239116234332, 125.36367534818477)), ((1, 4, 1, 4, 1, 1), (553280, 12.331239125860996, 146.25651203970745)), ((1, 6, 1, 1, 1, 4), (569320, 12.938391350249391, 140.25651205970743)), ((1, 6, 1, 1, 2, 2), (568840, 12.217905782900997, 146.25651205970743)), ((1, 6, 1, 2, 2, 1), (571000, 2.968391350249392, 64.81135163843554)), ((2, 4, 1, 4, 1, 1), (563840, 12.331239125227663, 156.92317871670744)), ((1, 6, 1, 1, 1, 2), (564040, 19.63505801691606, 112.9231787263741)), ((1, 6, 1, 1, 1, 3), (566680, 17.287905782900996, 130.25651205970743)), ((1, 2, 1, 1, 1, 1), (516360, 19.301724683582727, 117.36367534818477)), ((1, 6, 1, 2, 1, 2), (568840, 13.140391350249393, 137.36367534818478)), ((1, 1, 1, 1, 1, 1), (505100, 17.968391350249394, 127.58984539304078)), ((1, 5, 1, 1, 1, 1), (550140, 12.33147811623433, 146.25651205970743)), ] 505100 17.968391350249394 546800 17.331239116234332 550140 12.33147811623433 553280 12.331239125860996 563840 12.331239125227663 567680 12.33123466623433 568840 12.217905782900997 570320 11.81023911623433 571000 2.968391350249392 626440 2.0683913502493922 629580 1.83123911623433 639360 1.287905782900997 642060 0.468391350249392 812840 0.13860094809806492 818120 0.02839905190193548 """
""" Class average finetuning functions. Before using any of these finetuning functions, ensure that the model is set up with nb_classes=2. """ from __future__ import print_function import sys import uuid import numpy as np from os.path import dirname from time import sleep from keras.optimizers import Adam from global_variables import ( FINETUNING_METHODS, WEIGHTS_DIR) from finetuning import ( freeze_layers, sampling_generator, finetuning_callbacks, train_by_chain_thaw, find_f1_threshold) def relabel(y, current_label_nr, nb_classes): """ Makes a binary classification for a specific class in a multi-class dataset. # Arguments: y: Outputs to be relabelled. current_label_nr: Current label number. nb_classes: Total number of classes. # Returns: Relabelled outputs of a given multi-class dataset into a binary classification dataset. """ # Handling binary classification if nb_classes == 2 and len(y.shape) == 1: return y y_new = np.zeros(len(y)) y_cut = y[:, current_label_nr] label_pos = np.where(y_cut == 1)[0] y_new[label_pos] = 1 return y_new def class_avg_finetune(model, texts, labels, nb_classes, batch_size, method, epoch_size=5000, nb_epochs=1000, error_checking=True, verbose=True): """ Compiles and finetunes the given model. # Arguments: model: Model to be finetuned texts: List of three lists, containing tokenized inputs for training, validation and testing (in that order). labels: List of three lists, containing labels for training, validation and testing (in that order). nb_classes: Number of classes in the dataset. batch_size: Batch size. method: Finetuning method to be used. For available methods, see FINETUNING_METHODS in global_variables.py. Note that the model should be defined accordingly (see docstring for deepmoji_transfer()) epoch_size: Number of samples in an epoch. nb_epochs: Number of epochs. Doesn't matter much as early stopping is used. error_checking: If set to True, warnings will be printed when the label list has the wrong dimensions. verbose: Verbosity flag. # Returns: Model after finetuning, score after finetuning using the class average F1 metric. """ if method not in FINETUNING_METHODS: raise ValueError('ERROR (class_avg_tune_trainable): ' 'Invalid method parameter. ' 'Available options: {}'.format(FINETUNING_METHODS)) (X_train, y_train) = (texts[0], labels[0]) (X_val, y_val) = (texts[1], labels[1]) (X_test, y_test) = (texts[2], labels[2]) checkpoint_path = '{}/deepmoji-checkpoint-{}.hdf5' \ .format(WEIGHTS_DIR, str(uuid.uuid4())) f1_init_path = '{}/deepmoji-f1-init-{}.hdf5' \ .format(WEIGHTS_DIR, str(uuid.uuid4())) # Check dimension of labels if error_checking: # Binary classification has two classes but one value expected_shape = 1 if nb_classes == 2 else nb_classes for ls in [y_train, y_val, y_test]: if len(ls.shape) <= 1 or not ls.shape[1] == expected_shape: print('WARNING (class_avg_tune_trainable): ' 'The dimension of the provided ' 'labels do not match the expected value. ' 'Expected: {}, actual: {}' .format(expected_shape, ls.shape[1])) break if method in ['last', 'new']: lr = 0.001 elif method in ['full', 'chain-thaw']: lr = 0.0001 loss = 'binary_crossentropy' # Freeze layers if using last if method == 'last': model = freeze_layers(model, unfrozen_keyword='softmax') # Compile model, for chain-thaw we compile it later (after freezing) if method != 'chain-thaw': adam = Adam(clipnorm=1, lr=lr) model.compile(loss=loss, optimizer=adam, metrics=['accuracy']) # Training if verbose: print('Method: {}'.format(method)) print('Classes: {}'.format(nb_classes)) if method == 'chain-thaw': result = class_avg_chainthaw(model, nb_classes=nb_classes, train=(X_train, y_train), val=(X_val, y_val), test=(X_test, y_test), batch_size=batch_size, loss=loss, epoch_size=epoch_size, nb_epochs=nb_epochs, checkpoint_weight_path=checkpoint_path, f1_init_weight_path=f1_init_path, verbose=verbose) else: result = class_avg_tune_trainable(model, nb_classes=nb_classes, train=(X_train, y_train), val=(X_val, y_val), test=(X_test, y_test), epoch_size=epoch_size, nb_epochs=nb_epochs, batch_size=batch_size, init_weight_path=f1_init_path, checkpoint_weight_path=checkpoint_path, verbose=verbose) return model, result def prepare_labels(y_train, y_val, y_test, iter_i, nb_classes): # Relabel into binary classification y_train_new = relabel(y_train, iter_i, nb_classes) y_val_new = relabel(y_val, iter_i, nb_classes) y_test_new = relabel(y_test, iter_i, nb_classes) return y_train_new, y_val_new, y_test_new def prepare_generators(X_train, y_train_new, X_val, y_val_new, batch_size, epoch_size): # Create sample generators # Make a fixed validation set to avoid fluctuations in validation train_gen = sampling_generator(X_train, y_train_new, batch_size, upsample=False) val_gen = sampling_generator(X_val, y_val_new, epoch_size, upsample=False) X_val_resamp, y_val_resamp = next(val_gen) return train_gen, X_val_resamp, y_val_resamp def class_avg_tune_trainable(model, nb_classes, train, val, test, epoch_size, nb_epochs, batch_size, init_weight_path, checkpoint_weight_path, patience=5, verbose=True): """ Finetunes the given model using the F1 measure. # Arguments: model: Model to be finetuned. nb_classes: Number of classes in the given dataset. train: Training data, given as a tuple of (inputs, outputs) val: Validation data, given as a tuple of (inputs, outputs) test: Testing data, given as a tuple of (inputs, outputs) epoch_size: Number of samples in an epoch. nb_epochs: Number of epochs. batch_size: Batch size. init_weight_path: Filepath where weights will be initially saved before training each class. This file will be rewritten by the function. checkpoint_weight_path: Filepath where weights will be checkpointed to during training. This file will be rewritten by the function. verbose: Verbosity flag. # Returns: F1 score of the trained model """ total_f1 = 0 nb_iter = nb_classes if nb_classes > 2 else 1 # Unpack args X_train, y_train = train X_val, y_val = val X_test, y_test = test # Save and reload initial weights after running for # each class to avoid learning across classes model.save_weights(init_weight_path) for i in range(nb_iter): if verbose: print('Iteration number {}/{}'.format(i + 1, nb_iter)) model.load_weights(init_weight_path, by_name=False) y_train_new, y_val_new, y_test_new = prepare_labels(y_train, y_val, y_test, i, nb_classes) train_gen, X_val_resamp, y_val_resamp = \ prepare_generators(X_train, y_train_new, X_val, y_val_new, batch_size, epoch_size) if verbose: print("Training..") callbacks = finetuning_callbacks(checkpoint_weight_path, patience, verbose=2) steps = int(epoch_size / batch_size) model.fit_generator(train_gen, steps_per_epoch=steps, max_q_size=2, epochs=nb_epochs, validation_data=(X_val_resamp, y_val_resamp), callbacks=callbacks, verbose=0) # Reload the best weights found to avoid overfitting # Wait a bit to allow proper closing of weights file sleep(1) model.load_weights(checkpoint_weight_path, by_name=False) # Evaluate y_pred_val = np.array(model.predict(X_val, batch_size=batch_size)) y_pred_test = np.array(model.predict(X_test, batch_size=batch_size)) f1_test, best_t = find_f1_threshold(y_val_new, y_pred_val, y_test_new, y_pred_test) if verbose: print('f1_test: {}'.format(f1_test)) print('best_t: {}'.format(best_t)) total_f1 += f1_test return total_f1 / nb_iter def class_avg_chainthaw(model, nb_classes, train, val, test, batch_size, loss, epoch_size, nb_epochs, checkpoint_weight_path, f1_init_weight_path, patience=5, initial_lr=0.001, next_lr=0.0001, seed=None, verbose=True): """ Finetunes given model using chain-thaw and evaluates using F1. For a dataset with multiple classes, the model is trained once for each class, relabeling those classes into a binary classification task. The result is an average of all F1 scores for each class. # Arguments: model: Model to be finetuned. nb_classes: Number of classes in the given dataset. train: Training data, given as a tuple of (inputs, outputs) val: Validation data, given as a tuple of (inputs, outputs) test: Testing data, given as a tuple of (inputs, outputs) batch_size: Batch size. loss: Loss function to be used during training. epoch_size: Number of samples in an epoch. nb_epochs: Number of epochs. checkpoint_weight_path: Filepath where weights will be checkpointed to during training. This file will be rewritten by the function. f1_init_weight_path: Filepath where weights will be saved to and reloaded from before training each class. This ensures that each class is trained independently. This file will be rewritten. initial_lr: Initial learning rate. Will only be used for the first training step (i.e. the softmax layer) next_lr: Learning rate for every subsequent step. seed: Random number generator seed. verbose: Verbosity flag. # Returns: Averaged F1 score. """ # Unpack args X_train, y_train = train X_val, y_val = val X_test, y_test = test total_f1 = 0 nb_iter = nb_classes if nb_classes > 2 else 1 model.save_weights(f1_init_weight_path) for i in range(nb_iter): if verbose: print('Iteration number {}/{}'.format(i + 1, nb_iter)) model.load_weights(f1_init_weight_path, by_name=False) y_train_new, y_val_new, y_test_new = prepare_labels(y_train, y_val, y_test, i, nb_classes) train_gen, X_val_resamp, y_val_resamp = \ prepare_generators(X_train, y_train_new, X_val, y_val_new, batch_size, epoch_size) if verbose: print("Training..") callbacks = finetuning_callbacks(checkpoint_weight_path, patience=patience, verbose=2) # Train using chain-thaw train_by_chain_thaw(model=model, train_gen=train_gen, val_data=(X_val_resamp, y_val_resamp), loss=loss, callbacks=callbacks, epoch_size=epoch_size, nb_epochs=nb_epochs, checkpoint_weight_path=checkpoint_weight_path, initial_lr=initial_lr, next_lr=next_lr, batch_size=batch_size, verbose=verbose) # Evaluate y_pred_val = np.array(model.predict(X_val, batch_size=batch_size)) y_pred_test = np.array(model.predict(X_test, batch_size=batch_size)) f1_test, best_t = find_f1_threshold(y_val_new, y_pred_val, y_test_new, y_pred_test) if verbose: print('f1_test: {}'.format(f1_test)) print('best_t: {}'.format(best_t)) total_f1 += f1_test return total_f1 / nb_iter
""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ import errno import os import re import sys from collections import namedtuple import msgfy from docker import APIClient from docker.errors import APIError, NotFound from path import Path from simplesqlite import OperationalError, connect_memdb from simplesqlite.model import Integer, Model, Text from simplesqlite.query import And, Where from subprocrunner import SubprocessRunner from ._common import is_execute_tc_command from ._const import TcCommandOutput from ._error import ContainerNotFoundError from ._logger import logger ContainerInfo = namedtuple("ContainerInfo", "id name pid ipaddr image state") class IfIndex(Model): host = Text(not_null=True) ifindex = Integer(primary_key=True) ifname = Text(not_null=True) peer_ifindex = Integer(not_null=True, unique=True) class DockerClient: @property def __netns_root_path(self): return Path("/var/run/netns") def __init__(self, tc_command_output=TcCommandOutput.NOT_SET): self.__client = APIClient(version="auto") self.__host_name = os.uname()[1] self.__tc_command_output = tc_command_output self.__con = connect_memdb() IfIndex.attach(self.__con) def exist_container(self, container): try: self.__verify_container(container) return True except ContainerNotFoundError: return False def verify_container(self, container, exit_on_exception=False): if not is_execute_tc_command(self.__tc_command_output): return try: self.__verify_container(container) except ContainerNotFoundError as e: if exit_on_exception: logger.error(msgfy.to_error_message(e)) sys.exit(errno.EPERM) raise def extract_running_container_names(self): running_container_name_list = [] for container in self.__get_containers(): if container.get("State") != "running": continue running_container_name_list.append(container["Names"][0].lstrip("/")) return running_container_name_list def extract_container_info(self, container): try: container_map = self.__client.inspect_container(container=container) except APIError as e: logger.error(e) sys.exit(1) container_name = container_map["Name"].lstrip("/") container_state = container_map["State"] container_info = ContainerInfo( id=container_map["Id"], name=container_name, pid=int(container_state["Pid"]), ipaddr=container_map["NetworkSettings"]["IPAddress"], image=container_map["Config"]["Image"], state=namedtuple("ContainerState", (k.lower() for k in container_state.keys()))( *container_state.values() ), ) return container_info def create_veth_table(self, container): try: self.__netns_root_path.makedirs_p() except PermissionError as e: logger.error(e) sys.exit(errno.EPERM) container_info = self.extract_container_info(container) logger.debug( "found container: name={}, pid={}".format(container_info.name, container_info.pid) ) try: netns_path = self.__get_netns_path(container_info.name) if not os.path.lexists(netns_path): logger.debug("make symlink to {}".format(netns_path)) try: Path("/proc/{:d}/ns/net".format(container_info.pid)).symlink(netns_path) except PermissionError as e: logger.error(e) sys.exit(errno.EPERM) return_code = self.__create_ifindex_table(container_info.name) if return_code != 0: sys.exit(return_code) return return_code finally: netns_path.remove_p() def select_veth(self, container_name): for container_record in IfIndex.select(where=Where("host", container_name)): yield from IfIndex.select( where=And( [ Where("host", self.__host_name), Where("ifindex", container_record.peer_ifindex), ] ) ) def fetch_veth_list(self, container_name): return [veth_record.ifname for veth_record in self.select_veth(container_name)] def __verify_container(self, container): if len(self.__get_containers()) == 0: raise ContainerNotFoundError() try: self.__client.inspect_container(container=container) except NotFound: raise ContainerNotFoundError(target=container) except APIError as e: logger.error(e) sys.exit(1) def __get_containers(self): try: return self.__client.containers() except APIError as e: logger.error(e) sys.exit(1) def __get_netns_path(self, container_name): return self.__netns_root_path / container_name def __create_ifindex_table(self, container_name): netns_path = self.__get_netns_path(container_name) try: netns_path.stat() except PermissionError as e: logger.error(e) return errno.EPERM IfIndex.create() proc = SubprocessRunner( "ip netns exec {ns} ip link show type veth".format(ns=container_name), dry_run=False ) if proc.run() != 0: logger.error(proc.stderr) return proc.returncode veth_groups_regexp = re.compile("([0-9]+): ([a-z0-9]+)@([a-z0-9]+): ") peer_ifindex_prefix_regexp = re.compile("^if") try: for i, line in enumerate(proc.stdout.splitlines()): match = veth_groups_regexp.search(line) if not match: continue logger.debug("parse veth @{} [{:02d}] {}".format(container_name, i, line)) ifindex, ifname, peer_ifindex = match.groups() IfIndex.insert( IfIndex( host=container_name, ifindex=int(ifindex), ifname=ifname, peer_ifindex=int(peer_ifindex_prefix_regexp.sub("", peer_ifindex)), ) ) proc = SubprocessRunner("ip link show type veth", dry_run=False) if proc.run() != 0: logger.error(proc.stderr) return proc.returncode for line in proc.stdout.splitlines(): logger.debug("parse veth @docker-host [{:02d}] {}".format(i, line)) match = veth_groups_regexp.search(line) if not match: continue ifindex, ifname, peer_ifindex = match.groups() try: IfIndex.insert( IfIndex( host=self.__host_name, ifindex=int(ifindex), ifname=ifname, peer_ifindex=int(peer_ifindex_prefix_regexp.sub("", peer_ifindex)), ) ) except OperationalError as e: logger.error(msgfy.to_error_message(e)) finally: IfIndex.commit() try: netns_path.remove_p() except PermissionError as e: logger.error(msgfy.to_error_message(e)) return errno.EPERM return 0
from __future__ import print_function from lazy import lazy from operator import itemgetter from ploy.common import BaseMaster, StartupScriptMixin from ploy.plain import Instance as BaseInstance from ploy.config import BaseMassager, BooleanMassager, IntegerMassager from ploy.config import HooksMassager, PathMassager from ploy.config import StartupScriptMassager import argparse import datetime import logging import os import re import sys import time log = logging.getLogger('ploy_ec2') re_hex_byte = '[0-9a-fA-F]{2}' re_fingerprint = "(?:%s:){15}%s" % (re_hex_byte, re_hex_byte) re_fingerprint_info = "^.*?(\d*)\s*(%s)(.*)$" % re_fingerprint fingerprint_regexp = re.compile(re_fingerprint_info, re.MULTILINE) fingerprint_type_regexp = re.compile("\((.*?)\)") def get_fingerprints(data): fingerprints = [] for match in fingerprint_regexp.findall(data): info = dict(keylen=match[0], fingerprint=match[1]) try: info['keylen'] = int(info['keylen']) except ValueError: info['keylen'] = None key_info = match[2].lower() if '(rsa1)' in key_info or 'ssh_host_key' in key_info: info['keytype'] = 'rsa1' elif '(rsa)' in key_info or 'ssh_host_rsa_key' in key_info: info['keytype'] = 'rsa' elif '(dsa)' in key_info or 'ssh_host_dsa_key' in key_info: info['keytype'] = 'dsa' elif '(ecdsa)' in key_info or 'ssh_host_ecdsa_key' in key_info: info['keytype'] = 'ecdsa' else: match = fingerprint_type_regexp.search(key_info) if match: info['keytype'] = match.group(1) fingerprints.append(info) return sorted(fingerprints, key=itemgetter('fingerprint')) class ConnMixin(object): @lazy def ec2_conn(self): region_id = self.config.get( 'region', self.master.master_config.get('region', None)) if region_id is None: log.error("No region set in ec2-instance:%s or ec2-master:%s config" % (self.id, self.master.id)) sys.exit(1) return self.master.get_ec2_conn(region_id) class Instance(BaseInstance, StartupScriptMixin, ConnMixin): max_startup_script_size = 16 * 1024 sectiongroupname = 'ec2-instance' def get_massagers(self): return get_instance_massagers() def get_console_output(self): return self.ec2_instance.get_console_output().output def get_fingerprints(self): output = self.ec2_instance.get_console_output().output if output is None or output.strip() == '': raise self.paramiko.SSHException('No console output (yet) for %s' % self.get_host()) return get_fingerprints(output) def get_fingerprint(self): for fingerprint in self.get_fingerprints(): if fingerprint.get('keytype') == 'rsa': return fingerprint['fingerprint'] raise self.paramiko.SSHException('Fingerprint not in console output of %s' % self.get_host()) @lazy def ec2_instance(self): ec2_instances = [] for reservation in self.ec2_conn.get_all_instances(): for ec2_instance in reservation.instances: if ec2_instance.state in ['shutting-down', 'terminated']: continue tags = getattr(ec2_instance, 'tags', {}) if not tags or not tags.get('Name'): groups = set(x.name for x in ec2_instance.groups) if groups != self.config['securitygroups']: continue else: if tags['Name'] != self.id: continue ec2_instances.append(ec2_instance) if len(ec2_instances) < 1: log.info("Instance '%s' unavailable.", self.id) return elif len(ec2_instances) > 1: log.warn("More than one instance found, using first.") ec2_instance = ec2_instances[0] log.info("Instance '%s' (%s) available.", self.id, ec2_instance.id) return ec2_instance def image(self): images = self.ec2_conn.get_all_images([self.config['image']]) return images[0] def securitygroups(self): sgs = [] for sgid in self.config.get('securitygroups', []): sgs.append(self.master.securitygroups.get(sgid, create=True)) return sgs def get_host(self): return self.ec2_instance.public_dns_name def _status(self): ec2_instance = self.ec2_instance if ec2_instance is None: return 'unavailable' return ec2_instance.state def status(self): ec2_instance = self.ec2_instance if ec2_instance is None: return status = self._status() if status != 'running': log.info("Instance state: %s", status) return log.info("Instance running.") log.info("Instances DNS name %s", ec2_instance.dns_name) log.info("Instances private DNS name %s", ec2_instance.private_dns_name) log.info("Instances public DNS name %s", ec2_instance.public_dns_name) output = ec2_instance.get_console_output().output if output is None or output.strip() == '': log.warn("Console output not (yet) available. SSH fingerprint verification not possible.") else: log.info("Console output available. SSH fingerprint verification possible.") def stop(self): from boto.exception import EC2ResponseError ec2_instance = self.ec2_instance if ec2_instance is None: return if ec2_instance.state != 'running': log.info("Instance state: %s", ec2_instance.state) log.info("Instance not stopped") return try: rc = self.ec2_conn.stop_instances([ec2_instance.id]) ec2_instance._update(rc[0]) except EC2ResponseError as e: log.error(e.error_message) if 'cannot be stopped' in e.error_message: log.error("Did you mean to terminate the instance?") log.info("Instance not stopped") return log.info("Instance stopped") def terminate(self): ec2_instance = self.ec2_instance if ec2_instance is None: return if ec2_instance.state not in ('running', 'stopped'): log.info("Instance state: %s", ec2_instance.state) log.info("Instance not terminated") return volumes_to_delete = [] if 'snapshots' in self.config and self.config.get('delete-volumes-on-terminate', False): snapshots = self.master.snapshots volumes = dict((x.volume_id, d) for d, x in ec2_instance.block_device_mapping.items()) for volume in self.ec2_conn.get_all_volumes(volume_ids=volumes.keys()): snapshot_id = volume.snapshot_id if snapshot_id in snapshots: volumes_to_delete.append(volume) rc = self.ec2_conn.terminate_instances([ec2_instance.id]) ec2_instance._update(rc[0]) log.info("Instance terminating") if len(volumes_to_delete): log.info("Instance terminating, waiting until it's terminated") while ec2_instance.state != 'terminated': time.sleep(5) sys.stdout.write(".") sys.stdout.flush() ec2_instance.update() sys.stdout.write("\n") sys.stdout.flush() log.info("Instance terminated") for volume in volumes_to_delete: log.info("Deleting volume %s", volume.id) volume.delete() def start(self, overrides=None): config = self.get_config(overrides) placement = config['placement'] ec2_instance = self.ec2_instance if ec2_instance is not None: log.info("Instance state: %s", ec2_instance.state) if ec2_instance.state == 'stopping': log.info("The instance is currently stopping") return if ec2_instance.state == 'stopped': log.info("Starting stopped instance '%s'" % self.id) ec2_instance.modify_attribute('instanceType', config.get('instance_type', 'm1.small')) if 'device_map' in config: ec2_instance.modify_attribute('blockDeviceMapping', config.get('device_map', None)) ec2_instance.start() else: log.info("Instance already started, waiting until it's available") else: log.info("Creating instance '%s'" % self.id) reservation = self.image().run( 1, 1, config['keypair'], instance_type=config.get('instance_type', 'm1.small'), block_device_map=config.get('device_map', None), security_groups=self.securitygroups(), user_data=self.startup_script(overrides=overrides), placement=placement) ec2_instance = reservation.instances[0] log.info("Instance '%s' created, waiting until it's available", ec2_instance.id) while ec2_instance.state != 'running': if ec2_instance.state != 'pending': log.error("Something went wrong, instance status: %s", ec2_instance.state) return time.sleep(5) sys.stdout.write(".") sys.stdout.flush() ec2_instance.update() sys.stdout.write("\n") sys.stdout.flush() self.ec2_conn.create_tags([ec2_instance.id], {"Name": self.id}) ip = config.get('ip', None) if ip is not None: addresses = [x for x in self.ec2_conn.get_all_addresses() if x.public_ip == ip] if len(addresses) > 0: if addresses[0].instance_id != ec2_instance.id: if ec2_instance.use_ip(addresses[0]): log.info("Assigned IP %s to instance '%s'", addresses[0].public_ip, self.id) else: log.error("Couldn't assign IP %s to instance '%s'", addresses[0].public_ip, self.id) return volumes = dict((x.id, x) for x in self.ec2_conn.get_all_volumes()) for volume_id, device in config.get('volumes', []): if volume_id not in volumes: try: volume = self.master.volumes[volume_id].volume(placement) except KeyError: log.error("Unknown volume %s" % volume_id) return else: volume = volumes[volume_id] if volume_id != volume.id: volume_id = "%s (%s)" % (volume_id, volume.id) if volume.attachment_state() == 'attached': if volume.attach_data.instance_id == ec2_instance.id: continue log.error( "Volume %s already attached to instance %s.", volume.id, volume.attach_data.instance_id) sys.exit(1) log.info("Attaching storage %s on %s" % (volume_id, device)) self.ec2_conn.attach_volume(volume.id, ec2_instance.id, device) snapshots = dict((x.id, x) for x in self.ec2_conn.get_all_snapshots(owner="self")) for snapshot_id, device in config.get('snapshots', []): if snapshot_id not in snapshots: log.error("Unknown snapshot %s" % snapshot_id) return log.info("Creating volume from snapshot: %s" % snapshot_id) snapshot = snapshots[snapshot_id] volume = self.ec2_conn.create_volume(snapshot.volume_size, placement, snapshot_id) log.info("Attaching storage (%s on %s)" % (volume.id, device)) self.ec2_conn.attach_volume(volume.id, ec2_instance.id, device) return ec2_instance def snapshot(self, devs=None): if devs is None: devs = set() else: devs = set(devs) volume_ids = [x[0] for x in self.config.get('volumes', []) if x[1] in devs] volumes = dict((x.id, x) for x in self.ec2_conn.get_all_volumes(volume_ids=volume_ids)) for volume_id in volume_ids: volume = volumes[volume_id] date = datetime.datetime.now().strftime("%Y%m%d%H%M") description = "%s-%s" % (date, volume_id) log.info("Creating snapshot for volume %s on %s (%s)" % (volume_id, self.id, description)) volume.create_snapshot(description=description) class Connection(ConnMixin): """ This is more or less a dummy object to get a connection to AWS for Fabric scripts. """ def __init__(self, master, sid, config): self.id = sid self.master = master self.config = config def get_host(self): return None class Volume(object): def __init__(self, name, config, master): self.name = name self.config = config self.master = master def volume(self, placement): volumes = {} for volume in self.master.ec2_conn.get_all_volumes(): name_tag = volume.tags.get('Name') if not name_tag: continue volumes[name_tag] = volume if self.name in volumes: return volumes[self.name] if 'size' not in self.config: log.error("Missing option 'size' for [ec2-volume:%s].", self.name) volume = self.master.ec2_conn.create_volume( self.config['size'], placement, snapshot=self.config.get('snapshot'), volume_type=self.config.get('volume_type'), iops=self.config.get('iops'), encrypted=self.config.get('encrypted')) self.master.ec2_conn.create_tags(volume.id, {'Name': self.name}) return volume def __contains__(self, name): return name in self.volumes class InfoBase(object): def __init__(self, master): self.master = master self.config = self.master.main_config.get(self.sectiongroupname, {}) self._cache = {} def __getitem__(self, key): if key not in self._cache: self._cache[key] = self.klass(key, self.config[key], self.master) return self._cache[key] class Volumes(InfoBase): sectiongroupname = 'ec2-volume' klass = Volume def __init__(self, master): InfoBase.__init__(self, master) class Securitygroups(object): def __init__(self, master): self.master = master self.update() def update(self): self.securitygroups = dict((x.name, x) for x in self.master.ec2_conn.get_all_security_groups()) def get(self, sgid, create=False): if 'ec2-securitygroup' not in self.master.main_config: log.error("No security groups defined in configuration.") sys.exit(1) securitygroup = self.master.main_config['ec2-securitygroup'][sgid] if sgid not in self.securitygroups: if not create: raise KeyError if 'description' in securitygroup: description = securitygroup['description'] else: description = "security settings for %s" % sgid sg = self.master.ec2_conn.create_security_group(sgid, description) self.update() else: sg = self.securitygroups[sgid] if create: from boto.ec2.securitygroup import GroupOrCIDR rules = {} for rule in sg.rules: for grant in rule.grants: if grant.cidr_ip: key = ( rule.ip_protocol, int(rule.from_port), int(rule.to_port), grant.cidr_ip) else: key = ( rule.ip_protocol, int(rule.from_port), int(rule.to_port), grant.name) rules[key] = (rule, grant) # cleanup rules from config connections = [] for connection in securitygroup['connections']: if connection[3].endswith("-%s" % sg.owner_id): # backward compatibility, strip the owner_id connection = ( connection[0], connection[1], connection[2], connection[3].rstrip("-%s" % sg.owner_id)) connections.append(connection) # delete rules which aren't defined in the config for connection in set(rules).difference(connections): rule, grant = rules[connection] status = sg.revoke( ip_protocol=rule.ip_protocol, from_port=int(rule.from_port), to_port=int(rule.to_port), cidr_ip=grant.cidr_ip, src_group=grant) if status: del rules[connection] for connection in connections: if connection in rules: continue cidr_ip = None src_group = None if '/' in connection[3]: cidr_ip = connection[3] else: src_group = GroupOrCIDR() src_group.name = connection[3] src_group.ownerid = sg.owner_id sg.authorize( ip_protocol=connection[0], from_port=connection[1], to_port=connection[2], cidr_ip=cidr_ip, src_group=src_group) return sg class MasterConnection(BaseInstance, ConnMixin): def status(self): instances = {} known = {} unknown = set() for reservation in self.ec2_conn.get_all_instances(): for ec2_instance in reservation.instances: instance = instances.setdefault(ec2_instance.id, {}) instance['id'] = ec2_instance.id instance['status'] = ec2_instance.state instance['ip'] = ec2_instance.ip_address tags = getattr(ec2_instance, 'tags', {}) name = instance['name'] = tags['Name'] if name in self.master.ctrl.instances: known.setdefault(name, set()).add(ec2_instance.id) else: unknown.add(ec2_instance.id) for name in sorted(self.master.instances): if name == self.id: continue if name in known: infos = [instances[x] for x in known[name]] else: infos = [dict( id='n/a', status='terminated', name=name, ip=self.master.instances[name].config.get('ip'))] for info in infos: log.info("%-10s %-20s %15s %15s" % (info['id'], info['name'], info['status'], info['ip'])) if unknown: log.warn("Unknown instances:") for iid in unknown: instance = instances[iid] log.warn("%-10s %-20s %15s %15s" % (iid, instance['name'], instance['status'], instance['ip'])) class Master(BaseMaster): sectiongroupname = 'ec2-master' section_info = { None: Instance, 'ec2-instance': Instance, 'ec2-connection': Connection} def __init__(self, *args, **kwargs): BaseMaster.__init__(self, *args, **kwargs) self.instance = MasterConnection(self, self.id, self.master_config) self.instance.sectiongroupname = 'ez-master' self.instances[self.id] = self.instance @lazy def credentials(self): aws_id = None aws_key = None if 'AWS_ACCESS_KEY_ID' not in os.environ or 'AWS_SECRET_ACCESS_KEY' not in os.environ: try: id_file = self.master_config['access-key-id'] key_file = self.master_config['secret-access-key'] except KeyError: log.error("You need to either set the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables or add the path to files containing them to the config. You can find the values at http://aws.amazon.com under 'Your Account'-'Security Credentials'.") sys.exit(1) id_file = os.path.abspath(os.path.expanduser(id_file)) if not os.path.exists(id_file): log.error("The access-key-id file at '%s' doesn't exist.", id_file) sys.exit(1) key_file = os.path.abspath(os.path.expanduser(key_file)) if not os.path.exists(key_file): log.error("The secret-access-key file at '%s' doesn't exist.", key_file) sys.exit(1) aws_id = open(id_file).readline().strip() aws_key = open(key_file).readline().strip() return (aws_id, aws_key) @lazy def regions(self): from boto.ec2 import regions (aws_id, aws_key) = self.credentials return dict((x.name, x) for x in regions( aws_access_key_id=aws_id, aws_secret_access_key=aws_key )) @property def snapshots(self): return dict((x.id, x) for x in self.ec2_conn.get_all_snapshots(owner="self")) def get_ec2_conn(self, region_id): (aws_id, aws_key) = self.credentials try: region = self.regions[region_id] except KeyError: log.error("Region '%s' not found in regions returned by EC2.", region_id) sys.exit(1) return region.connect( aws_access_key_id=aws_id, aws_secret_access_key=aws_key ) @lazy def ec2_conn(self): region_id = self.master_config.get('region', None) if region_id is None: log.error("No region set in ec2-master:%s config" % self.id) sys.exit(1) return self.get_ec2_conn(region_id) @lazy def securitygroups(self): return Securitygroups(self) @lazy def volumes(self): return Volumes(self) class SecuritygroupsMassager(BaseMassager): def __call__(self, config, sectionname): value = BaseMassager.__call__(self, config, sectionname) securitygroups = [] for securitygroup in value.split(','): securitygroups.append(securitygroup.strip()) return set(securitygroups) class DevicemapMassager(BaseMassager): def __call__(self, config, sectionname): from boto.ec2.blockdevicemapping import BlockDeviceMapping from boto.ec2.blockdevicemapping import BlockDeviceType value = BaseMassager.__call__(self, config, sectionname) device_map = BlockDeviceMapping() for mapping in value.split(): device_path, ephemeral_name = mapping.split(':') device = BlockDeviceType() device.ephemeral_name = ephemeral_name device_map[device_path] = device return device_map class VolumesMassager(BaseMassager): def __call__(self, config, sectionname): value = BaseMassager.__call__(self, config, sectionname) volumes = [] for line in value.split('\n'): volume = line.split() if not len(volume): continue volumes.append((volume[0], volume[1])) return tuple(volumes) class SnapshotsMassager(BaseMassager): def __call__(self, config, sectionname): value = BaseMassager.__call__(self, config, sectionname) snapshots = [] for line in value.split('\n'): snapshot = line.split() if not len(snapshot): continue snapshots.append((snapshot[0], snapshot[1])) return tuple(snapshots) class ConnectionsMassager(BaseMassager): def __call__(self, config, sectionname): value = BaseMassager.__call__(self, config, sectionname) connections = [] for line in value.split('\n'): connection = line.split() if not len(connection): continue connections.append((connection[0], int(connection[1]), int(connection[2]), connection[3])) return tuple(connections) class ListSnapshotsCmd(object): def __init__(self, ctrl): self.ctrl = ctrl def __call__(self, argv, help): parser = argparse.ArgumentParser( prog="%s list snapshots" % self.ctrl.progname, description=help) parser.parse_args(argv) snapshots = [] for master in self.ctrl.get_masters('snapshots'): snapshots.extend(master.snapshots.values()) snapshots = sorted(snapshots, key=lambda x: x.start_time) print("id time size volume progress description") for snapshot in snapshots: info = snapshot.__dict__ print("{id} {start_time} {volume_size:>4} GB {volume_id} {progress:>8} {description}".format(**info)) def get_instance_massagers(sectiongroupname='instance'): return [ HooksMassager(sectiongroupname, 'hooks'), PathMassager(sectiongroupname, 'ssh-key-filename'), StartupScriptMassager(sectiongroupname, 'startup_script'), SecuritygroupsMassager(sectiongroupname, 'securitygroups'), VolumesMassager(sectiongroupname, 'volumes'), DevicemapMassager(sectiongroupname, 'device_map'), SnapshotsMassager(sectiongroupname, 'snapshots'), BooleanMassager(sectiongroupname, 'delete-volumes-on-terminate')] def get_list_commands(ctrl): return [ ('snapshots', ListSnapshotsCmd(ctrl))] def get_massagers(): massagers = [] sectiongroupname = 'ec2-master' massagers.extend([ PathMassager(sectiongroupname, 'access-key-id'), PathMassager(sectiongroupname, 'secret-access-key')]) sectiongroupname = 'ec2-instance' massagers.extend(get_instance_massagers(sectiongroupname)) sectiongroupname = 'ec2-securitygroup' massagers.extend([ ConnectionsMassager(sectiongroupname, 'connections')]) sectiongroupname = 'ec2-volume' massagers.extend([ IntegerMassager(sectiongroupname, 'size'), IntegerMassager(sectiongroupname, 'iops'), BooleanMassager(sectiongroupname, 'encrypted')]) return massagers def get_macro_cleaners(main_config): def clean_instance(macro): for key in macro.keys(): if key in ('ip', 'volumes'): del macro[key] return {"ec2-instance": clean_instance} def get_masters(ctrl): masters = ctrl.config.get('ec2-master', {}) for master, master_config in masters.items(): yield Master(ctrl, master, master_config) plugin = dict( get_list_commands=get_list_commands, get_massagers=get_massagers, get_macro_cleaners=get_macro_cleaners, get_masters=get_masters)
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import numpy as np import os import re import subprocess import sys def wait_for_output(proc): """This is a convenience method to parse a process's stdout and stderr. Args: proc: A process started by subprocess.Popen. Returns: A tuple of the stdout and stderr of the process as strings. """ stdout_data, stderr_data = proc.communicate() if stdout_data is not None: try: # NOTE(rkn): This try/except block is here because I once saw an # exception raised here and want to print more information if that # happens again. stdout_data = stdout_data.decode("ascii") except UnicodeDecodeError: raise Exception("Failed to decode stdout_data:", stdout_data) if stderr_data is not None: try: # NOTE(rkn): This try/except block is here because I once saw an # exception raised here and want to print more information if that # happens again. stderr_data = stderr_data.decode("ascii") except UnicodeDecodeError: raise Exception("Failed to decode stderr_data:", stderr_data) return stdout_data, stderr_data class DockerRunner(object): """This class manages the logistics of running multiple nodes in Docker. This class is used for starting multiple Ray nodes within Docker, stopping Ray, running a workload, and determining the success or failure of the workload. Attributes: head_container_id: The ID of the docker container that runs the head node. worker_container_ids: A list of the docker container IDs of the Ray worker nodes. head_container_ip: The IP address of the docker container that runs the head node. """ def __init__(self): """Initialize the DockerRunner.""" self.head_container_id = None self.worker_container_ids = [] self.head_container_ip = None def _get_container_id(self, stdout_data): """Parse the docker container ID from stdout_data. Args: stdout_data: This should be a string with the standard output of a call to a docker command. Returns: The container ID of the docker container. """ p = re.compile("([0-9a-f]{64})\n") m = p.match(stdout_data) if m is None: return None else: return m.group(1) def _get_container_ip(self, container_id): """Get the IP address of a specific docker container. Args: container_id: The docker container ID of the relevant docker container. Returns: The IP address of the container. """ proc = subprocess.Popen(["docker", "inspect", "--format={{.NetworkSettings.Networks.bridge" ".IPAddress}}", container_id], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout_data, _ = wait_for_output(proc) p = re.compile("([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})") m = p.match(stdout_data) if m is None: raise RuntimeError("Container IP not found.") else: return m.group(1) def _start_head_node(self, docker_image, mem_size, shm_size, num_redis_shards, num_cpus, num_gpus, development_mode): """Start the Ray head node inside a docker container.""" mem_arg = ["--memory=" + mem_size] if mem_size else [] shm_arg = ["--shm-size=" + shm_size] if shm_size else [] volume_arg = (["-v", "{}:{}".format(os.path.dirname( os.path.realpath(__file__)), "/ray/test/jenkins_tests")] if development_mode else []) command = (["docker", "run", "-d"] + mem_arg + shm_arg + volume_arg + [docker_image, "ray", "start", "--head", "--block", "--redis-port=6379", "--num-redis-shards={}".format(num_redis_shards), "--num-cpus={}".format(num_cpus), "--num-gpus={}".format(num_gpus), "--no-ui"]) print("Starting head node with command:{}".format(command)) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout_data, _ = wait_for_output(proc) container_id = self._get_container_id(stdout_data) if container_id is None: raise RuntimeError("Failed to find container ID.") self.head_container_id = container_id self.head_container_ip = self._get_container_ip(container_id) def _start_worker_node(self, docker_image, mem_size, shm_size, num_cpus, num_gpus, development_mode): """Start a Ray worker node inside a docker container.""" mem_arg = ["--memory=" + mem_size] if mem_size else [] shm_arg = ["--shm-size=" + shm_size] if shm_size else [] volume_arg = (["-v", "{}:{}".format(os.path.dirname( os.path.realpath(__file__)), "/ray/test/jenkins_tests")] if development_mode else []) command = (["docker", "run", "-d"] + mem_arg + shm_arg + volume_arg + ["--shm-size=" + shm_size, docker_image, "ray", "start", "--block", "--redis-address={:s}:6379".format(self.head_container_ip), "--num-cpus={}".format(num_cpus), "--num-gpus={}".format(num_gpus)]) print("Starting worker node with command:{}".format(command)) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout_data, _ = wait_for_output(proc) container_id = self._get_container_id(stdout_data) if container_id is None: raise RuntimeError("Failed to find container id") self.worker_container_ids.append(container_id) def start_ray(self, docker_image=None, mem_size=None, shm_size=None, num_nodes=None, num_redis_shards=1, num_cpus=None, num_gpus=None, development_mode=None): """Start a Ray cluster within docker. This starts one docker container running the head node and num_nodes - 1 docker containers running the Ray worker nodes. Args: docker_image: The docker image to use for all of the nodes. mem_size: The amount of memory to start each docker container with. This will be passed into `docker run` as the --memory flag. If this is None, then no --memory flag will be used. shm_size: The amount of shared memory to start each docker container with. This will be passed into `docker run` as the `--shm-size` flag. num_nodes: The number of nodes to use in the cluster (this counts the head node as well). num_redis_shards: The number of Redis shards to use on the head node. num_cpus: A list of the number of CPUs to start each node with. num_gpus: A list of the number of GPUs to start each node with. development_mode: True if you want to mount the local copy of test/jenkins_test on the head node so we can avoid rebuilding docker images during development. """ assert len(num_cpus) == num_nodes assert len(num_gpus) == num_nodes # Launch the head node. self._start_head_node(docker_image, mem_size, shm_size, num_redis_shards, num_cpus[0], num_gpus[0], development_mode) # Start the worker nodes. for i in range(num_nodes - 1): self._start_worker_node(docker_image, mem_size, shm_size, num_cpus[1 + i], num_gpus[1 + i], development_mode) def _stop_node(self, container_id): """Stop a node in the Ray cluster.""" proc = subprocess.Popen(["docker", "kill", container_id], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout_data, _ = wait_for_output(proc) stopped_container_id = self._get_container_id(stdout_data) if not container_id == stopped_container_id: raise Exception("Failed to stop container {}." .format(container_id)) proc = subprocess.Popen(["docker", "rm", "-f", container_id], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout_data, _ = wait_for_output(proc) removed_container_id = self._get_container_id(stdout_data) if not container_id == removed_container_id: raise Exception("Failed to remove container {}." .format(container_id)) print("stop_node", {"container_id": container_id, "is_head": container_id == self.head_container_id}) def stop_ray(self): """Stop the Ray cluster.""" success = True try: self._stop_node(self.head_container_id) except: success = False for container_id in self.worker_container_ids: try: self._stop_node(container_id) except: success = False return success def run_test(self, test_script, num_drivers, driver_locations=None): """Run a test script. Run a test using the Ray cluster. Args: test_script: The test script to run. num_drivers: The number of copies of the test script to run. driver_locations: A list of the indices of the containers that the different copies of the test script should be run on. If this is None, then the containers will be chosen randomly. Returns: A dictionary with information about the test script run. """ all_container_ids = ([self.head_container_id] + self.worker_container_ids) if driver_locations is None: driver_locations = [np.random.randint(0, len(all_container_ids)) for _ in range(num_drivers)] # Start the different drivers. driver_processes = [] for i in range(len(driver_locations)): # Get the container ID to run the ith driver in. container_id = all_container_ids[driver_locations[i]] command = ["docker", "exec", container_id, "/bin/bash", "-c", ("RAY_REDIS_ADDRESS={}:6379 RAY_DRIVER_INDEX={} python " "{}".format(self.head_container_ip, i, test_script))] print("Starting driver with command {}.".format(test_script)) # Start the driver. p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) driver_processes.append(p) # Wait for the drivers to finish. results = [] for p in driver_processes: stdout_data, stderr_data = wait_for_output(p) print("STDOUT:") print(stdout_data) print("STDERR:") print(stderr_data) results.append({"success": p.returncode == 0, "return_code": p.returncode}) return results if __name__ == "__main__": parser = argparse.ArgumentParser( description="Run multinode tests in Docker.") parser.add_argument("--docker-image", default="ray-project/deploy", help="docker image") parser.add_argument("--mem-size", help="memory size") parser.add_argument("--shm-size", default="1G", help="shared memory size") parser.add_argument("--num-nodes", default=1, type=int, help="number of nodes to use in the cluster") parser.add_argument("--num-redis-shards", default=1, type=int, help=("the number of Redis shards to start on the " "head node")) parser.add_argument("--num-cpus", type=str, help=("a comma separated list of values representing " "the number of CPUs to start each node with")) parser.add_argument("--num-gpus", type=str, help=("a comma separated list of values representing " "the number of GPUs to start each node with")) parser.add_argument("--num-drivers", default=1, type=int, help="number of drivers to run") parser.add_argument("--driver-locations", type=str, help=("a comma separated list of indices of the " "containers to run the drivers in")) parser.add_argument("--test-script", required=True, help="test script") parser.add_argument("--development-mode", action="store_true", help="use local copies of the test scripts") args = parser.parse_args() # Parse the number of CPUs and GPUs to use for each worker. num_nodes = args.num_nodes num_cpus = ([int(i) for i in args.num_cpus.split(",")] if args.num_cpus is not None else num_nodes * [10]) num_gpus = ([int(i) for i in args.num_gpus.split(",")] if args.num_gpus is not None else num_nodes * [0]) # Parse the driver locations. driver_locations = (None if args.driver_locations is None else [int(i) for i in args.driver_locations.split(",")]) d = DockerRunner() d.start_ray(docker_image=args.docker_image, mem_size=args.mem_size, shm_size=args.shm_size, num_nodes=num_nodes, num_redis_shards=args.num_redis_shards, num_cpus=num_cpus, num_gpus=num_gpus, development_mode=args.development_mode) try: run_results = d.run_test(args.test_script, args.num_drivers, driver_locations=driver_locations) finally: successfully_stopped = d.stop_ray() any_failed = False for run_result in run_results: if "success" in run_result and run_result["success"]: print("RESULT: Test {} succeeded.".format(args.test_script)) else: print("RESULT: Test {} failed.".format(args.test_script)) any_failed = True if any_failed: sys.exit(1) elif not successfully_stopped: print("There was a failure when attempting to stop the containers.") sys.exit(1) else: sys.exit(0)
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import logging import os import shutil import ssl import sys import tempfile import threading import zipfile from contextlib import contextmanager from pathlib import Path from queue import Queue from socketserver import TCPServer from typing import IO, Any, Callable, Iterator, Mapping, Tuple, Type from colors import green from pants.util.dirutil import safe_delete class InvalidZipPath(ValueError): """Indicates a bad zip file path.""" @contextmanager def environment_as(**kwargs: str | None) -> Iterator[None]: """Update the environment to the supplied values, for example: with environment_as(PYTHONPATH='foo:bar:baz', PYTHON='/usr/bin/python2.7'): subprocess.Popen(foo).wait() """ new_environment = kwargs old_environment = {} def setenv(key: str, val: str | None) -> None: if val is not None: os.environ[key] = val else: if key in os.environ: del os.environ[key] for key, val in new_environment.items(): old_environment[key] = os.environ.get(key) setenv(key, val) try: yield finally: for key, val in old_environment.items(): setenv(key, val) def _purge_env() -> None: # N.B. Without the use of `del` here (which calls `os.unsetenv` under the hood), subprocess # invokes or other things that may access the environment at the C level may not see the # correct env vars (i.e. we can't just replace os.environ with an empty dict). # See https://docs.python.org/3/library/os.html#os.unsetenv for more info. # # Wraps iterable in list() to make a copy and avoid issues with deleting while iterating. for k in list(os.environ.keys()): del os.environ[k] def _restore_env(env: Mapping[str, str]) -> None: for k, v in env.items(): os.environ[k] = v @contextmanager def hermetic_environment_as(**kwargs: str | None) -> Iterator[None]: """Set the environment to the supplied values from an empty state.""" old_environment = os.environ.copy() _purge_env() try: with environment_as(**kwargs): yield finally: _purge_env() _restore_env(old_environment) @contextmanager def argv_as(args: Tuple[str, ...]) -> Iterator[None]: """Temporarily set `sys.argv` to the supplied value.""" old_args = sys.argv try: sys.argv = list(args) yield finally: sys.argv = old_args @contextmanager def temporary_dir( root_dir: str | None = None, cleanup: bool = True, suffix: str | None = None, permissions: int | None = None, prefix: str | None = tempfile.template, ) -> Iterator[str]: """A with-context that creates a temporary directory. :API: public You may specify the following keyword args: :param root_dir: The parent directory to create the temporary directory. :param cleanup: Whether or not to clean up the temporary directory. :param permissions: If provided, sets the directory permissions to this mode. """ path = tempfile.mkdtemp(dir=root_dir, suffix=suffix, prefix=prefix) try: if permissions is not None: os.chmod(path, permissions) yield path finally: if cleanup: shutil.rmtree(path, ignore_errors=True) @contextmanager def temporary_file_path( root_dir: str | None = None, cleanup: bool = True, suffix: str | None = None, permissions: int | None = None, ) -> Iterator[str]: """A with-context that creates a temporary file and returns its path. :API: public You may specify the following keyword args: :param root_dir: The parent directory to create the temporary file. :param cleanup: Whether or not to clean up the temporary file. """ with temporary_file(root_dir, cleanup=cleanup, suffix=suffix, permissions=permissions) as fd: fd.close() yield fd.name @contextmanager def temporary_file( root_dir: str | None = None, cleanup: bool = True, suffix: str | None = None, permissions: int | None = None, binary_mode: bool = True, ) -> Iterator[IO]: """A with-context that creates a temporary file and returns a writeable file descriptor to it. You may specify the following keyword args: :param root_dir: The parent directory to create the temporary file. :param cleanup: Whether or not to clean up the temporary file. :param suffix: If suffix is specified, the file name will end with that suffix. Otherwise there will be no suffix. mkstemp() does not put a dot between the file name and the suffix; if you need one, put it at the beginning of suffix. See :py:class:`tempfile.NamedTemporaryFile`. :param permissions: If provided, sets the file to use these permissions. :param binary_mode: Whether file opens in binary or text mode. """ mode = "w+b" if binary_mode else "w+" # tempfile's default is 'w+b' with tempfile.NamedTemporaryFile(suffix=suffix, dir=root_dir, delete=False, mode=mode) as fd: try: if permissions is not None: os.chmod(fd.name, permissions) yield fd finally: if cleanup: safe_delete(fd.name) @contextmanager def overwrite_file_content( file_path: str | Path, temporary_content: bytes | str | Callable[[bytes], bytes] | None = None, ) -> Iterator[None]: """A helper that resets a file after the method runs. It will read a file, save the content, maybe write temporary_content to it, yield, then write the original content to the file. :param file_path: Absolute path to the file to be reset after the method runs. :param temporary_content: Content to write to the file, or a function from current content to new temporary content. """ file_path = Path(file_path) original_content = file_path.read_bytes() try: if temporary_content is not None: if callable(temporary_content): content = temporary_content(original_content) elif isinstance(temporary_content, bytes): content = temporary_content else: content = temporary_content.encode() file_path.write_bytes(content) yield finally: file_path.write_bytes(original_content) @contextmanager def pushd(directory: str) -> Iterator[str]: """A with-context that encapsulates pushd/popd.""" cwd = os.getcwd() os.chdir(directory) try: yield directory finally: os.chdir(cwd) @contextmanager def open_zip(path_or_file: str | Any, *args, **kwargs) -> Iterator[zipfile.ZipFile]: """A with-context for zip files. Passes through *args and **kwargs to zipfile.ZipFile. :API: public :param path_or_file: Full path to zip file. :param args: Any extra args accepted by `zipfile.ZipFile`. :param kwargs: Any extra keyword args accepted by `zipfile.ZipFile`. :raises: `InvalidZipPath` if path_or_file is invalid. :raises: `zipfile.BadZipfile` if zipfile.ZipFile cannot open a zip at path_or_file. """ if not path_or_file: raise InvalidZipPath(f"Invalid zip location: {path_or_file}") if "allowZip64" not in kwargs: kwargs["allowZip64"] = True try: zf = zipfile.ZipFile(path_or_file, *args, **kwargs) except zipfile.BadZipfile as bze: # Use the realpath in order to follow symlinks back to the problem source file. raise zipfile.BadZipfile(f"Bad Zipfile {os.path.realpath(path_or_file)}: {bze}") try: yield zf finally: zf.close() @contextmanager def maybe_profiled(profile_path: str | None) -> Iterator[None]: """A profiling context manager. :param profile_path: The path to write profile information to. If `None`, this will no-op. """ if not profile_path: yield return import cProfile profiler = cProfile.Profile() try: profiler.enable() yield finally: profiler.disable() profiler.dump_stats(profile_path) view_cmd = green( "gprof2dot -f pstats {path} | dot -Tpng -o {path}.png && open {path}.png".format( path=profile_path ) ) logging.getLogger().info( f"Dumped profile data to: {profile_path}\nUse e.g. {view_cmd} to render and view." ) @contextmanager def http_server(handler_class: Type, ssl_context: ssl.SSLContext | None = None) -> Iterator[int]: def serve(port_queue: "Queue[int]", shutdown_queue: "Queue[bool]") -> None: httpd = TCPServer(("", 0), handler_class) httpd.timeout = 0.1 if ssl_context: httpd.socket = ssl_context.wrap_socket(httpd.socket, server_side=True) port_queue.put(httpd.server_address[1]) while shutdown_queue.empty(): httpd.handle_request() port_queue: "Queue[int]" = Queue() shutdown_queue: "Queue[bool]" = Queue() t = threading.Thread(target=lambda: serve(port_queue, shutdown_queue)) t.daemon = True t.start() try: yield port_queue.get(block=True) finally: shutdown_queue.put(True) t.join()
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ The worker communicates with the scheduler and does two things: 1. Sends all tasks that has to be run 2. Gets tasks from the scheduler that should be run When running in local mode, the worker talks directly to a :py:class:`~luigi.scheduler.Scheduler` instance. When you run a central server, the worker will talk to the scheduler using a :py:class:`~luigi.rpc.RemoteScheduler` instance. Everything in this module is private to luigi and may change in incompatible ways between versions. The exception is the exception types and the :py:class:`worker` config class. """ import collections import getpass import logging import multiprocessing # Note: this seems to have some stability issues: https://github.com/spotify/luigi/pull/438 import os import signal import subprocess import sys try: import Queue except ImportError: import queue as Queue import random import socket import threading import time import traceback import types from luigi import six from luigi import notifications from luigi.event import Event from luigi.task_register import load_task from luigi.scheduler import DISABLED, DONE, FAILED, PENDING, UNKNOWN, Scheduler, RetryPolicy from luigi.target import Target from luigi.task import Task, flatten, getpaths, Config from luigi.task_register import TaskClassException from luigi.task_status import RUNNING from luigi.parameter import FloatParameter, IntParameter, BoolParameter try: import simplejson as json except ImportError: import json logger = logging.getLogger('luigi-interface') # Prevent fork() from being called during a C-level getaddrinfo() which uses a process-global mutex, # that may not be unlocked in child process, resulting in the process being locked indefinitely. fork_lock = threading.Lock() # Why we assert on _WAIT_INTERVAL_EPS: # multiprocessing.Queue.get() is undefined for timeout=0 it seems: # https://docs.python.org/3.4/library/multiprocessing.html#multiprocessing.Queue.get. # I also tried with really low epsilon, but then ran into the same issue where # the test case "test_external_dependency_worker_is_patient" got stuck. So I # unscientifically just set the final value to a floating point number that # "worked for me". _WAIT_INTERVAL_EPS = 0.00001 def _is_external(task): return task.run is None or task.run == NotImplemented def _get_retry_policy_dict(task): return RetryPolicy(task.retry_count, task.disable_hard_timeout, task.disable_window_seconds)._asdict() class TaskException(Exception): pass class TaskProcess(multiprocessing.Process): """ Wrap all task execution in this class. Mainly for convenience since this is run in a separate process. """ def __init__(self, task, worker_id, result_queue, tracking_url_callback, status_message_callback, random_seed=False, worker_timeout=0): super(TaskProcess, self).__init__() self.task = task self.worker_id = worker_id self.result_queue = result_queue self.tracking_url_callback = tracking_url_callback self.status_message_callback = status_message_callback self.random_seed = random_seed if task.worker_timeout is not None: worker_timeout = task.worker_timeout self.timeout_time = time.time() + worker_timeout if worker_timeout else None def _run_get_new_deps(self): self.task.set_tracking_url = self.tracking_url_callback self.task.set_status_message = self.status_message_callback task_gen = self.task.run() self.task.set_tracking_url = None self.task.set_status_message = None if not isinstance(task_gen, types.GeneratorType): return None next_send = None while True: try: if next_send is None: requires = six.next(task_gen) else: requires = task_gen.send(next_send) except StopIteration: return None new_req = flatten(requires) if all(t.complete() for t in new_req): next_send = getpaths(requires) else: new_deps = [(t.task_module, t.task_family, t.to_str_params()) for t in new_req] return new_deps def run(self): logger.info('[pid %s] Worker %s running %s', os.getpid(), self.worker_id, self.task) if self.random_seed: # Need to have different random seeds if running in separate processes random.seed((os.getpid(), time.time())) status = FAILED expl = '' missing = [] new_deps = [] try: # Verify that all the tasks are fulfilled! For external tasks we # don't care about unfulfilled dependencies, because we are just # checking completeness of self.task so outputs of dependencies are # irrelevant. if not _is_external(self.task): missing = [dep.task_id for dep in self.task.deps() if not dep.complete()] if missing: deps = 'dependency' if len(missing) == 1 else 'dependencies' raise RuntimeError('Unfulfilled %s at run time: %s' % (deps, ', '.join(missing))) self.task.trigger_event(Event.START, self.task) t0 = time.time() status = None if _is_external(self.task): # External task # TODO(erikbern): We should check for task completeness after non-external tasks too! # This will resolve #814 and make things a lot more consistent if self.task.complete(): status = DONE else: status = FAILED expl = 'Task is an external data dependency ' \ 'and data does not exist (yet?).' else: new_deps = self._run_get_new_deps() status = DONE if not new_deps else PENDING if new_deps: logger.info( '[pid %s] Worker %s new requirements %s', os.getpid(), self.worker_id, self.task) elif status == DONE: self.task.trigger_event( Event.PROCESSING_TIME, self.task, time.time() - t0) expl = self.task.on_success() logger.info('[pid %s] Worker %s done %s', os.getpid(), self.worker_id, self.task) self.task.trigger_event(Event.SUCCESS, self.task) except KeyboardInterrupt: raise except BaseException as ex: status = FAILED logger.exception("[pid %s] Worker %s failed %s", os.getpid(), self.worker_id, self.task) self.task.trigger_event(Event.FAILURE, self.task, ex) raw_error_message = self.task.on_failure(ex) expl = raw_error_message finally: self.result_queue.put( (self.task.task_id, status, expl, missing, new_deps)) def _recursive_terminate(self): import psutil try: parent = psutil.Process(self.pid) children = parent.children(recursive=True) # terminate parent. Give it a chance to clean up super(TaskProcess, self).terminate() parent.wait() # terminate children for child in children: try: child.terminate() except psutil.NoSuchProcess: continue except psutil.NoSuchProcess: return def terminate(self): """Terminate this process and its subprocesses.""" # default terminate() doesn't cleanup child processes, it orphans them. try: return self._recursive_terminate() except ImportError: return super(TaskProcess, self).terminate() class SingleProcessPool(object): """ Dummy process pool for using a single processor. Imitates the api of multiprocessing.Pool using single-processor equivalents. """ def apply_async(self, function, args): return function(*args) def close(self): pass def join(self): pass class DequeQueue(collections.deque): """ deque wrapper implementing the Queue interface. """ def put(self, obj, block=None, timeout=None): return self.append(obj) def get(self, block=None, timeout=None): try: return self.pop() except IndexError: raise Queue.Empty class AsyncCompletionException(Exception): """ Exception indicating that something went wrong with checking complete. """ def __init__(self, trace): self.trace = trace class TracebackWrapper(object): """ Class to wrap tracebacks so we can know they're not just strings. """ def __init__(self, trace): self.trace = trace def check_complete(task, out_queue): """ Checks if task is complete, puts the result to out_queue. """ logger.debug("Checking if %s is complete", task) try: is_complete = task.complete() except Exception: is_complete = TracebackWrapper(traceback.format_exc()) out_queue.put((task, is_complete)) class worker(Config): # NOTE: `section.config-variable` in the config_path argument is deprecated in favor of `worker.config_variable` ping_interval = FloatParameter(default=1.0, config_path=dict(section='core', name='worker-ping-interval')) keep_alive = BoolParameter(default=False, config_path=dict(section='core', name='worker-keep-alive')) count_uniques = BoolParameter(default=False, config_path=dict(section='core', name='worker-count-uniques'), description='worker-count-uniques means that we will keep a ' 'worker alive only if it has a unique pending task, as ' 'well as having keep-alive true') wait_interval = FloatParameter(default=1.0, config_path=dict(section='core', name='worker-wait-interval')) wait_jitter = FloatParameter(default=5.0) max_reschedules = IntParameter(default=1, config_path=dict(section='core', name='worker-max-reschedules')) timeout = IntParameter(default=0, config_path=dict(section='core', name='worker-timeout')) task_limit = IntParameter(default=None, config_path=dict(section='core', name='worker-task-limit')) retry_external_tasks = BoolParameter(default=False, config_path=dict(section='core', name='retry-external-tasks'), description='If true, incomplete external tasks will be ' 'retested for completion while Luigi is running.') no_install_shutdown_handler = BoolParameter(default=False, description='If true, the SIGUSR1 shutdown handler will' 'NOT be install on the worker') class KeepAliveThread(threading.Thread): """ Periodically tell the scheduler that the worker still lives. """ def __init__(self, scheduler, worker_id, ping_interval): super(KeepAliveThread, self).__init__() self._should_stop = threading.Event() self._scheduler = scheduler self._worker_id = worker_id self._ping_interval = ping_interval def stop(self): self._should_stop.set() def run(self): while True: self._should_stop.wait(self._ping_interval) if self._should_stop.is_set(): logger.info("Worker %s was stopped. Shutting down Keep-Alive thread" % self._worker_id) break with fork_lock: try: self._scheduler.ping(worker=self._worker_id) except: # httplib.BadStatusLine: logger.warning('Failed pinging scheduler') class Worker(object): """ Worker object communicates with a scheduler. Simple class that talks to a scheduler and: * tells the scheduler what it has to do + its dependencies * asks for stuff to do (pulls it in a loop and runs it) """ def __init__(self, scheduler=None, worker_id=None, worker_processes=1, assistant=False, **kwargs): if scheduler is None: scheduler = Scheduler() self.worker_processes = int(worker_processes) self._worker_info = self._generate_worker_info() if not worker_id: worker_id = 'Worker(%s)' % ', '.join(['%s=%s' % (k, v) for k, v in self._worker_info]) self._config = worker(**kwargs) assert self._config.wait_interval >= _WAIT_INTERVAL_EPS, "[worker] wait_interval must be positive" assert self._config.wait_jitter >= 0.0, "[worker] wait_jitter must be equal or greater than zero" self._id = worker_id self._scheduler = scheduler self._assistant = assistant self._stop_requesting_work = False self.host = socket.gethostname() self._scheduled_tasks = {} self._suspended_tasks = {} self._first_task = None self.add_succeeded = True self.run_succeeded = True self.unfulfilled_counts = collections.defaultdict(int) # note that ``signal.signal(signal.SIGUSR1, fn)`` only works inside the main execution thread, which is why we # provide the ability to conditionally install the hook. if not self._config.no_install_shutdown_handler: try: signal.signal(signal.SIGUSR1, self.handle_interrupt) except AttributeError: pass # Keep info about what tasks are running (could be in other processes) if worker_processes == 1: self._task_result_queue = DequeQueue() else: self._task_result_queue = multiprocessing.Queue() self._running_tasks = {} # Stuff for execution_summary self._add_task_history = [] self._get_work_response_history = [] def _add_task(self, *args, **kwargs): """ Call ``self._scheduler.add_task``, but store the values too so we can implement :py:func:`luigi.execution_summary.summary`. """ task_id = kwargs['task_id'] status = kwargs['status'] runnable = kwargs['runnable'] task = self._scheduled_tasks.get(task_id) if task: msg = (task, status, runnable) self._add_task_history.append(msg) self._scheduler.add_task(*args, **kwargs) logger.info('Informed scheduler that task %s has status %s', task_id, status) def __enter__(self): """ Start the KeepAliveThread. """ self._keep_alive_thread = KeepAliveThread(self._scheduler, self._id, self._config.ping_interval) self._keep_alive_thread.daemon = True self._keep_alive_thread.start() return self def __exit__(self, type, value, traceback): """ Stop the KeepAliveThread and kill still running tasks. """ self._keep_alive_thread.stop() self._keep_alive_thread.join() for task in self._running_tasks.values(): if task.is_alive(): task.terminate() return False # Don't suppress exception def _generate_worker_info(self): # Generate as much info as possible about the worker # Some of these calls might not be available on all OS's args = [('salt', '%09d' % random.randrange(0, 999999999)), ('workers', self.worker_processes)] try: args += [('host', socket.gethostname())] except BaseException: pass try: args += [('username', getpass.getuser())] except BaseException: pass try: args += [('pid', os.getpid())] except BaseException: pass try: sudo_user = os.getenv("SUDO_USER") if sudo_user: args.append(('sudo_user', sudo_user)) except BaseException: pass return args def _validate_task(self, task): if not isinstance(task, Task): raise TaskException('Can not schedule non-task %s' % task) if not task.initialized(): # we can't get the repr of it since it's not initialized... raise TaskException('Task of class %s not initialized. Did you override __init__ and forget to call super(...).__init__?' % task.__class__.__name__) def _log_complete_error(self, task, tb): log_msg = "Will not run {task} or any dependencies due to error in complete() method:\n{tb}".format(task=task, tb=tb) logger.warning(log_msg) def _log_dependency_error(self, task, tb): log_msg = "Will not run {task} or any dependencies due to error in deps() method:\n{tb}".format(task=task, tb=tb) logger.warning(log_msg) def _log_unexpected_error(self, task): logger.exception("Luigi unexpected framework error while scheduling %s", task) # needs to be called from within except clause def _email_complete_error(self, task, formatted_traceback): self._email_error(task, formatted_traceback, subject="Luigi: {task} failed scheduling. Host: {host}", headline="Will not run {task} or any dependencies due to error in complete() method", ) def _email_dependency_error(self, task, formatted_traceback): self._email_error(task, formatted_traceback, subject="Luigi: {task} failed scheduling. Host: {host}", headline="Will not run {task} or any dependencies due to error in deps() method", ) def _email_unexpected_error(self, task, formatted_traceback): self._email_error(task, formatted_traceback, subject="Luigi: Framework error while scheduling {task}. Host: {host}", headline="Luigi framework error", ) def _email_task_failure(self, task, formatted_traceback): self._email_error(task, formatted_traceback, subject="Luigi: {task} FAILED. Host: {host}", headline="A task failed when running. Most likely run() raised an exception.", ) def _email_error(self, task, formatted_traceback, subject, headline): formatted_subject = subject.format(task=task, host=self.host) command = subprocess.list2cmdline(sys.argv) message = notifications.format_task_error(headline, task, command, formatted_traceback) notifications.send_error_email(formatted_subject, message, task.owner_email) def add(self, task, multiprocess=False): """ Add a Task for the worker to check and possibly schedule and run. Returns True if task and its dependencies were successfully scheduled or completed before. """ if self._first_task is None and hasattr(task, 'task_id'): self._first_task = task.task_id self.add_succeeded = True if multiprocess: queue = multiprocessing.Manager().Queue() pool = multiprocessing.Pool() else: queue = DequeQueue() pool = SingleProcessPool() self._validate_task(task) pool.apply_async(check_complete, [task, queue]) # we track queue size ourselves because len(queue) won't work for multiprocessing queue_size = 1 try: seen = set([task.task_id]) while queue_size: current = queue.get() queue_size -= 1 item, is_complete = current for next in self._add(item, is_complete): if next.task_id not in seen: self._validate_task(next) seen.add(next.task_id) pool.apply_async(check_complete, [next, queue]) queue_size += 1 except (KeyboardInterrupt, TaskException): raise except Exception as ex: self.add_succeeded = False formatted_traceback = traceback.format_exc() self._log_unexpected_error(task) task.trigger_event(Event.BROKEN_TASK, task, ex) self._email_unexpected_error(task, formatted_traceback) raise finally: pool.close() pool.join() return self.add_succeeded def _add(self, task, is_complete): deps_retry_policy_dicts = None if self._config.task_limit is not None and len(self._scheduled_tasks) >= self._config.task_limit: logger.warning('Will not run %s or any dependencies due to exceeded task-limit of %d', task, self._config.task_limit) deps = None status = UNKNOWN runnable = False else: formatted_traceback = None try: self._check_complete_value(is_complete) except KeyboardInterrupt: raise except AsyncCompletionException as ex: formatted_traceback = ex.trace except BaseException: formatted_traceback = traceback.format_exc() if formatted_traceback is not None: self.add_succeeded = False self._log_complete_error(task, formatted_traceback) task.trigger_event(Event.DEPENDENCY_MISSING, task) self._email_complete_error(task, formatted_traceback) deps = None status = UNKNOWN runnable = False elif is_complete: deps = None status = DONE runnable = False task.trigger_event(Event.DEPENDENCY_PRESENT, task) elif _is_external(task): deps = None status = PENDING runnable = worker().retry_external_tasks task.trigger_event(Event.DEPENDENCY_MISSING, task) logger.warning('Data for %s does not exist (yet?). The task is an ' 'external data depedency, so it can not be run from' ' this luigi process.', task) else: try: deps = task.deps() except Exception as ex: formatted_traceback = traceback.format_exc() self.add_succeeded = False self._log_dependency_error(task, formatted_traceback) task.trigger_event(Event.BROKEN_TASK, task, ex) self._email_dependency_error(task, formatted_traceback) deps = None status = UNKNOWN runnable = False else: status = PENDING runnable = True if task.disabled: status = DISABLED if deps: for d in deps: self._validate_dependency(d) task.trigger_event(Event.DEPENDENCY_DISCOVERED, task, d) yield d # return additional tasks to add deps_retry_policy_dicts = {d.task_id: _get_retry_policy_dict(d) for d in deps} deps = [d.task_id for d in deps] self._scheduled_tasks[task.task_id] = task self._add_task(worker=self._id, task_id=task.task_id, status=status, deps=deps, runnable=runnable, priority=task.priority, resources=task.process_resources(), params=task.to_str_params(), family=task.task_family, module=task.task_module, retry_policy_dict=_get_retry_policy_dict(task), deps_retry_policy_dicts=deps_retry_policy_dicts) def _validate_dependency(self, dependency): if isinstance(dependency, Target): raise Exception('requires() can not return Target objects. Wrap it in an ExternalTask class') elif not isinstance(dependency, Task): raise Exception('requires() must return Task objects') def _check_complete_value(self, is_complete): if is_complete not in (True, False): if isinstance(is_complete, TracebackWrapper): raise AsyncCompletionException(is_complete.trace) raise Exception("Return value of Task.complete() must be boolean (was %r)" % is_complete) def _add_worker(self): self._worker_info.append(('first_task', self._first_task)) self._scheduler.add_worker(self._id, self._worker_info) def _log_remote_tasks(self, running_tasks, n_pending_tasks, n_unique_pending): logger.debug("Done") logger.debug("There are no more tasks to run at this time") if running_tasks: for r in running_tasks: logger.debug('%s is currently run by worker %s', r['task_id'], r['worker']) elif n_pending_tasks: logger.debug("There are %s pending tasks possibly being run by other workers", n_pending_tasks) if n_unique_pending: logger.debug("There are %i pending tasks unique to this worker", n_unique_pending) def _get_work(self): if self._stop_requesting_work: return None, 0, 0, 0 logger.debug("Asking scheduler for work...") r = self._scheduler.get_work( worker=self._id, host=self.host, assistant=self._assistant, current_tasks=list(self._running_tasks.keys()), ) n_pending_tasks = r['n_pending_tasks'] task_id = r['task_id'] running_tasks = r['running_tasks'] n_unique_pending = r['n_unique_pending'] self._get_work_response_history.append(dict( task_id=task_id, running_tasks=running_tasks, )) if task_id is not None and task_id not in self._scheduled_tasks: logger.info('Did not schedule %s, will load it dynamically', task_id) try: # TODO: we should obtain the module name from the server! self._scheduled_tasks[task_id] = \ load_task(module=r.get('task_module'), task_name=r['task_family'], params_str=r['task_params']) except TaskClassException as ex: msg = 'Cannot find task for %s' % task_id logger.exception(msg) subject = 'Luigi: %s' % msg error_message = notifications.wrap_traceback(ex) notifications.send_error_email(subject, error_message) self._add_task(worker=self._id, task_id=task_id, status=FAILED, runnable=False, assistant=self._assistant) task_id = None self.run_succeeded = False return task_id, running_tasks, n_pending_tasks, n_unique_pending def _run_task(self, task_id): task = self._scheduled_tasks[task_id] p = self._create_task_process(task) self._running_tasks[task_id] = p if self.worker_processes > 1: with fork_lock: p.start() else: # Run in the same process p.run() def _create_task_process(self, task): def update_tracking_url(tracking_url): self._scheduler.add_task( task_id=task.task_id, worker=self._id, status=RUNNING, tracking_url=tracking_url, ) def update_status_message(message): self._scheduler.set_task_status_message(task.task_id, message) return TaskProcess( task, self._id, self._task_result_queue, update_tracking_url, update_status_message, random_seed=bool(self.worker_processes > 1), worker_timeout=self._config.timeout ) def _purge_children(self): """ Find dead children and put a response on the result queue. :return: """ for task_id, p in six.iteritems(self._running_tasks): if not p.is_alive() and p.exitcode: error_msg = 'Task {} died unexpectedly with exit code {}'.format(task_id, p.exitcode) p.task.trigger_event(Event.PROCESS_FAILURE, p.task, error_msg) elif p.timeout_time is not None and time.time() > float(p.timeout_time) and p.is_alive(): p.terminate() error_msg = 'Task {} timed out after {} seconds and was terminated.'.format(task_id, p.task.worker_timeout) p.task.trigger_event(Event.TIMEOUT, p.task, error_msg) else: continue logger.info(error_msg) self._task_result_queue.put((task_id, FAILED, error_msg, [], [])) def _handle_next_task(self): """ We have to catch three ways a task can be "done": 1. normal execution: the task runs/fails and puts a result back on the queue, 2. new dependencies: the task yielded new deps that were not complete and will be rescheduled and dependencies added, 3. child process dies: we need to catch this separately. """ while True: self._purge_children() # Deal with subprocess failures try: task_id, status, expl, missing, new_requirements = ( self._task_result_queue.get( timeout=self._config.wait_interval)) except Queue.Empty: return task = self._scheduled_tasks[task_id] if not task or task_id not in self._running_tasks: continue # Not a running task. Probably already removed. # Maybe it yielded something? # external task if run not implemented, retry-able if config option is enabled. external_task_retryable = _is_external(task) and self._config.retry_external_tasks if status == FAILED and not external_task_retryable: self._email_task_failure(task, expl) new_deps = [] if new_requirements: new_req = [load_task(module, name, params) for module, name, params in new_requirements] for t in new_req: self.add(t) new_deps = [t.task_id for t in new_req] self._add_task(worker=self._id, task_id=task_id, status=status, expl=json.dumps(expl), resources=task.process_resources(), runnable=None, params=task.to_str_params(), family=task.task_family, module=task.task_module, new_deps=new_deps, assistant=self._assistant, ) self._running_tasks.pop(task_id) # re-add task to reschedule missing dependencies if missing: reschedule = True # keep out of infinite loops by not rescheduling too many times for task_id in missing: self.unfulfilled_counts[task_id] += 1 if (self.unfulfilled_counts[task_id] > self._config.max_reschedules): reschedule = False if reschedule: self.add(task) self.run_succeeded &= (status == DONE) or (len(new_deps) > 0) return def _sleeper(self): # TODO is exponential backoff necessary? while True: jitter = self._config.wait_jitter wait_interval = self._config.wait_interval + random.uniform(0, jitter) logger.debug('Sleeping for %f seconds', wait_interval) time.sleep(wait_interval) yield def _keep_alive(self, n_pending_tasks, n_unique_pending): """ Returns true if a worker should stay alive given. If worker-keep-alive is not set, this will always return false. For an assistant, it will always return the value of worker-keep-alive. Otherwise, it will return true for nonzero n_pending_tasks. If worker-count-uniques is true, it will also require that one of the tasks is unique to this worker. """ if not self._config.keep_alive: return False elif self._assistant: return True else: return n_pending_tasks and (n_unique_pending or not self._config.count_uniques) def handle_interrupt(self, signum, _): """ Stops the assistant from asking for more work on SIGUSR1 """ if signum == signal.SIGUSR1: self._config.keep_alive = False self._stop_requesting_work = True def run(self): """ Returns True if all scheduled tasks were executed successfully. """ logger.info('Running Worker with %d processes', self.worker_processes) sleeper = self._sleeper() self.run_succeeded = True self._add_worker() while True: while len(self._running_tasks) >= self.worker_processes: logger.debug('%d running tasks, waiting for next task to finish', len(self._running_tasks)) self._handle_next_task() task_id, running_tasks, n_pending_tasks, n_unique_pending = self._get_work() if task_id is None: if not self._stop_requesting_work: self._log_remote_tasks(running_tasks, n_pending_tasks, n_unique_pending) if len(self._running_tasks) == 0: if self._keep_alive(n_pending_tasks, n_unique_pending): six.next(sleeper) continue else: break else: self._handle_next_task() continue # task_id is not None: logger.debug("Pending tasks: %s", n_pending_tasks) self._run_task(task_id) while len(self._running_tasks): logger.debug('Shut down Worker, %d more tasks to go', len(self._running_tasks)) self._handle_next_task() return self.run_succeeded
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 Nicira Networks, 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. # # @author: Salvatore Orlando, VMware # import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy.orm import exc as sa_orm_exc from webob import exc as web_exc from neutron.api.v2 import attributes from neutron.api.v2 import base from neutron.common import exceptions from neutron.db import model_base from neutron.db import models_v2 from neutron.openstack.common import log as logging from neutron.openstack.common import uuidutils from neutron.plugins.nicira.extensions import nvp_networkgw LOG = logging.getLogger(__name__) DEVICE_OWNER_NET_GW_INTF = 'network:gateway-interface' NETWORK_ID = 'network_id' SEGMENTATION_TYPE = 'segmentation_type' SEGMENTATION_ID = 'segmentation_id' ALLOWED_CONNECTION_ATTRIBUTES = set((NETWORK_ID, SEGMENTATION_TYPE, SEGMENTATION_ID)) class GatewayInUse(exceptions.InUse): message = _("Network Gateway '%(gateway_id)s' still has active mappings " "with one or more neutron networks.") class NetworkGatewayPortInUse(exceptions.InUse): message = _("Port '%(port_id)s' is owned by '%(device_owner)s' and " "therefore cannot be deleted directly via the port API.") class GatewayConnectionInUse(exceptions.InUse): message = _("The specified mapping '%(mapping)s' is already in use on " "network gateway '%(gateway_id)s'.") class MultipleGatewayConnections(exceptions.NeutronException): message = _("Multiple network connections found on '%(gateway_id)s' " "with provided criteria.") class GatewayConnectionNotFound(exceptions.NotFound): message = _("The connection %(network_mapping_info)s was not found on the " "network gateway '%(network_gateway_id)s'") class NetworkGatewayUnchangeable(exceptions.InUse): message = _("The network gateway %(gateway_id)s " "cannot be updated or deleted") # Add exceptions to HTTP Faults mappings base.FAULT_MAP.update({GatewayInUse: web_exc.HTTPConflict, NetworkGatewayPortInUse: web_exc.HTTPConflict, GatewayConnectionInUse: web_exc.HTTPConflict, GatewayConnectionNotFound: web_exc.HTTPNotFound, MultipleGatewayConnections: web_exc.HTTPConflict}) class NetworkConnection(model_base.BASEV2, models_v2.HasTenant): """Defines a connection between a network gateway and a network.""" # We use port_id as the primary key as one can connect a gateway # to a network in multiple ways (and we cannot use the same port form # more than a single gateway) network_gateway_id = sa.Column(sa.String(36), sa.ForeignKey('networkgateways.id', ondelete='CASCADE')) network_id = sa.Column(sa.String(36), sa.ForeignKey('networks.id', ondelete='CASCADE')) segmentation_type = sa.Column( sa.Enum('flat', 'vlan', name='networkconnections_segmentation_type')) segmentation_id = sa.Column(sa.Integer) __table_args__ = (sa.UniqueConstraint(network_gateway_id, segmentation_type, segmentation_id),) # Also, storing port id comes back useful when disconnecting a network # from a gateway port_id = sa.Column(sa.String(36), sa.ForeignKey('ports.id', ondelete='CASCADE'), primary_key=True) class NetworkGatewayDevice(model_base.BASEV2): id = sa.Column(sa.String(36), primary_key=True) network_gateway_id = sa.Column(sa.String(36), sa.ForeignKey('networkgateways.id', ondelete='CASCADE')) interface_name = sa.Column(sa.String(64)) class NetworkGateway(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant): """Defines the data model for a network gateway.""" name = sa.Column(sa.String(255)) # Tenant id is nullable for this resource tenant_id = sa.Column(sa.String(36)) default = sa.Column(sa.Boolean()) devices = orm.relationship(NetworkGatewayDevice, backref='networkgateways', cascade='all,delete') network_connections = orm.relationship(NetworkConnection, lazy='joined') class NetworkGatewayMixin(nvp_networkgw.NetworkGatewayPluginBase): resource = nvp_networkgw.RESOURCE_NAME.replace('-', '_') def _get_network_gateway(self, context, gw_id): return self._get_by_id(context, NetworkGateway, gw_id) def _make_gw_connection_dict(self, gw_conn): return {'port_id': gw_conn['port_id'], 'segmentation_type': gw_conn['segmentation_type'], 'segmentation_id': gw_conn['segmentation_id']} def _make_network_gateway_dict(self, network_gateway, fields=None): device_list = [] for d in network_gateway['devices']: device_list.append({'id': d['id'], 'interface_name': d['interface_name']}) res = {'id': network_gateway['id'], 'name': network_gateway['name'], 'default': network_gateway['default'], 'devices': device_list, 'tenant_id': network_gateway['tenant_id']} # Query gateway connections only if needed if (fields and 'ports' in fields) or not fields: res['ports'] = [self._make_gw_connection_dict(conn) for conn in network_gateway.network_connections] return self._fields(res, fields) def _set_mapping_info_defaults(self, mapping_info): if not mapping_info.get('segmentation_type'): mapping_info['segmentation_type'] = 'flat' if not mapping_info.get('segmentation_id'): mapping_info['segmentation_id'] = 0 def _validate_network_mapping_info(self, network_mapping_info): self._set_mapping_info_defaults(network_mapping_info) network_id = network_mapping_info.get(NETWORK_ID) if not network_id: raise exceptions.InvalidInput( error_message=_("A network identifier must be specified " "when connecting a network to a network " "gateway. Unable to complete operation")) connection_attrs = set(network_mapping_info.keys()) if not connection_attrs.issubset(ALLOWED_CONNECTION_ATTRIBUTES): raise exceptions.InvalidInput( error_message=(_("Invalid keys found among the ones provided " "in request body: %(connection_attrs)s."), connection_attrs)) seg_type = network_mapping_info.get(SEGMENTATION_TYPE) seg_id = network_mapping_info.get(SEGMENTATION_ID) if not seg_type and seg_id: msg = _("In order to specify a segmentation id the " "segmentation type must be specified as well") raise exceptions.InvalidInput(error_message=msg) elif seg_type and seg_type.lower() == 'flat' and seg_id: msg = _("Cannot specify a segmentation id when " "the segmentation type is flat") raise exceptions.InvalidInput(error_message=msg) return network_id def _retrieve_gateway_connections(self, context, gateway_id, mapping_info={}, only_one=False): filters = {'network_gateway_id': [gateway_id]} for k, v in mapping_info.iteritems(): if v and k != NETWORK_ID: filters[k] = [v] query = self._get_collection_query(context, NetworkConnection, filters) return only_one and query.one() or query.all() def _unset_default_network_gateways(self, context): with context.session.begin(subtransactions=True): context.session.query(NetworkGateway).update( {NetworkGateway.default: False}) def _set_default_network_gateway(self, context, gw_id): with context.session.begin(subtransactions=True): gw = (context.session.query(NetworkGateway). filter_by(id=gw_id).one()) gw['default'] = True def prevent_network_gateway_port_deletion(self, context, port): """Pre-deletion check. Ensures a port will not be deleted if is being used by a network gateway. In that case an exception will be raised. """ if port['device_owner'] == DEVICE_OWNER_NET_GW_INTF: raise NetworkGatewayPortInUse(port_id=port['id'], device_owner=port['device_owner']) def create_network_gateway(self, context, network_gateway): gw_data = network_gateway[self.resource] tenant_id = self._get_tenant_id_for_create(context, gw_data) with context.session.begin(subtransactions=True): gw_db = NetworkGateway( id=gw_data.get('id', uuidutils.generate_uuid()), tenant_id=tenant_id, name=gw_data.get('name')) # Device list is guaranteed to be a valid list gw_db.devices.extend([NetworkGatewayDevice(**device) for device in gw_data['devices']]) context.session.add(gw_db) LOG.debug(_("Created network gateway with id:%s"), gw_db['id']) return self._make_network_gateway_dict(gw_db) def update_network_gateway(self, context, id, network_gateway): gw_data = network_gateway[self.resource] with context.session.begin(subtransactions=True): gw_db = self._get_network_gateway(context, id) if gw_db.default: raise NetworkGatewayUnchangeable(gateway_id=id) # Ensure there is something to update before doing it if any([gw_db[k] != gw_data[k] for k in gw_data]): gw_db.update(gw_data) LOG.debug(_("Updated network gateway with id:%s"), id) return self._make_network_gateway_dict(gw_db) def get_network_gateway(self, context, id, fields=None): gw_db = self._get_network_gateway(context, id) return self._make_network_gateway_dict(gw_db, fields) def delete_network_gateway(self, context, id): with context.session.begin(subtransactions=True): gw_db = self._get_network_gateway(context, id) if gw_db.network_connections: raise GatewayInUse(gateway_id=id) if gw_db.default: raise NetworkGatewayUnchangeable(gateway_id=id) context.session.delete(gw_db) LOG.debug(_("Network gateway '%s' was destroyed."), id) def get_network_gateways(self, context, filters=None, fields=None): return self._get_collection(context, NetworkGateway, self._make_network_gateway_dict, filters=filters, fields=fields) def connect_network(self, context, network_gateway_id, network_mapping_info): network_id = self._validate_network_mapping_info(network_mapping_info) LOG.debug(_("Connecting network '%(network_id)s' to gateway " "'%(network_gateway_id)s'"), {'network_id': network_id, 'network_gateway_id': network_gateway_id}) with context.session.begin(subtransactions=True): gw_db = self._get_network_gateway(context, network_gateway_id) tenant_id = self._get_tenant_id_for_create(context, gw_db) # TODO(salvatore-orlando): Leverage unique constraint instead # of performing another query! if self._retrieve_gateway_connections(context, network_gateway_id, network_mapping_info): raise GatewayConnectionInUse(mapping=network_mapping_info, gateway_id=network_gateway_id) # TODO(salvatore-orlando): Creating a port will give it an IP, # but we actually do not need any. Instead of wasting an IP we # should have a way to say a port shall not be associated with # any subnet try: # We pass the segmentation type and id too - the plugin # might find them useful as the network connection object # does not exist yet. # NOTE: they're not extended attributes, rather extra data # passed in the port structure to the plugin # TODO(salvatore-orlando): Verify optimal solution for # ownership of the gateway port port = self.create_port(context, { 'port': {'tenant_id': tenant_id, 'network_id': network_id, 'mac_address': attributes.ATTR_NOT_SPECIFIED, 'admin_state_up': True, 'fixed_ips': [], 'device_id': network_gateway_id, 'device_owner': DEVICE_OWNER_NET_GW_INTF, 'name': '', 'gw:segmentation_type': network_mapping_info.get('segmentation_type'), 'gw:segmentation_id': network_mapping_info.get('segmentation_id')}}) except exceptions.NetworkNotFound: err_msg = (_("Requested network '%(network_id)s' not found." "Unable to create network connection on " "gateway '%(network_gateway_id)s") % {'network_id': network_id, 'network_gateway_id': network_gateway_id}) LOG.error(err_msg) raise exceptions.InvalidInput(error_message=err_msg) port_id = port['id'] LOG.debug(_("Gateway port for '%(network_gateway_id)s' " "created on network '%(network_id)s':%(port_id)s"), {'network_gateway_id': network_gateway_id, 'network_id': network_id, 'port_id': port_id}) # Create NetworkConnection record network_mapping_info['port_id'] = port_id network_mapping_info['tenant_id'] = tenant_id gw_db.network_connections.append( NetworkConnection(**network_mapping_info)) port_id = port['id'] # now deallocate and recycle ip from the port for fixed_ip in port.get('fixed_ips', []): self._recycle_ip(context, network_id, fixed_ip['subnet_id'], fixed_ip['ip_address']) LOG.debug(_("Ensured no Ip addresses are configured on port %s"), port_id) return {'connection_info': {'network_gateway_id': network_gateway_id, 'network_id': network_id, 'port_id': port_id}} def disconnect_network(self, context, network_gateway_id, network_mapping_info): network_id = self._validate_network_mapping_info(network_mapping_info) LOG.debug(_("Disconnecting network '%(network_id)s' from gateway " "'%(network_gateway_id)s'"), {'network_id': network_id, 'network_gateway_id': network_gateway_id}) with context.session.begin(subtransactions=True): # Uniquely identify connection, otherwise raise try: net_connection = self._retrieve_gateway_connections( context, network_gateway_id, network_mapping_info, only_one=True) except sa_orm_exc.NoResultFound: raise GatewayConnectionNotFound( network_mapping_info=network_mapping_info, network_gateway_id=network_gateway_id) except sa_orm_exc.MultipleResultsFound: raise MultipleGatewayConnections( gateway_id=network_gateway_id) # Remove gateway port from network # FIXME(salvatore-orlando): Ensure state of port in NVP is # consistent with outcome of transaction self.delete_port(context, net_connection['port_id'], nw_gw_port_check=False) # Remove NetworkConnection record context.session.delete(net_connection)
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json from extensions_paths import CHROME_EXTENSIONS from test_file_system import MoveAllTo from test_util import ReadFile FAKE_TABS_IDL = '\n'.join([ '// Copyleft stuff.', '', '// Some description here.', 'namespace fakeTabs {', ' dictionary WasImplicitlyInlinedType {};', ' interface Functions {', ' static void myFunc(WasImplicitlyInlinedType arg);', ' static void anotherFunc(WasImplicitlyInlinedType arg);', ' };', '};']) FAKE_TABS_WITH_INLINING_IDL = '\n'.join([ '// Copyleft stuff.', '', '// Some description here.', 'namespace fakeTabs {', ' dictionary WasImplicitlyInlinedType {};', ' interface Functions {', ' static void myFunc(WasImplicitlyInlinedType arg);', ' };', '};']) TABS_SCHEMA_BRANCHES = MoveAllTo(CHROME_EXTENSIONS, { 'master': { 'docs': { 'templates': { 'json': { 'api_availabilities.json': json.dumps({ 'tabs.fakeTabsProperty4': { 'channel': 'stable', 'version': 27 } }), 'intro_tables.json': '{}' } } }, 'api': { '_api_features.json': json.dumps({ 'tabs.scheduledFunc': { 'channel': 'stable' } }), '_manifest_features.json': '{}', '_permission_features.json': '{}', 'fake_tabs.idl': FAKE_TABS_IDL, 'tabs.json': json.dumps([{ 'namespace': 'tabs', 'types': [ { 'id': 'Tab', 'type': 'any', 'properties': { 'url': { 'type': 'any' }, 'index': { 'type': 'any' }, 'selected': { 'type': 'any' }, 'id': { 'type': 'any' }, 'windowId': { 'type': 'any' } } }, { 'id': 'InlinedType', 'type': 'any', 'inline_doc': True }, { 'id': 'InjectDetails', 'type': 'any', 'properties': { 'allFrames': { 'type': 'any' }, 'code': { 'type': 'any' }, 'file': { 'type':'any' } } }, { 'id': 'DeprecatedType', 'type': 'any', 'deprecated': 'This is deprecated' } ], 'properties': { 'fakeTabsProperty1': { 'type': 'any' }, 'fakeTabsProperty2': { 'type': 'any' }, 'fakeTabsProperty3': { 'type': 'any' }, 'fakeTabsProperty4': { 'type': 'any' } }, 'functions': [ { 'name': 'getCurrent', 'parameters': [ { 'name': 'callback', 'type': 'function', 'parameters': [ { 'name': 'tab', 'type': 'any' } ] } ] }, { 'name': 'get', 'parameters': [ { 'name': 'callback', 'type': 'function', 'parameters': [ { 'name': 'tab', 'type': 'any' } ] }, { 'name': 'tabId', 'type': 'any' } ] }, { 'name': 'restrictedFunc' }, { 'name': 'scheduledFunc', 'parameters': [] } ], 'events': [ { 'name': 'onActivated', 'type': 'event', 'parameters': [ { 'name': 'activeInfo', 'type': 'any', 'properties': { 'tabId': { 'type': 'any' }, 'windowId': { 'type': 'any' } } } ] }, { 'name': 'onUpdated', 'type': 'event', 'parameters': [ { 'name': 'tabId', 'type': 'any' }, { 'name': 'tab', 'type': 'any' }, { 'name': 'changeInfo', 'type': 'any', 'properties': { 'pinned': { 'type': 'any' }, 'status': { 'type': 'any' } } } ] } ] }]) } }, '1612': { 'api': { '_api_features.json': json.dumps({ 'tabs.scheduledFunc': { 'channel': 'stable' } }), '_manifest_features.json': "{}", '_permission_features.json': "{}", 'fake_tabs.idl': FAKE_TABS_IDL, 'tabs.json': json.dumps([{ 'namespace': 'tabs', 'types': [ { 'id': 'Tab', 'properties': { 'url': {}, 'index': {}, 'selected': {}, 'id': {}, 'windowId': {} } }, { 'id': 'InjectDetails', 'properties': { 'allFrames': {}, 'code': {}, 'file': {} } }, { 'id': 'DeprecatedType', 'deprecated': 'This is deprecated' } ], 'properties': { 'fakeTabsProperty1': {}, 'fakeTabsProperty2': {} }, 'functions': [ { 'name': 'getCurrent', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] }, { 'name': 'get', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] }, { 'name': 'tabId' } ] }, { 'name': 'restrictedFunc' }, { 'name': 'scheduledFunc', 'parameters': [] } ], 'events': [ { 'name': 'onActivated', 'parameters': [ { 'name': 'activeInfo', 'properties': { 'tabId': {}, 'windowId': {} } } ] }, { 'name': 'onUpdated', 'parameters': [ { 'name': 'tabId' }, { 'name': 'tab' }, { 'name': 'changeInfo', 'properties': { 'pinned': {}, 'status': {} } } ] } ] }]) } }, '1599': { 'api': { '_api_features.json': "{}", '_manifest_features.json': "{}", '_permission_features.json': "{}", 'fake_tabs.idl': FAKE_TABS_IDL, 'tabs.json': json.dumps([{ 'namespace': 'tabs', 'types': [ { 'id': 'Tab', 'properties': { 'url': {}, 'index': {}, 'selected': {}, 'id': {}, 'windowId': {} } }, { 'id': 'InjectDetails', 'properties': { 'allFrames': {}, 'code': {}, 'file': {} } }, { 'id': 'DeprecatedType', 'deprecated': 'This is deprecated' } ], 'properties': { 'fakeTabsProperty1': {}, 'fakeTabsProperty2': {} }, 'functions': [ { 'name': 'getCurrent', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] }, { 'name': 'get', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] }, { 'name': 'tabId' } ] }, { 'name': 'restrictedFunc' } ], 'events': [ { 'name': 'onActivated', 'parameters': [ { 'name': 'activeInfo', 'properties': { 'tabId': {}, } } ] }, { 'name': 'onUpdated', 'parameters': [ { 'name': 'tabId' }, { 'name': 'changeInfo', 'properties': { 'pinned': {}, 'status': {} } } ] } ] }]) } }, '1547': { 'api': { '_api_features.json': json.dumps({ 'tabs.restrictedFunc': { 'channel': 'dev' } }), '_manifest_features.json': "{}", '_permission_features.json': "{}", 'fake_tabs.idl': FAKE_TABS_IDL, 'tabs.json': json.dumps([{ 'namespace': 'tabs', 'types': [ { 'id': 'Tab', 'properties': { 'url': {}, 'index': {}, 'selected': {}, 'id': {}, 'windowId': {} } }, { 'id': 'InjectDetails', 'properties': { 'allFrames': {}, 'code': {}, 'file': {} } }, { 'id': 'DeprecatedType', 'deprecated': 'This is deprecated' } ], 'properties': { 'fakeTabsProperty1': {}, 'fakeTabsProperty2': {} }, 'functions': [ { 'name': 'getCurrent', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] }, { 'name': 'get', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] }, ] }, { 'name': 'restrictedFunc' } ], 'events': [ { 'name': 'onUpdated', 'parameters': [ { 'name': 'tabId' }, { 'name': 'changeInfo', 'properties': { 'pinned': {}, 'status': {} } } ] } ] }]) } }, '1500': { 'api': { '_api_features.json': "{}", '_manifest_features.json': "{}", '_permission_features.json': "{}", 'fake_tabs.idl': FAKE_TABS_IDL, 'tabs.json': json.dumps([{ 'namespace': 'tabs', 'types': [ { 'id': 'Tab', 'properties': { 'url': {}, 'index': {}, 'selected': {}, 'id': {}, 'windowId': {} } }, { 'id': 'InjectDetails', 'properties': { 'allFrames': {}, } }, { 'id': 'DeprecatedType', 'deprecated': 'This is deprecated' } ], 'properties': { 'fakeTabsProperty1': {}, 'fakeTabsProperty2': {} }, 'functions': [ { 'name': 'getCurrent', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] }, { 'name': 'get', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] }, ] } ], 'events': [ { 'name': 'onUpdated', 'parameters': [ { 'name': 'tabId' }, { 'name': 'changeInfo', 'properties': { 'pinned': {}, 'status': {} } } ] } ] }]) } }, '1453': { 'api': { '_api_features.json': "{}", '_manifest_features.json': "{}", '_permission_features.json': "{}", 'fake_tabs.idl': FAKE_TABS_IDL, 'tabs.json': json.dumps([{ 'namespace': 'tabs', 'types': [ { 'id': 'Tab', 'properties': { 'url': {}, 'index': {}, 'selected': {}, 'id': {}, 'windowId': {} } }, { 'id': 'InjectDetails', 'properties': { 'allFrames': {}, } }, { 'id': 'DeprecatedType', 'deprecated': 'This is deprecated' } ], 'properties': { 'fakeTabsProperty1': {}, 'fakeTabsProperty2': {} }, 'functions': [ { 'name': 'getCurrent', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] }, { 'name': 'get', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] }, ] } ], 'events': [ { 'name': 'onUpdated', 'parameters': [ { 'name': 'tabId' }, { 'name': 'changeInfo', 'properties': { 'pinned': {}, 'status': {} } } ] } ] }]) } }, '1410': { 'api': { '_manifest_features.json': "{}", '_permission_features.json': "{}", 'fake_tabs.idl': FAKE_TABS_IDL, 'tabs.json': json.dumps([{ 'namespace': 'tabs', 'types': [ { 'id': 'Tab', 'properties': { 'url': {}, 'index': {}, 'selected': {}, 'id': {}, 'windowId': {} } }, { 'id': 'InjectDetails', 'properties': { 'allFrames': {}, } }, { 'id': 'DeprecatedType', 'deprecated': 'This is deprecated' } ], 'properties': { 'fakeTabsProperty1': {}, 'fakeTabsProperty2': {} }, 'functions': [ { 'name': 'getCurrent', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] }, { 'name': 'get', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] } ], 'events': [ { 'name': 'onUpdated', 'parameters': [ { 'name': 'tabId' }, { 'name': 'changeInfo', 'properties': { 'pinned': {}, 'status': {} } } ] } ] }]) } }, '1364': { 'api': { '_manifest_features.json': "{}", '_permission_features.json': "{}", 'fake_tabs.idl': FAKE_TABS_WITH_INLINING_IDL, 'tabs.json': json.dumps([{ 'namespace': 'tabs', 'types': [ { 'id': 'Tab', 'properties': { 'url': {}, 'index': {}, 'selected': {}, 'id': {}, 'windowId': {} } }, { 'id': 'InjectDetails', 'properties': { 'allFrames': {} } }, { 'id': 'DeprecatedType', } ], 'properties': { 'fakeTabsProperty1': {}, 'fakeTabsProperty2': {} }, 'functions': [ { 'name': 'getCurrent', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] }, { 'name': 'get', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] } ], 'events': [ { 'name': 'onUpdated', 'parameters': [ { 'name': 'tabId' }, { 'name': 'changeInfo', 'properties': { 'pinned': {}, 'status': {} } } ] } ] }]) } }, '1312': { 'api': { '_manifest_features.json': "{}", '_permission_features.json': "{}", 'tabs.json': json.dumps([{ 'namespace': 'tabs', 'types': [ { 'id': 'Tab', 'properties': { 'url': {}, 'index': {}, 'selected': {}, 'id': {}, 'windowId': {} } } ], 'properties': { 'fakeTabsProperty1': {}, 'fakeTabsProperty2': {} }, 'functions': [ { 'name': 'getCurrent', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] }, { 'name': 'get', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] } ], 'events': [ { 'name': 'onUpdated', 'parameters': [ { 'name': 'tabId' }, { 'name': 'changeInfo', 'properties': { 'pinned': {}, 'status': {} } } ] } ] }]) } }, '1271': { 'api': { '_manifest_features.json': "{}", '_permission_features.json': "{}", 'tabs.json': json.dumps([{ 'namespace': 'tabs', 'types': [ { 'id': 'Tab', 'properties': { 'url': {}, 'index': {}, 'selected': {}, 'id': {}, 'windowId': {} } } ], 'properties': { 'fakeTabsProperty1': {}, 'fakeTabsProperty2': {} }, 'functions': [ { 'name': 'getCurrent', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] }, { 'name': 'get', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] } ], 'events': [ { 'name': 'onUpdated', 'parameters': [ { 'name': 'tabId' }, { 'name': 'changeInfo', 'properties': { 'pinned': {}, 'status': {} } } ] } ] }]) } }, '1229': { 'api': { '_manifest_features.json': "{}", '_permission_features.json': "{}", 'tabs.json': json.dumps([{ 'namespace': 'tabs', 'types': [ { 'id': 'Tab', 'properties': { 'url': {}, 'index': {}, 'selected': {}, 'id': {}, 'windowId': {} } } ], 'properties': { 'fakeTabsProperty1': {}, 'fakeTabsProperty2': {} }, 'functions': [ { 'name': 'getCurrent', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] }, { 'name': 'get', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] } ], 'events': [ { 'name': 'onUpdated', 'parameters': [ { 'name': 'tabId' }, { 'name': 'changeInfo', 'properties': { 'pinned': {}, 'status': {} } } ] } ] }]) } }, '1180': { 'api': { '_manifest_features.json': "{}", '_permission_features.json': "{}", 'tabs.json': json.dumps([{ 'namespace': 'tabs', 'types': [ { 'id': 'Tab', 'properties': { 'url': {}, 'index': {}, 'selected': {}, 'id': {} } } ], 'properties': { 'fakeTabsProperty1': {}, 'fakeTabsProperty2': {} }, 'functions': [ { 'name': 'getCurrent', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] }, { 'name': 'get', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] } ], 'events': [ { 'name': 'onUpdated', 'parameters': [ { 'name': 'tabId' }, { 'name': 'changeInfo', 'properties': { 'pinned': {}, 'status': {} } } ] } ] }]) } }, '1132': { 'api': { '_manifest_features.json': "{}", '_permission_features.json': "{}", 'tabs.json': json.dumps([{ 'namespace': 'tabs', 'types': [ { 'id': 'Tab', 'properties': { 'url': {}, 'index': {}, 'id': {} } } ], 'properties': { 'fakeTabsProperty1': {}, 'fakeTabsProperty2': {} }, 'functions': [ { 'name': 'getCurrent', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] }, { 'name': 'get', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] } ], 'events': [ { 'name': 'onUpdated', 'parameters': [ { 'name': 'tabId' }, { 'name': 'changeInfo', 'properties': { 'pinned': {}, 'status': {} } } ] } ] }]) } }, '1084': { 'api': { 'tabs.json': json.dumps([{ 'namespace': 'tabs', 'types': [ { 'id': 'Tab', 'properties': { 'url': {}, 'index': {}, 'id': {} } } ], 'properties': { 'fakeTabsProperty1': {}, 'fakeTabsProperty2': {} }, 'functions': [ { 'name': 'getCurrent', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] }, { 'name': 'get', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] } ], 'events': [ { 'name': 'onUpdated', 'parameters': [ { 'name': 'tabId' }, { 'name': 'changeInfo', 'properties': { 'pinned': {}, 'status': {} } } ] } ] }]) } }, '1025': { 'api': { 'tabs.json': json.dumps([{ 'namespace': 'tabs', 'types': [ { 'id': 'Tab', 'properties': { 'url': {}, 'index': {}, 'id': {} } } ], 'properties': { 'fakeTabsProperty1': {}, 'fakeTabsProperty2': {} }, 'functions': [ { 'name': 'get', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] } ], 'events': [ { 'name': 'onUpdated', 'parameters': [ { 'name': 'tabId' }, { 'name': 'changeInfo', 'properties': { 'pinned': {}, 'status': {} } } ] } ] }]) } }, '963': { 'api': { 'extension_api.json': json.dumps([{ 'namespace': 'tabs', 'types': [ { 'id': 'Tab', 'properties': { 'url': {}, 'id': {} } } ], 'properties': { 'fakeTabsProperty1': {}, 'fakeTabsProperty2': {} }, 'functions': [ { 'name': 'get', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] } ], 'events': [ { 'name': 'onUpdated', 'parameters': [ { 'name': 'tabId' }, { 'name': 'changeInfo', 'properties': { 'pinned': {}, 'status': {} } } ] } ] }]) } }, '912': { 'api': { 'extension_api.json': json.dumps([{ 'namespace': 'tabs', 'types': [ { 'id': 'Tab', 'properties': { 'url': {}, 'id': {} } } ], 'properties': { 'fakeTabsProperty1': {}, 'fakeTabsProperty2': {} }, 'functions': [ { 'name': 'get', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] } ], 'events': [ { 'name': 'onUpdated', 'parameters': [ { 'name': 'tabId' } ] } ] }]) } }, '874': { 'api': { 'extension_api.json': json.dumps([{ 'namespace': 'tabs', 'types': [ { 'id': 'Tab', 'properties': { 'url': {}, 'id': {} } } ], 'properties': { 'fakeTabsProperty1': {}, 'fakeTabsProperty2': {} }, 'functions': [ { 'name': 'get', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] } ], 'events': [ { 'name': 'onUpdated', 'parameters': [ { 'name': 'tabId' } ] } ] }]) } }, '835': { 'api': { 'extension_api.json': json.dumps([{ 'namespace': 'tabs', 'types': [ { 'id': 'Tab', 'properties': { 'url': {}, 'id': {} } } ], 'properties': { 'fakeTabsProperty1': {} }, 'functions': [ { 'name': 'get', 'parameters': [ { 'name': 'callback', 'parameters': [ { 'name': 'tab' } ] } ] } ], 'events': [ { 'name': 'onUpdated', 'parameters': [ { 'name': 'tabId' } ] } ] }]) } }, '782': { 'api': { 'extension_api.json': "{}" } } })
from collections import defaultdict from django.conf import settings from django.contrib import auth from django.core.exceptions import PermissionDenied from django.core.mail import send_mail from django.db import IntegrityError from canvas.exceptions import ServiceError, ValidationError from canvas.models import UserInfo, FacebookUser, Visibility from canvas.view_guards import require_user from canvas.view_helpers import check_rate_limit from drawquest import economy from drawquest.api_decorators import api_decorator from drawquest.apps.drawquest_auth.details_models import PrivateUserDetails from drawquest.apps.drawquest_auth.inactive import inactive_user_http_response from drawquest.apps.drawquest_auth.models import User from drawquest.apps.push_notifications.models import is_subscribed urlpatterns = [] api = api_decorator(urlpatterns) @api('username_available') def username_available(request, username): if User.objects.filter(username__iexact=username): return {'available': False} return { 'available': True, 'reserved_from_canvas': User.is_username_reserved(username), } @api('email_is_unused') def email_is_unused(request, email): return {'email_is_unused': User.email_is_unused(email)} @api('signup') def signup(request, username, password, email, facebook_access_token=None): if check_rate_limit(request, username): raise ServiceError("Too many signup attempts. Wait a minute and try again.") try: return _login(request, password, username=username, email=email) except ValidationError: pass migrated_from_canvas_account = False errors = defaultdict(list) fb_user = None if facebook_access_token: fb_user = FacebookUser.create_from_access_token(facebook_access_token) def username_taken(): # Ugly hack. for error in errors['username']: if 'taken' in error: return errors['username'].append("Sorry! That username is already taken.") if not password: errors['password'].append("Please enter a password.") if not User.validate_password(password): errors['password'].append("Sorry, your password is too short. " "Please use {} or more characters.".format(User.MINIMUM_PASSWORD_LENGTH)) if not email: errors['email'].append("Please enter your email address.") elif not User.validate_email(email): errors['email'].append("Please enter a valid email address.") username_error = User.validate_username(username) if username_error: errors['username'].append(username_error) if not User.email_is_unused(email): errors['email'].append("Sorry! That email address is already being used for an account.") elif User.is_username_reserved(username): try: user = User.migrate_canvas_user(request, username, password, email=email) except IntegrityError: username_taken() except ValidationError: errors['username'] = ["""Sorry! This username is taken. Please pick a different username, """ + """or if you are "{}," enter your password to sign in.""".format(username)] else: migrated_from_canvas_account = True if errors: if fb_user: fb_user.delete() raise ValidationError(errors) if not migrated_from_canvas_account: try: user = User.objects.create_user(username, email, password) except IntegrityError: username_taken() raise ValidationError(errors) UserInfo.objects.create(user=user) if fb_user: fb_user.user = user fb_user.save() fb_user.notify_friends_of_signup(facebook_access_token) user.migrate_facebook_avatar(request, facebook_access_token) user = auth.authenticate(username=username, password=password) # auth.login starts a new session and copies the session data from the old one to the new one auth.login(request, user) return { 'user': PrivateUserDetails.from_id(user.id).to_client(), 'user_bio': user.userinfo.bio_text, 'user_subscribed_to_starred': is_subscribed(user, 'starred'), 'sessionid': request.session.session_key, 'migrated_from_canvas_account': migrated_from_canvas_account, } @api('login_with_facebook') def login_with_facebook(request, facebook_access_token): try: fb_user = FacebookUser.get_from_access_token(facebook_access_token) except FacebookUser.DoesNotExist: raise PermissionDenied("No DrawQuest user exists for this Facebook account.") user = fb_user.user if not user.is_active: return inactive_user_http_response() # this is a total hack because we don't care to write a backend for the above authenticate method user.backend = settings.AUTHENTICATION_BACKENDS[0] auth.login(request, user) return { 'user': PrivateUserDetails.from_id(user.id).to_client(), 'user_bio': user.userinfo.bio_text, 'user_subscribed_to_starred': is_subscribed(user, 'starred'), 'sessionid': request.session.session_key, } def _login(request, password, username=None, email=None): migrated_from_canvas_account = False def wrong_password(): raise ValidationError({ 'password': "The password you entered is incorrect. " "Please try again (make sure your caps lock is off)." }) def wrong_username(username): raise ValidationError({ 'username': """The username you entered, "{}", doesn't exist. """.format(username) + """Please try again, or enter the e-mail address you used to sign up.""" }) def get_username_from_email(email): if not email: wrong_username(email) try: return User.objects.get(email=email).username except User.DoesNotExist: wrong_username(email) if not username and not email: raise ValidationError({'username': "Username is required to sign in."}) if not username: username = get_username_from_email(email) user = auth.authenticate(username=username, password=password) if user is None: # Maybe they entered an email into the username field? try: User.objects.get(username=username) except User.DoesNotExist: try: #TODO This might be broken - should probably pass username. username = get_username_from_email(email) user = auth.authenticate(username=username, password=password) except ValidationError: # No such username exists. # See if it's a example.com account we need to migrate over. if User.is_username_reserved(username): try: user = User.migrate_canvas_user(request, username, password, email=email) except ValidationError as e: wrong_password() else: migrated_from_canvas_account = True if user is None: wrong_password() if not user.is_active: return inactive_user_http_response() auth.login(request, user) return { 'user': PrivateUserDetails.from_id(user.id).to_client(), 'user_bio': user.userinfo.bio_text, 'user_subscribed_to_starred': is_subscribed(user, 'starred'), 'sessionid': request.session.session_key, 'migrated_from_canvas_account': migrated_from_canvas_account, } @api('login') def login(request, password, username=None, email=None): return _login(request, password, username=username, email=email) @api('logout') @require_user def logout(request): user_id = request.user.id auth.logout(request) return {'user': PrivateUserDetails.from_id(user_id).to_client()} @api('deactivate') @require_user def deactivate_user(request): """ Sends us an email. """ subject = "User deactivation request ({})".format(request.user.username) admin_url = 'http://example.com/admin/api_console' message = "{}\n\n{}\n\n{}".format(request.user.username, request.user.email, admin_url) from_ = "support@example.com" to = "support@example.com" send_mail(subject, message, from_, [to]) @api('actually_deactivate') @require_user def actually_deactivate_user(request): for comment in request.user.comments.all(): if comment.is_visible(): comment.moderate_and_save(Visibility.UNPUBLISHED, request.user, undoing=True) request.user.is_active = False request.user.save()
# Author: Fred L. Drake, Jr. # fdrake@cnri.reston.va.us, fdrake@acm.org # # This is a simple little module I wrote to make life easier. I didn't # see anything quite like it in the library, though I may have overlooked # something. I wrote this when I was trying to read some heavily nested # tuples with fairly non-descriptive content. This is modeled very much # after Lisp/Scheme - style pretty-printing of lists. If you find it # useful, thank small children who sleep at night. """Support to pretty-print lists, tuples, & dictionaries recursively. Very simple, but useful, especially in debugging data structures. Classes ------- PrettyPrinter() Handle pretty-printing operations onto a stream using a configured set of formatting parameters. Functions --------- pformat() Format a Python object into a pretty-printed representation. pprint() Pretty-print a Python object to a stream [default is sys.sydout]. saferepr() Generate a 'standard' repr()-like value, but protect against recursive data structures. """ from types import DictType, ListType, TupleType try: from cStringIO import StringIO except ImportError: from StringIO import StringIO __all__ = ["pprint","pformat","isreadable","isrecursive","saferepr", "PrettyPrinter"] def pprint(object, stream=None): """Pretty-print a Python object to a stream [default is sys.sydout].""" printer = PrettyPrinter(stream=stream) printer.pprint(object) def pformat(object): """Format a Python object into a pretty-printed representation.""" return PrettyPrinter().pformat(object) def isreadable(object): """Determine if saferepr(object) is readable by eval().""" return PrettyPrinter().isreadable(object) def isrecursive(object): """Determine if object requires a recursive representation.""" return PrettyPrinter().isrecursive(object) def saferepr(object): """Version of repr() which can handle recursive data structures.""" return _safe_repr(object, {})[0] class PrettyPrinter: def __init__(self, indent=1, width=80, depth=None, stream=None): """Handle pretty printing operations onto a stream using a set of configured parameters. indent Number of spaces to indent for each level of nesting. width Attempted maximum number of columns in the output. depth The maximum depth to print out nested structures. stream The desired output stream. If omitted (or false), the standard output stream available at construction will be used. """ indent = int(indent) width = int(width) assert indent >= 0 assert (not depth) or depth > 0, "depth may not be negative" assert width self.__depth = depth self.__indent_per_level = indent self.__width = width if stream: self.__stream = stream else: import sys self.__stream = sys.stdout def pprint(self, object): self.__stream.write(self.pformat(object) + "\n") def pformat(self, object): sio = StringIO() self.__format(object, sio, 0, 0, {}, 0) return sio.getvalue() def isrecursive(self, object): self.__recursive = 0 self.pformat(object) return self.__recursive def isreadable(self, object): self.__recursive = 0 self.__readable = 1 self.pformat(object) return self.__readable and not self.__recursive def __format(self, object, stream, indent, allowance, context, level): level = level + 1 if context.has_key(id(object)): object = _Recursion(object) self.__recursive = 1 rep = self.__repr(object, context, level - 1) objid = id(object) context[objid] = 1 typ = type(object) sepLines = len(rep) > (self.__width - 1 - indent - allowance) if sepLines and typ in (ListType, TupleType): # Pretty-print the sequence. stream.write((typ is ListType) and '[' or '(') if self.__indent_per_level > 1: stream.write((self.__indent_per_level - 1) * ' ') length = len(object) if length: indent = indent + self.__indent_per_level self.__format(object[0], stream, indent, allowance + 1, context, level) if length > 1: for ent in object[1:]: stream.write(',\n' + ' '*indent) self.__format(ent, stream, indent, allowance + 1, context, level) indent = indent - self.__indent_per_level if typ is TupleType and length == 1: stream.write(',') stream.write(((typ is ListType) and ']') or ')') elif sepLines and typ is DictType: stream.write('{') if self.__indent_per_level > 1: stream.write((self.__indent_per_level - 1) * ' ') length = len(object) if length: indent = indent + self.__indent_per_level items = object.items() items.sort() key, ent = items[0] rep = self.__repr(key, context, level) + ': ' stream.write(rep) self.__format(ent, stream, indent + len(rep), allowance + 1, context, level) if len(items) > 1: for key, ent in items[1:]: rep = self.__repr(key, context, level) + ': ' stream.write(',\n' + ' '*indent + rep) self.__format(ent, stream, indent + len(rep), allowance + 1, context, level) indent = indent - self.__indent_per_level stream.write('}') else: stream.write(rep) del context[objid] def __repr(self, object, context, level): repr, readable = _safe_repr(object, context, self.__depth, level) if not readable: self.__readable = 0 return repr def _safe_repr(object, context, maxlevels=None, level=0): level = level + 1 typ = type(object) if not (typ in (DictType, ListType, TupleType) and object): rep = `object` return rep, (rep and (rep[0] != '<')) if context.has_key(id(object)): return `_Recursion(object)`, 0 objid = id(object) context[objid] = 1 readable = 1 if typ is DictType: if maxlevels and level >= maxlevels: s = "{...}" readable = 0 else: items = object.items() k, v = items[0] krepr, kreadable = _safe_repr(k, context, maxlevels, level) vrepr, vreadable = _safe_repr(v, context, maxlevels, level) readable = readable and kreadable and vreadable s = "{%s: %s" % (krepr, vrepr) for k, v in items[1:]: krepr, kreadable = _safe_repr(k, context, maxlevels, level) vrepr, vreadable = _safe_repr(v, context, maxlevels, level) readable = readable and kreadable and vreadable s = "%s, %s: %s" % (s, krepr, vrepr) s = s + "}" else: s, term = (typ is ListType) and ('[', ']') or ('(', ')') if maxlevels and level >= maxlevels: s = s + "..." readable = 0 else: subrepr, subreadable = _safe_repr( object[0], context, maxlevels, level) readable = readable and subreadable s = s + subrepr tail = object[1:] if not tail: if typ is TupleType: s = s + ',' for ent in tail: subrepr, subreadable = _safe_repr( ent, context, maxlevels, level) readable = readable and subreadable s = "%s, %s" % (s, subrepr) s = s + term del context[objid] return s, readable class _Recursion: # represent a recursive relationship; really only used for the __repr__() # method... def __init__(self, object): self.__repr = "<Recursion on %s with id=%s>" \ % (type(object).__name__, id(object)) def __repr__(self): return self.__repr
import shapely.geometry as geom import matplotlib.pyplot as plt from copy import copy from numpy import inf, dot import math import munkres import scipy.spatial as spatial import numpy as np class PolygonInterpolator: def __init__(self, p1 = None, p2 = None): if p1 is not None and p2 is not None: self.p1 = p1 self.p2 = p2 self.compute_interpolation() self.compute_vertex_order() else: pass def compute_interpolation(self): done = set([]) pstrt = [geom.Point(p) for p in self.p1.exterior.coords[:-1]] pdest = [geom.Point(p) for p in self.p2.exterior.coords[:-1]] self.pairs, self.tuple_pairs = [], [] while len(pdest) > len(pstrt): pstrt += midpoints(pstrt) #Use hungarian algorithm to find the best set of match points mat = [[p1.distance(p2) for p2 in pstrt] for p1 in pdest] m = munkres.Munkres() indexes = m.compute(mat) for i in indexes: closest = pstrt[i[1]] p = pdest[i[0]] done.add(closest) self.pairs.append((closest, p)) self.tuple_pairs.append((as_tuple(closest), as_tuple(p))) #Match remaining start points to closest destination point for p in done.symmetric_difference(pstrt): closest, _ = project_point_points(p, pdest, 0) self.pairs.append((p, closest)) self.tuple_pairs.append((as_tuple(p), as_tuple(closest))) def compute_vertex_order(self): points = np.vstack(self.fast_interpolate_pairs(0.5)) hull = spatial.ConvexHull(points) #bar = (sum([p[0][0] for p in self.tuple_pairs]), # sum([p[0][1] for p in self.tuple_pairs])) #order_ccw = lambda p: math.atan2(p[0][1] - bar[1], p[0][0] - bar[0]) #order_ccw_p = lambda p: math.atan2(p[0].xy[1][0] - bar[1], p[0].xy[0][0] - bar[0]) #self.tuple_pairs = sorted(self.tuple_pairs, key=order_ccw) #self.pairs = sorted(self.pairs, key=order_ccw_p) self.order = hull.vertices self.tuple_pairs = [self.tuple_pairs[i] for i in self.order] self.pairs = [self.pairs[i] for i in self.order] def interpolate(self, percent): poly = [] for p1, p2 in self.pairs: line = geom.LineString((as_tuple(p1), as_tuple(p2))) interp = line.interpolate(percent, normalized=True) poly.append(as_tuple(interp)) return geom.Polygon(poly).convex_hull def fast_interpolate_pairs(self, percent): perc = max(min(percent, 1.), -1.) if perc < 0: perc = 1 + perc return [((t1[0]*(1-perc) + t2[0]*perc, t1[1]*(1-perc) + t2[1]*perc)) for t1, t2 in self.tuple_pairs] def fast_interpolate(self, percent): pairs = self.fast_interpolate_pairs(percent) return geom.Polygon(pairs).convex_hull def point_derivative(self, epsilon_derivative): return [point_derivative(p1, p2, epsilon_derivative) for p1, p2 in self.pairs] def pairs_derivative(self, epsilon_derivative): return [tuple_derivative(p1, p2, epsilon_derivative) for p1, p2 in self.tuple_pairs] def midpoint_derivative(self, epsilon_derivative): ps, pd = zip(*self.pairs) m_strt = midpoints(ps) m_dest = midpoints(pd) return [point_derivative(m, n, epsilon_derivative) for m, n in zip(m_strt, m_dest)] def point_dist_derivative(self, point, percent, epsilon_derivative): spd_points = self.pairs_derivative(epsilon_derivative) #cur_poly = self.fast_interpolate(percent).exterior.coords cur_poly = self.fast_interpolate_pairs(percent) spd_segment = [None]*len(spd_points) for i, p in enumerate(cur_poly): p2 = cur_poly[i-1] vec = (p[0] - p2[0], p[1] - p2[1]) vec_point = (point[0] - p2[0], point[1] - p2[1]) length = dot(vec, vec) dist = dot(vec, vec_point) spd_x = (spd_points[i-1][0]*dist+spd_points[i][0]*(length-dist))/length spd_y = (spd_points[i-1][1]*dist+spd_points[i][1]*(length-dist))/length #spd_y = spd_points[i-1][1]+spd_points[i][1]*dist/length #print vec #print vec_point #print spd_points[i-1], spd_points[i] #print length, dist #print spd_x, spd_y #print '---' spd_segment[i] = (spd_x, spd_y) return spd_segment def projections(self, point, percent): #cur_poly = self.fast_interpolate(percent) cur_poly = self.fast_interpolate_pairs(percent) #proj = [None]*(len(cur_poly.exterior.coords)-1) proj = [None]*len(cur_poly) for i, p in enumerate(cur_poly): p_prec = cur_poly[i-1] vec = (p[0] - p_prec[0], p[1] - p_prec[1]) vec_point = (point[0] - p_prec[0], point[1] - p_prec[1]) dist = dot(vec_point, vec) length = dot(vec, vec) x = p_prec[0]+(dist*vec[0]/length) y = p_prec[1]+(dist*vec[1]/length) proj[i] = (x, y) return proj def normals_offset(self, percent): points = self.fast_interpolate_pairs(percent) normals = [None]*len(points) offsets = [None]*len(points) norms = [None]*len(points) for i, p in enumerate(points): p2 = points[i-1] normal = (-(p[1] - p2[1]), p[0] - p2[0]) norm = math.sqrt(normal[0]**2+normal[1]**2) norms[i] = norm if norm > 9e-3: normal = (normal[0]/norm, normal[1]/norm) offset = -(normal[0]*p[0] + normal[1]*p[1]) else: normal = (0.0, 0.0) offset = 0 normals[i] = normal offsets[i] = offset print norms return normals, offsets def perc_normal_derivative(self, epsilon_derivative): n_strt, _ = self.normals_offset(0.) n_dest, _ = self.normals_offset(1.) return [tuple_derivative(n, m, epsilon_derivative) if n != (0., 0.) and n_dest != (0., 0.) else (0., 0.) for n, m in zip(n_strt, n_dest)] def normal_derivative(self, epsilon_derivative): ps, pd = zip(*self.pairs) poly_s = geom.Polygon([p.coords[0] for p in ps]) poly_d = geom.Polygon([p.coords[0] for p in pd]) n_strt, _ = normals_offset(poly_s) n_dest, _ = normals_offset(poly_d) return [tuple_derivative(n, m, epsilon_derivative) if n != (0., 0.) and n_dest != (0., 0.) else (0., 0.) for n, m in zip(n_strt, n_dest)] def point_derivative(p1, p2, e_n): return ((p2.x-p1.x)/e_n, (p2.y-p1.y)/e_n) def tuple_derivative(p1, p2, e_n): return ((p2[0]-p1[0])/e_n, (p2[1]-p1[1])/e_n) def plot_polygons(polys): for p in polys: x, y = p.exterior.xy plt.plot(x, y) plt.show() def plot_poly_normals(poly): fig = plt.figure() ax = fig.add_subplot(111, aspect='equal', autoscale_on=False, xlim=(-0.5, 2.5), ylim=(-0.5, 2.5)) x, y = poly.exterior.xy ax.plot(x, y) n, _ = normals_offset(poly) mid = midpoints([geom.Point(p) for p in zip(*poly.exterior.coords.xy)[:-1]]) print len(n), len(mid) x, y = zip(*[(p.xy[0], p.xy[1]) for p in mid]) u, v = zip(*n) ax.quiver(x, y, u, v) def as_tuple(point): return (point.xy[0][0], point.xy[1][0]) def midpoints(points): l = [] for i, point in enumerate(points): prev = points[i-1] mid = geom.Point((point.xy[0][0]+prev.xy[0][0])/2, (point.xy[1][0]+prev.xy[1][0])/2) l.append(mid) return l #Deprecated, better to use hungarian algorithm def interpolate_point_points(point, points, percent, exclude=set()): dists = [point.distance(p) if p not in exclude else inf for p in points] dmin = min(dists) closest = points[dists.index(dmin)] if point.xy == closest.xy: return closest, copy(closest) else: line = geom.LineString((as_tuple(point), as_tuple(closest))) interp = line.interpolate(percent, normalized=True) return closest, interp def project_point_points(point, points, percent): dists = [point.distance(p) for p in points] dmin = min(dists) imin = dists.index(dmin) closest = points[imin] if imin < len(points) - 1: next_p = points[imin+1] else: next_p = points[-1] prev_p = points[imin-1] if point.distance(prev_p) > point.distance(next_p): edge = geom.LineString([as_tuple(closest), as_tuple(next_p)]) else: edge = geom.LineString([as_tuple(prev_p), as_tuple(closest)]) if point.xy == closest.xy: return closest, copy(closest) else: dist = edge.project(point) projection = edge.interpolate(dist) line = geom.LineString((as_tuple(point), as_tuple(projection))) interp = line.interpolate(percent, normalized=True) return projection, interp #Deprecated : better to use Interpolator and hungarian algorithm def interpolate_poly(ps, pd, percent=0.1): new_p = [] done = set([]) pstrt = [geom.Point(p) for p in ps.exterior.coords[:-1]] pdest = [geom.Point(p) for p in pd.exterior.coords[:-1]] if len(pdest) > len(pstrt): pstrt += midpoints(pstrt) #Match every destination point to closest start point for p in pdest: closest, interpolate = interpolate_point_points(p, pstrt, 1-percent, done) new_p.append(as_tuple(interpolate)) done.add(closest) #Match remaining start points to closest destination point for p in done.symmetric_difference(pstrt): projection, interpolate = project_point_points(p, pdest, percent) new_p.append(as_tuple(interpolate)) return geom.Polygon(new_p).convex_hull def normals_offset(polygon): n = [] o = [] coords = polygon.exterior.coords[:-1] for i, p in enumerate(coords): normal = (p[1] - coords[i-1][1], -(p[0] - coords[i-1][0])) norm = math.sqrt(normal[0]**2+normal[1]**2) if norm > 0: normal = (normal[0]/norm, normal[1]/norm) else: normal = (0.0, 0.0) n.append(normal) o.append(-(normal[0]*p[0] + normal[1]*p[1])) return n, o
# 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. # ============================================================================== """Meatadata about fields for user-defined ExtensionType classes.""" import collections import collections.abc import typing from tensorflow.python.framework import composite_tensor from tensorflow.python.framework import dtypes from tensorflow.python.framework import immutable_dict from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_spec from tensorflow.python.framework import type_spec from tensorflow.python.util import type_annotations # These names may not be used as the name for a ExtensionType field (to prevent # name clashes). All names beginning with `'_tf_extension_type'` are also # reserved. RESERVED_FIELD_NAMES = [ 'self', # Name of the nested TypeSpec class. 'Spec', # Names defined by the CompositeTensor base class. '_type_spec', '_shape_invariant_to_type_spec', '_consumers', # Names defined by the TypeSpec base class. 'value_type', 'is_compatible_with', 'most_specific_compatible_type', '_with_tensor_ranks_only', '_to_components', '_from_components', '_component_specs', '_to_tensor_list', '_from_tensor_list', '_from_compatible_tensor_list', '_flat_tensor_specs', '_serialize', '_deserialize', '_to_legacy_output_types', '_to_legacy_output_shapes', '_to_legacy_output_classes', ] class Sentinel(object): """Sentinel value that's not equal (w/ `is`) to any user value.""" def __init__(self, name): self._name = name def __repr__(self): return self._name _NoneType = type(None) # ============================================================================== # ExtensionTypeField # ============================================================================== class ExtensionTypeField( collections.namedtuple('ExtensionTypeField', ['name', 'value_type', 'default'])): """Metadata about a single field in a `tf.ExtensionType` object.""" NO_DEFAULT = Sentinel('ExtensionTypeField.NO_DEFAULT') def __new__(cls, name, value_type, default=NO_DEFAULT): """Constructs a new ExtensionTypeField containing metadata for a single field. Args: name: The name of the new field (`str`). May not be a reserved name. value_type: A python type expression constraining what values this field can take. default: The default value for the new field, or `NO_DEFAULT` if this field has no default value. Returns: A new `ExtensionTypeField`. Raises: TypeError: If the type described by `value_type` is not currently supported by `tf.ExtensionType`. TypeError: If `default` is specified and its type does not match `value_type`. """ try: validate_field_value_type(value_type, allow_forward_references=True) except TypeError as e: raise TypeError(f'In field {name!r}: {e}') if default is not cls.NO_DEFAULT: default = _convert_value(default, value_type, (f'default value for {name}',)) return super(ExtensionTypeField, cls).__new__(cls, name, value_type, default) @staticmethod def is_reserved_name(name): """Returns true if `name` is a reserved name.""" return name in RESERVED_FIELD_NAMES or name.lower().startswith( '_tf_extension_type') def validate_field_value_type(value_type, in_mapping_key=False, allow_forward_references=False): """Checks that `value_type` contains only supported type annotations. Args: value_type: The type annotation to check. in_mapping_key: True if `value_type` is nested in the key of a mapping. allow_forward_references: If false, then raise an exception if a `value_type` contains a forward reference (i.e., a string literal). Raises: TypeError: If `value_type` contains an unsupported type annotation. """ if isinstance(value_type, str) or type_annotations.is_forward_ref(value_type): if allow_forward_references: return else: raise TypeError(f'Unresolved forward reference {value_type!r}') if value_type in (int, float, str, bytes, bool, None, _NoneType, dtypes.DType): return elif (value_type in (ops.Tensor, tensor_shape.TensorShape) or isinstance(value_type, type_spec.TypeSpec) or (isinstance(value_type, type) and issubclass(value_type, composite_tensor.CompositeTensor))): if in_mapping_key: raise TypeError('Key must be hashable.') elif (type_annotations.is_generic_tuple(value_type) or type_annotations.is_generic_union(value_type)): type_args = type_annotations.get_generic_type_args(value_type) if (len(type_args) == 2 and type_args[1] is Ellipsis and type_annotations.is_generic_tuple(value_type)): # `Tuple[X, ...]` validate_field_value_type(type_args[0], in_mapping_key, allow_forward_references) else: for arg in type_annotations.get_generic_type_args(value_type): validate_field_value_type(arg, in_mapping_key, allow_forward_references) elif type_annotations.is_generic_mapping(value_type): key_type, value_type = type_annotations.get_generic_type_args(value_type) validate_field_value_type(key_type, True, allow_forward_references) validate_field_value_type(value_type, in_mapping_key, allow_forward_references) elif isinstance(value_type, type): raise TypeError(f'Unsupported type annotation `{value_type.__name__}`') else: raise TypeError(f'Unsupported type annotation {value_type!r}') # ============================================================================== # Type-checking & conversion for ExtensionTypeField values # ============================================================================== def convert_fields(fields, field_values): """Type-checks and converts each field in `field_values` (in place). Args: fields: A list of `ExtensionTypeField` objects. field_values: A `dict` mapping field names to values. Must contain an entry for each field. I.e., `set(field_values.keys())` must be equal to `set([f.name for f in fields])`. Raises: ValueError: If the keys of `field_values` do not match the names of the fields in `fields`. TypeError: If any value in `field_values` does not have the type indicated by the corresponding `ExtensionTypeField` object. """ _convert_fields(fields, field_values, for_spec=False) def convert_fields_for_spec(fields, field_values): """Type-checks and converts field values for a TypeSpec (in place). This is similar to `convert_fields`, except that we expect a TypeSpec for tensor-like types. In particular, if the `value_type` of a field specifies a tensor-like type (tf.Tensor, CompositeTensor, or TypeSpec), then the corresponding value in `fields` is expected to contain a TypeSpec (rather than a value described by that TypeSpec). Args: fields: A list of `ExtensionTypeField` objects. field_values: A `dict` mapping field names to values. Must contain an entry for each field. I.e., `set(field_values.keys())` must be equal to `set([f.name for f in fields])`. Raises: ValueError: If the keys of `field_values` do not match the names of the fields in `fields`. TypeError: If any value in `field_values` does not have the type indicated by the corresponding `ExtensionTypeField` object. """ _convert_fields(fields, field_values, for_spec=True) def _convert_fields(fields, field_values, for_spec): """Type-checks and converts each field in `field_values` (in place). Args: fields: A list of `ExtensionTypeField` objects. field_values: A `dict` mapping field names to values. Must contain an entry for each field. I.e., `set(field_values.keys())` must be equal to `set([f.name for f in fields])`. for_spec: If false, then expect a value for tensor-like types; if true, then expect a TypeSpec for tensor-like types. Raises: ValueError: If the keys of `field_values` do not match the names of the fields in `fields`. TypeError: If any value in `field_values` does not have the type indicated by the corresponding `ExtensionTypeField` object. """ converted = {} if len(fields) != len(field_values): _report_field_mismatches(fields, field_values) for field in fields: if field.name not in field_values: _report_field_mismatches(fields, field_values) field_value = field_values[field.name] converted[field.name] = _convert_value(field_value, field.value_type, (field.name,), for_spec) field_values.update(converted) def _convert_value(value, expected_type, path, for_spec=False): """Type-checks and converts a value. Args: value: The value to type-check. expected_type: The expected type for the value. path: Tuple of `str` naming the value (used for exception messages). for_spec: If false, then expect a value for tensor-like types; if true, then expect a TensorSpec for tensor-like types. Returns: A copy of `value`, converted to the expected type. Raises: TypeError: If `value` can not be converted to the expected type. """ assert isinstance(path, tuple) if expected_type is None: expected_type = _NoneType if expected_type is ops.Tensor: return _convert_tensor(value, path, for_spec) elif isinstance(expected_type, tensor_spec.TensorSpec): return _convert_tensor_spec(value, expected_type, path, for_spec) elif isinstance(expected_type, type_spec.TypeSpec): return _convert_type_spec(value, expected_type, path, for_spec) elif (isinstance(expected_type, type) and issubclass(expected_type, composite_tensor.CompositeTensor)): return _convert_composite_tensor(value, expected_type, path, for_spec) elif expected_type in (int, float, bool, str, bytes, _NoneType, dtypes.DType, tensor_shape.TensorShape): if not isinstance(value, expected_type): raise TypeError(f'{"".join(path)}: expected ' f'{expected_type.__name__}, got {value!r}') return value elif type_annotations.is_generic_tuple(expected_type): return _convert_tuple(value, expected_type, path, for_spec) elif type_annotations.is_generic_mapping(expected_type): return _convert_mapping(value, expected_type, path, for_spec) elif type_annotations.is_generic_union(expected_type): return _convert_union(value, expected_type, path, for_spec) else: raise TypeError(f'{"".join(path)}: Unsupported type annotation ' f'{expected_type!r}') def _convert_tensor(value, path, for_spec): """Converts `value` to a `Tensor`.""" if for_spec: if not isinstance(value, tensor_spec.TensorSpec): raise TypeError(f'{"".join(path)}: expected a TensorSpec, got {value!r}') return value if not isinstance(value, ops.Tensor): try: value = ops.convert_to_tensor(value) except (ValueError, TypeError) as e: raise TypeError(f'{"".join(path)}: expected a Tensor, ' f'got {value!r}') from e return value def _convert_tensor_spec(value, expected_type, path, for_spec): """Converts `value` to a Tensor comptible with TensorSpec expected_type.""" if for_spec: if not (isinstance(value, tensor_spec.TensorSpec) and expected_type.is_compatible_with(value)): raise TypeError(f'{"".join(path)}: expected a TensorSpec compatible ' f'with {expected_type}, got {value!r}') return value if not isinstance(value, ops.Tensor): try: value = ops.convert_to_tensor(value, expected_type.dtype) except (ValueError, TypeError): raise TypeError(f'{"".join(path)}: expected a {expected_type.dtype!r} ' f'Tensor, got {value!r}') if not expected_type.is_compatible_with(value): raise TypeError(f'{"".join(path)}: expected a Tensor compatible with ' f'{expected_type}, got {value!r}') return value def _convert_type_spec(value, expected_type, path, for_spec): """Converts `value` to a value comptible with TypeSpec `expected_type`.""" if for_spec: if not (isinstance(value, type_spec.TypeSpec) and expected_type.is_compatible_with(value)): raise TypeError(f'{"".join(path)}: expected a TypeSpec compatible ' f'with {expected_type}, got {value!r}') return value if (isinstance(value, type_spec.TypeSpec) or not expected_type.is_compatible_with(value)): raise TypeError(f'{"".join(path)}: expected {expected_type!r}, ' f'got {value!r}') return value def _convert_composite_tensor(value, expected_type, path, for_spec): """Converts `value` to a value of type `expected_type`.""" if for_spec: if not (isinstance(value, type_spec.TypeSpec) and issubclass(value.value_type, expected_type)): raise TypeError(f'{"".join(path)}: expected a TypeSpec for ' f'{expected_type.__name__}, got {value!r}') return value if not isinstance(value, expected_type): raise TypeError(f'{"".join(path)}: expected {expected_type.__name__}, ' f'got {value!r}') return value def _convert_tuple(value, expected_type, path, for_spec): """Converts `value` to a tuple with type `expected_type`.""" if not isinstance(value, typing.Sequence): raise TypeError(f'{"".join(path)}: expected tuple, got {value!r}') element_types = type_annotations.get_generic_type_args(expected_type) if len(element_types) == 2 and element_types[1] is Ellipsis: return tuple([ _convert_value(v, element_types[0], path + (f'[{i}]',), for_spec) for (i, v) in enumerate(value) ]) else: if len(value) != len(element_types): raise TypeError(f'{"".join(path)}: expected tuple with length ' f'{len(element_types)}, got {value!r})') return tuple([ _convert_value(v, t, path + (f'[{i}]',), for_spec) for (i, (v, t)) in enumerate(zip(value, element_types)) ]) def _convert_mapping(value, expected_type, path, for_spec): """Converts `value` to a mapping with type `expected_type`.""" if not isinstance(value, typing.Mapping): raise TypeError(f'{"".join(path)}: expected mapping, got {value!r}') key_type, value_type = type_annotations.get_generic_type_args(expected_type) return immutable_dict.ImmutableDict([ (_convert_value(k, key_type, path + ('[<key>]',), for_spec), _convert_value(v, value_type, path + (f'[{k!r}]',), for_spec)) for (k, v) in value.items() ]) def _convert_union(value, expected_type, path, for_spec): """Converts `value` to a value with any of the types in `expected_type`.""" for type_option in type_annotations.get_generic_type_args(expected_type): try: return _convert_value(value, type_option, path, for_spec) except TypeError: pass raise TypeError(f'{"".join(path)}: expected {expected_type}, got {value!r}') def _report_field_mismatches(fields, field_values): """Raises an exception with mismatches between fields and field_values.""" expected = set(f.name for f in fields) actual = set(field_values) extra = actual - expected if extra: raise ValueError(f'Got unexpected fields: {extra}') missing = expected - actual if missing: raise ValueError(f'Missing required fields: {missing}')
#!/usr/bin/env python """ Test module for surface tension """ from builtins import range from builtins import object from proteus.iproteus import * from proteus import Comm comm = Comm.get() Profiling.logLevel=1 Profiling.verbose=True import os import numpy as np import tables import pytest from proteus import default_so from . import (parameters, risingBubble_so, risingBubble, vof_p, vof_n, ls_p, ls_n, redist_p, redist_n, ls_consrv_p, ls_consrv_n, twp_navier_stokes_p, twp_navier_stokes_n, pressureincrement_p, pressureincrement_n, pressure_p, pressure_n, pressureInitial_p, pressureInitial_n) class TestSurfaceTension(object): @classmethod def setup_class(cls): pass @classmethod def teardown_class(cls): pass def reload_modules(self): reload(default_so) reload(risingBubble) reload(risingBubble_so) reload(vof_p) reload(vof_n) reload(ls_p) reload(ls_n) reload(redist_p) reload(redist_n) reload(ls_consrv_p) reload(ls_consrv_n) reload(twp_navier_stokes_p) reload(twp_navier_stokes_n) reload(pressureincrement_p) reload(pressureincrement_n) reload(pressure_p) reload(pressure_n) reload(pressureInitial_p) reload(pressureInitial_n) def setup_method(self,method): self._scriptdir = os.path.dirname(__file__) def teardown_method(self,method): pass def compare_files(self,path,name): actual = tables.open_file(name+'.h5','r') expected_path = 'comparison_files/' + 'comparison_' + name + '_phi_t2.csv' #write comparison file #np.array(actual.root.phi_t2).tofile(os.path.join(self._scriptdir, expected_path),sep=",") np.testing.assert_almost_equal(np.fromfile(os.path.join(self._scriptdir, expected_path),sep=","),np.array(actual.root.phi_t2).flatten(),decimal=10) expected_path = 'comparison_files/' + 'comparison_' + name + '_p_t2.csv' #np.array(actual.root.p_t2).tofile(os.path.join(self._scriptdir, expected_path),sep=",") np.testing.assert_almost_equal(np.fromfile(os.path.join(self._scriptdir, expected_path),sep=","),np.array(actual.root.p_t2).flatten(),decimal=10) expected_path = 'comparison_files/' + 'comparison_' + name + '_velocity_t2.csv' #np.array(actual.root.velocity_t2).tofile(os.path.join(self._scriptdir, expected_path),sep=",") np.testing.assert_almost_equal(np.fromfile(os.path.join(self._scriptdir, expected_path),sep=","),np.array(actual.root.velocity_t2).flatten(),decimal=10) actual.close() def test_2D_with_supg(self): # Set parameters for this test parameters.ct.USE_SUPG_NS=1 parameters.ct.ARTIFICIAL_VISCOSITY_NS=1 parameters.ct.nd=2 # RELOAD MODULES self.reload_modules() pnList = [(vof_p, vof_n), (ls_p, ls_n), (redist_p, redist_n), (ls_consrv_p, ls_consrv_n), (twp_navier_stokes_p, twp_navier_stokes_n), (pressureincrement_p, pressureincrement_n), (pressure_p, pressure_n), (pressureInitial_p, pressureInitial_n)] self.so = risingBubble_so pList=[] nList=[] sList=[] for (pModule,nModule) in pnList: pList.append(pModule) if pList[-1].name == None: pList[-1].name = pModule.__name__ nList.append(nModule) for i in range(len(pnList)): sList.append(default_s) self.so.name += "_2D_supg" # NUMERICAL SOLUTION # ns = proteus.NumericalSolution.NS_base(self.so, pList, nList, sList, opts) ns.calculateSolution('2D_supg') # COMPARE VS SAVED FILES # #expected_path = 'comparison_files/risingBubble_2D_supg.h5' #expected = tables.open_file(os.path.join(self._scriptdir,expected_path)) #actual = tables.open_file('risingBubble_2D_supg.h5','r') #assert np.allclose(expected.root.phi_t2,actual.root.phi_t2,atol=1e-5) #assert np.allclose(expected.root.p_t2,actual.root.p_t2,atol=1e-5) #assert np.allclose(expected.root.velocity_t2,actual.root.velocity_t2,atol=1e-5) #expected.close() #actual.close() self.compare_files('comparison_files',self.so.name) def test_2D_with_EV(self): # Set parameters for this test parameters.ct.USE_SUPG_NS=0 parameters.ct.ARTIFICIAL_VISCOSITY_NS=2 parameters.ct.nd=2 # RELOAD MODULES self.reload_modules() pnList = [(vof_p, vof_n), (ls_p, ls_n), (redist_p, redist_n), (ls_consrv_p, ls_consrv_n), (twp_navier_stokes_p, twp_navier_stokes_n), (pressureincrement_p, pressureincrement_n), (pressure_p, pressure_n), (pressureInitial_p, pressureInitial_n)] self.so = risingBubble_so pList=[] nList=[] sList=[] for (pModule,nModule) in pnList: pList.append(pModule) if pList[-1].name == None: pList[-1].name = pModule.__name__ nList.append(nModule) for i in range(len(pnList)): sList.append(default_s) self.so.name += "_2D_ev" # NUMERICAL SOLUTION # ns = proteus.NumericalSolution.NS_base(self.so, pList, nList, sList, opts) ns.calculateSolution('2D_ev') # COMPARE VS SAVED FILES # #expected_path = 'comparison_files/risingBubble_2D_ev.h5' #expected = tables.open_file(os.path.join(self._scriptdir,expected_path)) #actual = tables.open_file('risingBubble_2D_ev.h5','r') #assert np.allclose(expected.root.phi_t2,actual.root.phi_t2,atol=1e-5) #assert np.allclose(expected.root.p_t2,actual.root.p_t2,atol=1e-5) #assert np.allclose(expected.root.velocity_t2,actual.root.velocity_t2,atol=1e-5) #expected.close() #actual.close() self.compare_files('comparison_files',self.so.name) def test_3D_with_SUPG(self): # Set parameters for this test parameters.ct.USE_SUPG_NS=1 parameters.ct.ARTIFICIAL_VISCOSITY_NS=1 parameters.ct.nd=3 # RELOAD MODULES self.reload_modules() pnList = [(vof_p, vof_n), (ls_p, ls_n), (redist_p, redist_n), (ls_consrv_p, ls_consrv_n), (twp_navier_stokes_p, twp_navier_stokes_n), (pressureincrement_p, pressureincrement_n), (pressure_p, pressure_n), (pressureInitial_p, pressureInitial_n)] self.so = risingBubble_so pList=[] nList=[] sList=[] for (pModule,nModule) in pnList: pList.append(pModule) if pList[-1].name == None: pList[-1].name = pModule.__name__ nList.append(nModule) for i in range(len(pnList)): sList.append(default_s) self.so.name += "_3D_supg" # NUMERICAL SOLUTION # ns = proteus.NumericalSolution.NS_base(self.so, pList, nList, sList, opts) ns.calculateSolution('3D_supg') # COMPARE VS SAVED FILES # #expected_path = 'comparison_files/risingBubble_3D_supg.h5' #expected = tables.open_file(os.path.join(self._scriptdir,expected_path)) #actual = tables.open_file('risingBubble_3D_supg.h5','r') #assert np.allclose(expected.root.phi_t2,actual.root.phi_t2,atol=1e-5) #assert np.allclose(expected.root.p_t2,actual.root.p_t2,atol=1e-5) #assert np.allclose(expected.root.velocity_t2,actual.root.velocity_t2,atol=1e-5) #expected.close() #actual.close() self.compare_files('comparison_files',self.so.name) def test_3D_with_EV(self): # Set parameters for this test parameters.ct.USE_SUPG_NS=0 parameters.ct.ARTIFICIAL_VISCOSITY_NS=2 parameters.ct.nd=3 # RELOAD MODULES self.reload_modules() pnList = [(vof_p, vof_n), (ls_p, ls_n), (redist_p, redist_n), (ls_consrv_p, ls_consrv_n), (twp_navier_stokes_p, twp_navier_stokes_n), (pressureincrement_p, pressureincrement_n), (pressure_p, pressure_n), (pressureInitial_p, pressureInitial_n)] self.so = risingBubble_so pList=[] nList=[] sList=[] for (pModule,nModule) in pnList: pList.append(pModule) if pList[-1].name == None: pList[-1].name = pModule.__name__ nList.append(nModule) for i in range(len(pnList)): sList.append(default_s) self.so.name += "_3D_ev" # NUMERICAL SOLUTION # ns = proteus.NumericalSolution.NS_base(self.so, pList, nList, sList, opts) failed = ns.calculateSolution('3D_ev') assert(not failed) # COMPARE VS SAVED FILES # #expected_path = 'comparison_files/risingBubble_3D_ev.h5' #expected = tables.open_file(os.path.join(self._scriptdir,expected_path)) #actual = tables.open_file('risingBubble_3D_ev.h5','r') #assert np.allclose(expected.root.phi_t2,actual.root.phi_t2,atol=1e-5) #assert np.allclose(expected.root.p_t2,actual.root.p_t2,atol=1e-5) #assert np.allclose(expected.root.velocity_t2,actual.root.velocity_t2,atol=1e-5) #expected.close() #actual.close() self.compare_files('comparison_files',self.so.name)
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging log = logging.getLogger(__name__) from language_tags import tags from sqlalchemy import ( Column, Integer, Text, String, ForeignKey, UniqueConstraint, Table, event ) from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import ( relationship, backref ) Base = declarative_base() concept_label = Table( 'concept_label', Base.metadata, Column('concept_id', Integer, ForeignKey('concept.id'), primary_key=True), Column('label_id', Integer, ForeignKey('label.id'), primary_key=True) ) conceptscheme_label = Table( 'conceptscheme_label', Base.metadata, Column( 'conceptscheme_id', Integer, ForeignKey('conceptscheme.id'), primary_key=True ), Column('label_id', Integer, ForeignKey('label.id'), primary_key=True) ) concept_note = Table( 'concept_note', Base.metadata, Column('concept_id', Integer, ForeignKey('concept.id'), primary_key=True), Column('note_id', Integer, ForeignKey('note.id'), primary_key=True) ) conceptscheme_note = Table( 'conceptscheme_note', Base.metadata, Column( 'conceptscheme_id', Integer, ForeignKey('conceptscheme.id'), primary_key=True ), Column('note_id', Integer, ForeignKey('note.id'), primary_key=True) ) collection_concept = Table( 'collection_concept', Base.metadata, Column( 'collection_id', Integer, ForeignKey('concept.id'), primary_key=True ), Column('concept_id', Integer, ForeignKey('concept.id'), primary_key=True) ) concept_related_concept = Table( 'concept_related_concept', Base.metadata, Column( 'concept_id_from', Integer, ForeignKey('concept.id'), primary_key=True ), Column( 'concept_id_to', Integer, ForeignKey('concept.id'), primary_key=True ) ) concept_hierarchy_concept = Table( 'concept_hierarchy_concept', Base.metadata, Column( 'concept_id_broader', Integer, ForeignKey('concept.id'), primary_key=True ), Column( 'concept_id_narrower', Integer, ForeignKey('concept.id'), primary_key=True ) ) concept_hierarchy_collection = Table( 'concept_hierarchy_collection', Base.metadata, Column( 'concept_id_broader', Integer, ForeignKey('concept.id'), primary_key=True ), Column( 'collection_id_narrower', Integer, ForeignKey('concept.id'), primary_key=True ) ) class Thing(Base): ''' Abstract class for both :class:`Concept` and :class:`Collection`. ''' __tablename__ = 'concept' __table_args__ = ( UniqueConstraint('conceptscheme_id', 'concept_id'), ) id = Column(Integer, primary_key=True) type = Column(String(30)) concept_id = Column( Integer, nullable=False, index=True ) uri = Column(String(512)) labels = relationship( 'Label', secondary=concept_label, backref=backref('concept', uselist=False), cascade='all, delete-orphan', single_parent=True ) notes = relationship( 'Note', secondary=concept_note, backref=backref('concept', uselist=False), cascade='all, delete-orphan', single_parent=True ) conceptscheme = relationship('ConceptScheme', backref='concepts') conceptscheme_id = Column( Integer, ForeignKey('conceptscheme.id'), nullable=False, index=True ) def label(self, language='any'): return label(self.labels, language) __mapper_args__ = { 'polymorphic_on': 'type', 'polymorphic_identity': 'thing' } class Concept(Thing): ''' A concept as know by :term:`skosprovider:SKOS`. ''' related_concepts = relationship( 'Concept', secondary=concept_related_concept, primaryjoin='Concept.id==concept_related_concept.c.concept_id_to', secondaryjoin='Concept.id==concept_related_concept.c.concept_id_from', collection_class=set ) narrower_concepts = relationship( 'Concept', secondary=concept_hierarchy_concept, backref=backref('broader_concepts', collection_class=set), primaryjoin='Concept.id==concept_hierarchy_concept.c.concept_id_broader', secondaryjoin='Concept.id==concept_hierarchy_concept.c.concept_id_narrower', collection_class=set ) narrower_collections = relationship( 'Collection', secondary=concept_hierarchy_collection, backref=backref('broader_concepts', collection_class=set), primaryjoin='Concept.id==concept_hierarchy_collection.c.concept_id_broader', secondaryjoin='Concept.id==concept_hierarchy_collection.c.collection_id_narrower', collection_class=set ) __mapper_args__ = { 'polymorphic_identity': 'concept' } def related_concepts_append_listener(target, value, initiator): ''' Listener that ensures related concepts have a bidirectional relationship. ''' if not hasattr(target, '__related_to_'): target.__related_to__ = set() target.__related_to__.add(value) if (target) not in getattr(value, '__related_to__', set()): value.related_concepts.add(target) event.listen( Concept.related_concepts, 'append', related_concepts_append_listener ) def related_concepts_remove_listener(target, value, initiator): ''' Listener to remove a related concept from both ends of the relationship. ''' if (value) in getattr(target, '__related_to__', set()): target.__related_to__.remove(value) if not hasattr(target, '__removed_from__'): target.__removed_from__ = set() target.__removed_from__.add(value) if target in value.related_concepts and target not in getattr(value, '__removed_from__', set()): value.related_concepts.remove(target) event.listen(Concept.related_concepts, 'remove', related_concepts_remove_listener) class Collection(Thing): ''' A collection as know by :term:`skosprovider:SKOS`. ''' __mapper_args__ = { 'polymorphic_identity': 'collection' } members = relationship( 'Thing', secondary=collection_concept, backref=backref('member_of', collection_class=set), primaryjoin='Thing.id==collection_concept.c.collection_id', secondaryjoin='Thing.id==collection_concept.c.concept_id', collection_class=set ) class ConceptScheme(Base): ''' A :term:`skosprovider:SKOS` conceptscheme. ''' __tablename__ = 'conceptscheme' id = Column(Integer, primary_key=True) uri = Column(String(512)) labels = relationship( 'Label', secondary=conceptscheme_label, backref=backref('conceptscheme', uselist=False) ) notes = relationship( 'Note', secondary=conceptscheme_note, backref=backref('conceptscheme', uselist=False) ) def label(self, language='any'): return label(self.labels, language) class Language(Base): ''' A Language. ''' __tablename__ = 'language' id = Column(String(64), primary_key=True) name = Column(String(255)) def __init__(self, id, name): self.id = id self.name = name def __str__(self): return self.name class LabelType(Base): ''' A labelType according to :term:`skosprovider:SKOS`. ''' __tablename__ = 'labeltype' name = Column(String(20), primary_key=True) description = Column(Text) def __init__(self, name, description): self.name = name self.description = description def __str__(self): return self.name class Label(Base): ''' A label for a :class:`Concept`, :class:`Collection` or :class:`ConceptScheme`. ''' __tablename__ = 'label' id = Column(Integer, primary_key=True) label = Column( String(512), nullable=False ) labeltype = relationship('LabelType', uselist=False) language = relationship('Language', uselist=False) labeltype_id = Column( String(20), ForeignKey('labeltype.name'), nullable=False, index=True ) language_id = Column( String(64), ForeignKey('language.id'), nullable=True, index=True ) def __init__(self, label, labeltype_id='prefLabel', language_id=None): self.labeltype_id = labeltype_id self.language_id = language_id self.label = label def __str__(self): return self.label class NoteType(Base): ''' A noteType according to :term:`skosprovider:SKOS`. ''' __tablename__ = 'notetype' name = Column(String(20), primary_key=True) description = Column(Text) def __init__(self, name, description): self.name = name self.description = description def __str__(self): return self.name class Note(Base): ''' A note for a :class:`Concept`, :class:`Collection` or :class:`ConceptScheme`. ''' __tablename__ = 'note' id = Column(Integer, primary_key=True) note = Column( Text, nullable=False ) notetype = relationship('NoteType', uselist=False) notetype_id = Column( String(20), ForeignKey('notetype.name'), nullable=False, index=True ) language = relationship('Language', uselist=False) language_id = Column( String(64), ForeignKey('language.id'), nullable=True, index=True ) markup = Column(String(20), nullable=True) def __init__(self, note, notetype_id, language_id, markup=None): self.notetype_id = notetype_id self.language_id = language_id self.note = note self.markup = markup def __str__(self): return self.note class MatchType(Base): ''' A matchType according to :term:`skosprovider:SKOS`. ''' __tablename__ = 'matchtype' name = Column(String(20), primary_key=True) description = Column(Text) def __init__(self, name, description): self.name = name self.description = description def __str__(self): return self.name class Match(Base): ''' A match between a :class:`Concept` in one ConceptScheme and those in another one. ''' __tablename__ = 'match' concept = relationship('Concept', backref=backref('matches', cascade='save-update, merge, ' 'delete, delete-orphan')) concept_id = Column( Integer, ForeignKey('concept.id'), primary_key=True ) matchtype = relationship('MatchType', uselist=False) matchtype_id = Column( String(20), ForeignKey('matchtype.name'), primary_key=True ) uri = Column( String(512), primary_key=True ) def __str__(self): return self.uri class Visitation(Base): ''' Holds several nested sets. The visitation object and table hold several nested sets. Each :class:`skosprovider_sqlalchemy.models.Visitation` holds the positional information for one conceptplacement in a certain nested set. Each conceptscheme gets its own separate nested set. ''' __tablename__ = 'visitation' id = Column(Integer, primary_key=True) lft = Column(Integer, index=True, nullable=False) rght = Column(Integer, index=True, nullable=False) depth = Column(Integer, index=True, nullable=False) conceptscheme = relationship('ConceptScheme') conceptscheme_id = Column( Integer, ForeignKey('conceptscheme.id'), nullable=False, index=True ) concept = relationship('Concept') concept_id = Column( Integer, ForeignKey('concept.id'), nullable=False, index=True ) def label(labels=[], language='any'): ''' Provide a label for a list of labels. The items in the list of labels are assumed to be instances of :class:`Label`. This method tries to find a label by looking if there's a pref label for the specified language. If there's no pref label, it looks for an alt label. It disregards hidden labels. While matching languages, preference will be given to exact matches. But, if no exact match is present, an inexact match will be attempted. This might be because a label in language `nl-BE` is being requested, but only `nl` or even `nl-NL` is present. Similarly, when requesting `nl`, a label with language `nl-NL` or even `nl-Latn-NL` will also be considered, providing no label is present that has an exact match with the requested language. If language 'any' was specified, all labels will be considered, regardless of language. To find a label without a specified language, pass `None` as language. If a language or None was specified, and no label could be found, this method will automatically try to find a label in some other language. Finally, if no label could be found, None is returned. :param list labels: A list of :class:`labels <Label>`. :param str language: The language for which a label should preferentially be returned. This should be a valid IANA language tag. :rtype: A :class:`Label` or `None` if no label could be found. ''' # Normalise the tag broader_language_tag = None if language != 'any': language = tags.tag(language).format broader_language_tag = tags.tag(language).language pref = None alt = None for l in labels: labeltype = l.labeltype_id or l.labeltype.name if language == 'any' or l.language_id == language: if labeltype == 'prefLabel' and (pref is None or pref.language_id != language): pref = l if labeltype == 'altLabel' and (alt is None or alt.language_id != language): alt = l if broader_language_tag and tags.tag(l.language_id).language and tags.tag( l.language_id).language.format == broader_language_tag.format: if labeltype == 'prefLabel' and pref is None: pref = l if labeltype == 'altLabel' and alt is None: alt = l if pref is not None: return pref elif alt is not None: return alt return label(labels, 'any') if language != 'any' else None class Initialiser(object): ''' Initialises a database. Adds necessary values for labelType, noteType and language to the database. The list of languages added by default is very small and will probably need to be expanded for your local needs. ''' def __init__(self, session): self.session = session def init_all(self): ''' Initialise all objects (labeltype, notetype, language). ''' self.init_labeltype() self.init_notetype() self.init_matchtypes() self.init_languages() def init_notetype(self): ''' Initialise the notetypes. ''' notetypes = [ ('changeNote', 'A change note.'), ('definition', 'A definition.'), ('editorialNote', 'An editorial note.'), ('example', 'An example.'), ('historyNote', 'A historynote.'), ('scopeNote', 'A scopenote.'), ('note', 'A note.') ] for n in notetypes: nt = NoteType(n[0], n[1]) self.session.add(nt) def init_labeltype(self): ''' Initialise the labeltypes. ''' labeltypes = [ ('hiddenLabel', 'A hidden label.'), ('altLabel', 'An alternative label.'), ('prefLabel', 'A preferred label.') ] for l in labeltypes: lt = LabelType(l[0], l[1]) self.session.add(lt) def init_matchtypes(self): ''' Initialise the matchtypes. ''' matchtypes = [ ('closeMatch', 'Indicates that two concepts are sufficiently similar that they can be used interchangeably in some information retrieval applications.'), ('exactMatch', 'Indicates that there is a high degree of confidence that two concepts can be used interchangeably across a wide range of information retrieval applications.'), ('broadMatch', 'Indicates that one concept has a broader match with another one.'), ('narrowMatch', 'Indicates that one concept has a narrower match with another one.'), ('relatedMatch', 'Indicates that there is an associative mapping between two concepts.') ] for m in matchtypes: mt = MatchType(m[0], m[1]) self.session.add(mt) def init_languages(self): ''' Initialise the languages. Only adds a small set of languages. Will probably not be sufficient for most use cases. ''' languages = [ ('la', 'Latin'), ('nl', 'Dutch'), ('vls', '(West) Flemish'), ('en', 'English'), ('fr', 'French'), ('de', 'German') ] for l in languages: lan = Language(l[0], l[1]) self.session.add(lan)
############################################################################### ## ## Copyright (C) 2014-2015, New York University. ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## "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 New York University 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." ## ############################################################################### """ Convert VTK classes into functions using spec in vtk.xml""" from __future__ import division import locale import os import tempfile import types from platform import system import vtk from . import fix_classes from .wrapper import VTKInstanceWrapper from .specs import SpecList, ClassSpec ################################################################################ # filter some deprecation warnings coming from the fact that vtk calls # range() with float parameters #### METHOD PATCHING CODE #### def patch_methods(base_module, cls): """class_dict(base_module, cls: vtkClass) -> dict Returns the class dictionary for the module represented by base_module and with base class base_module""" instance_dict = {} def update_dict(name, callable_): if instance_dict.has_key(name): instance_dict[name] = callable_(types.MethodType(instance_dict[name], base_module)) elif hasattr(base_module, name): instance_dict[name] = callable_(getattr(base_module, name)) else: instance_dict[name] = callable_(None) def compute_UpdateAlgorithm(oldUpdate): def call_UpdateAlgorithm(self): if self._callback is None: oldUpdate() return is_aborted = [False] cbId = None def ProgressEvent(obj, event): try: self._callback(obj.GetProgress()) except Exception, e: if e.__name__ == 'AbortExecution': obj.SetAbortExecute(True) self.RemoveObserver(cbId) is_aborted[0] = True else: raise cbId = self.AddObserver('ProgressEvent', ProgressEvent) oldUpdate() if not is_aborted[0]: self.RemoveObserver(cbId) return call_UpdateAlgorithm if issubclass(cls, vtk.vtkAlgorithm): update_dict('Update', compute_UpdateAlgorithm) def guarded_SimpleScalarTree_wrap_compute(old_compute): # This builds the scalar tree def compute(self): old_compute(self) self.vtkInstance.BuildTree() return compute if issubclass(cls, vtk.vtkScalarTree): update_dict('Update', guarded_SimpleScalarTree_wrap_compute) def guarded_Writer_wrap_compute(self): # The behavior for vtkWriter subclasses is to call Write() # If the user sets a name, we will create a file with that name # If not, we will create a temporary file using _tempfile fn = self.vtkInstance.GetFileName() if not fn: fn = self._tempfile(suffix='.vtk') self.vtkInstance.SetFileName(fn) self.vtkInstance.Write() return fn if issubclass(cls, vtk.vtkWriter): instance_dict['file'] = guarded_Writer_wrap_compute def guarded_SetFileName(old_compute): # This builds the scalar tree def check_SetFileName(self): # This checks for the presence of file in VTK readers # Skips the check if it's a vtkImageReader or vtkPLOT3DReader, because # it has other ways of specifying files, like SetFilePrefix for # multiple files skip = [vtk.vtkBYUReader, vtk.vtkImageReader, vtk.vtkDICOMImageReader, vtk.vtkTIFFReader] # vtkPLOT3DReader does not exist from version 6.0.0 v = vtk.vtkVersion() version = [v.GetVTKMajorVersion(), v.GetVTKMinorVersion(), v.GetVTKBuildVersion()] if version < [6, 0, 0]: skip.append(vtk.vtkPLOT3DReader) if not any(issubclass(cls, x) for x in skip): filename = self.vtkInstance.GetFileName() if not os.path.isfile(filename): raise Exception('File does not exist') old_compute() return check_SetFileName if hasattr(cls, 'SetFileName') and \ cls.__name__.endswith('Reader') and \ not cls.__name__.endswith('TiffReader'): update_dict('Update', guarded_SetFileName) def call_SetRenderWindow(self, vtkRenderer): window = vtk.vtkRenderWindow() w = 512 h = 512 window.OffScreenRenderingOn() window.SetSize(w, h) widget = None if system() == 'Darwin': from PyQt4 import QtCore, QtGui widget = QtGui.QWidget(None, QtCore.Qt.FramelessWindowHint) widget.resize(w, h) widget.show() window.SetWindowInfo(str(int(widget.winId()))) window.AddRenderer(vtkRenderer.vtkInstance) window.Render() self.vtkInstance.SetRenderWindow(window) if hasattr(cls, 'SetRenderWindow'): instance_dict['vtkRenderer'] = call_SetRenderWindow def call_TransferFunction(self, tf): tf.set_on_vtk_volume_property(self.vtkInstance) if issubclass(cls, vtk.vtkVolumeProperty): instance_dict['SetTransferFunction'] = call_TransferFunction def call_PointData(self, pd): self.vtkInstance.GetPointData().ShallowCopy(pd.vtkInstance) def call_CellData(self, cd): self.vtkInstance.GetCellData().ShallowCopy(cd.vtkInstance) if issubclass(cls, vtk.vtkDataSet): instance_dict['PointData'] = call_PointData instance_dict['CellData'] = call_CellData def call_PointIds(self, point_ids): self.vtkInstance.GetPointIds().SetNumberOfIds(point_ids.GetNumberOfIds()) for i in xrange(point_ids.GetNumberOfIds()): self.vtkInstance.GetPointIds().SetId(i, point_ids.vtkInstance.GetId(i)) if issubclass(cls, vtk.vtkCell): instance_dict['PointIds'] = call_PointIds def call_CopyImportVoidPointer(self, pointer): self.CopyImportVoidPointer(pointer, len(pointer)) return call_CopyImportVoidPointer if issubclass(cls, vtk.vtkImageImport): instance_dict['CopyImportString'] = call_CopyImportVoidPointer def call_GetFirstBlock(self): return VTKInstanceWrapper(self.vtkInstance.GetOutput().GetBlock(0)) if issubclass(cls, vtk.vtkMultiBlockPLOT3DReader): instance_dict['FirstBlock'] = call_GetFirstBlock for name, method in instance_dict.iteritems(): setattr(base_module, name, types.MethodType(method, base_module)) #### END METHOD PATCHING CODE #### class vtkObjectInfo(object): """ Each instance represents a VTK class """ def __init__(self, spec, parent=None): self.parent = parent self.spec = spec self.vtkClass = getattr(vtk, spec.code_ref) # use fixed classes if hasattr(fix_classes, self.vtkClass.__name__ + '_fixed'): self.vtkClass = getattr(fix_classes, self.vtkClass.__name__ + '_fixed') class VTKInstancePatcher(object): """ This is used in place of the vtk instance because it may not be safe to set attributes directly on the vtk object. """ def __init__(self, info_obj): # fixes reading data files on non-C locales self._previous_locale = locale.setlocale(locale.LC_ALL) locale.setlocale(locale.LC_ALL, 'C') self._info_obj = info_obj self._callback = None self._tempfile = tempfile.mkstemp self.vtkInstance = info_obj.vtkClass() patch_methods(self, info_obj.vtkClass) def _cleanup(self): locale.setlocale(locale.LC_ALL, self._previous_locale) def __getattr__(self, name): v = vtk.vtkVersion() version = [v.GetVTKMajorVersion(), v.GetVTKMinorVersion(), v.GetVTKBuildVersion()] if version < [6, 0, 0]: # Translate vtk6 method names to vtk5 method names to_vtk5_names = {'AddInputData': 'AddInput', 'AddDataSetInput': 'AddInput', 'SetInputData': 'SetInput', 'AddSourceData': 'AddSource', 'SetSourceData': 'SetSource'} for new, old in to_vtk5_names.iteritems(): if name.startswith(new): # Keep suffix name = old + name[len(new):] break # redirect calls to vtkInstance def call_wrapper(*args): args = list(args) for i in xrange(len(args)): if hasattr(args[i], 'vtkInstance'): # Unwrap VTK objects args[i] = args[i].vtkInstance args = tuple(args) #print "CALLING", name, [a.__class__.__name__ for a in args] result = getattr(self.vtkInstance, name)(*args) #print "GOT", result.__class__.__name__ if isinstance(result, vtk.vtkObjectBase): # Wrap VTK objects result = VTKInstanceWrapper(result) return result return call_wrapper def _set_callback(self, callback): self._callback = callback def _set_tempfile(self, tempfile): self._tempfile = tempfile def Update(self): if hasattr(self.vtkInstance, 'Update'): self.vtkInstance.Update() # keep track of created modules for use as subclasses infoObjs = {} def gen_instance_factory(spec): """Create an instance factory from a vtk class specification """ infoObj = vtkObjectInfo(spec, infoObjs.get(spec.superklass, None)) infoObjs[spec.module_name] = infoObj def instanceFactory(): return VTKInstancePatcher(infoObj) return instanceFactory specs = None def initialize(spec_name=None): """ Generate class wrappers and add them to current module namespace Also adds spec so it can be referenced by module wrapper """ global specs if spec_name is None: # The spec can be placed in the same folder if used as a standalone package spec_name = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'vtk.xml') if not os.path.exists(spec_name): return specs = SpecList.read_from_xml(spec_name, ClassSpec) for spec in specs.module_specs: globals()[spec.module_name] = gen_instance_factory(spec) # Initialize if possible initialize()
from datetime import datetime import time from BeautifulSoup import BeautifulSoup from lxml import etree, html import pytz import requests import utils def get_weather(body_of_water): if body_of_water == 'lake washington': return king_county_buoy(body_of_water) elif body_of_water == 'lake sammamish': return king_county_buoy(body_of_water) elif body_of_water == 'lake union': return lake_union_weather() else: return "I'm sorry, I couldn't find that body of water" # If we're getting the data from the Lake Union Weather webpage def lake_union_weather(): url_to_use = 'https://lakeunionweather.info' page = requests.get(url_to_use) soup = BeautifulSoup(page.content) try: header_data = soup.findAll("div", {"id": "Header"})[0] atmosphere_data = soup.findAll("table", {"id": "WeatherTable"})[0] water_data = soup.findAll("table", {"id": "WaterTable"})[0] except IndexError: pass # First lets get the date and time out of this info_date = None date_data = header_data.findAll('h4')[0] date_data = BeautifulSoup("{}".format(date_data)).getText() date_string = date_data.split('recorded on')[1].strip() info_date = datetime.strptime(date_string, "%d %b %Y %I:%M %p") # This is a gross way to get all the data from the table, but so it goes air_temp_f = None wind_chill_f = None avg_windspeed_dir = None avg_windspeed_mph = None for tr in BeautifulSoup("{}".format(atmosphere_data)).findAll('tr')[1:]: ths = BeautifulSoup("{}".format(tr.findAll('th')[0])).getText() tds = BeautifulSoup("{}".format(tr.findAll('td')[0])).getText() if ths.find('Temperature') >= 0: air_temp_f = float(tds.split('&#176;F')[0]) elif ths.find('Wind Chill') >= 0: wind_chill_f = float(tds.split('&#176;F')[0]) elif ths.find('Av. Windspeed') >= 0: avg_windspeed_mph = float(tds.split('MPH')[0].strip()) avg_windspeed_dir = tds.split('from the')[1].strip() # This is a gross way to get all the data from the table, but so it goes water_temp_f = None for tr in BeautifulSoup("{}".format(water_data)).findAll('tr')[1:]: tds = tr.findAll('td') if float(BeautifulSoup("{}".format(tds[0])).getText()) < 5: water_temp_f = float(BeautifulSoup("{}".format(tds[1])).getText()) # Now let's find the time diff when we got this if info_date is None: time_string = "" else: # Need to make this aware of the time zone tz = pytz.timezone('US/Pacific') latest_date_tz = tz.localize(info_date) time_diff = datetime.now(tz) - latest_date_tz # time_diff = datetime.now() - latest_date_water_temp if time_diff.days > 0: hours_diff = time_diff.days * 24 hours_diff += time_diff.seconds / 60 / 60 else: hours_diff = time_diff.seconds / 60 / 60 time_string = " about {} hours ago".format(hours_diff) if air_temp_f is None and water_temp_f is None: # This means we didn't find anythiing retval = "I'm sorry, I couldn't find any recent data about the weather on lake union" else: retval = "Last known conditions on lake union include: " num_values = 0 if air_temp_f is not None: retval += "Water temperature of {:.0f} degrees fahrenheit".format(round(air_temp_f)) num_values += 1 if air_temp_f is not None: if num_values > 0: retval += ", and " retval += "Air temperature of {:.0f} degrees fahrenheit, ".format(round(air_temp_f)) retval += "Wind chill of {:.0f} degrees fahrenheit, ".format(round(wind_chill_f)) retval += "wind speed of {:.0f} miles per hour ".format(round(utils.mps_to_mph(avg_windspeed_mph), 1)) retval += "coming from the {}".format(utils.compass_to_words(avg_windspeed_dir)) retval += "{}".format(time_string) return retval # If we're getting the data from King County buoy data def king_county_buoy(body_of_water): if body_of_water == 'lake washington': buoy = 'wa' elif body_of_water == 'lake sammamish': buoy = 'samm' else: return "I'm sorry, I couldn't find that body of water" water_temp_url = 'https://green2.kingcounty.gov/lake-buoy/DataScrape.aspx?type=profile&buoy={}&year={}&month={}' air_temp_url = 'https://green2.kingcounty.gov/lake-buoy/DataScrape.aspx?type=met&buoy={}&year={}&month={}' # Of course we need to get the local timezones, since the buoy data is local to pacific tz = pytz.timezone('US/Pacific') dt = datetime.fromtimestamp(time.time(), tz) current_month = dt.strftime('%m') current_year = dt.strftime("%Y") # First let's get the water temperature from the buoy data # We're going to get back this awesome ASPX table that we'll have to disect url_to_use = water_temp_url.format(buoy, current_year, current_month) r = requests.get(url_to_use) table_start = r.content.find('<table') table_end = r.content.find('</table>') + 8 table_string = r.content[table_start:table_end] # Now we have the string from the response that is the table. # Let's look for the latest temp at a reasonable (< 1.5m) depth. Record the date/time/temp latest_date_water_temp = datetime.strptime('01/01/2000', "%m/%d/%Y") # latest_depth = 0 latest_temp_water = 0 table = etree.XML(table_string) rows = iter(table) headers = [col.text for col in next(rows)] for row in rows: values = [col.text for col in row] row_dict = dict(zip(headers, values)) if float(row_dict.get('Depth (m)')) < 1.5: temp_c = float(row_dict.get(u'Temperature (\xb0C)')) temp_f = temp_c * 1.8 + 32 date_object = datetime.strptime(row_dict.get('Date'), "%m/%d/%Y %I:%M:%S %p") if date_object >= latest_date_water_temp: latest_date_water_temp = date_object # latest_depth = row_dict.get('Depth (m)') latest_temp_water = temp_f # Excellent, now we have our most recent water temp latest_temp_water = round(latest_temp_water, 1) # Now let's get the air temperature from the buoy data # We're going to get back this awesome ASPX table that we'll have to disect url_to_use = air_temp_url.format(buoy, current_year, current_month) r = requests.get(url_to_use) table_start = r.content.find('<table') table_end = r.content.find('</table>') + 8 table_string = r.content[table_start:table_end] # Now we have the string from the response that is the table. # Let's look for the latest temp at a reasonable (< 1.5m) depth. Record the date/time/temp latest_date_air_temp = datetime.strptime('01/01/2000', "%m/%d/%Y") latest_temp_air = 0 latest_wind_air_speed = 0 latest_wind_air_dir = '' table = etree.XML(table_string) rows = iter(table) headers = [col.text for col in next(rows)] for row in rows: values = [col.text for col in row] row_dict = dict(zip(headers, values)) temp_c = float(row_dict.get(u'Air Temperature (\xb0C)')) temp_f = temp_c * 1.8 + 32 date_object = datetime.strptime(row_dict.get('Date'), "%m/%d/%Y %I:%M:%S %p") if date_object >= latest_date_air_temp: latest_date_air_temp = date_object latest_temp_air = temp_f latest_wind_air_speed = float(row_dict.get(u'Wind Speed (m/sec)')) latest_wind_air_dir = float(row_dict.get(u'Wind Direction (degrees)')) # Excellent, now we have our most recent water temp latest_temp_air = round(latest_temp_air, 1) if latest_date_water_temp == datetime.strptime('01/01/2000', "%m/%d/%Y") and \ latest_date_air_temp == datetime.strptime('01/01/2000', "%m/%d/%Y"): # This means we didn't find anythiing retval = "I'm sorry, I couldn't find any recent data about the weather on {}".format(body_of_water) else: retval = "Last known conditions on {} include: ".format(body_of_water) num_values = 0 if latest_date_water_temp != datetime.strptime('01/01/2000', "%m/%d/%Y"): # Need to make this aware of the time zone tz = pytz.timezone('US/Pacific') latest_date_tz = tz.localize(latest_date_water_temp) time_diff = datetime.now(tz) - latest_date_tz # time_diff = datetime.now() - latest_date_water_temp if time_diff.days > 0: hours_diff = time_diff.days * 24 hours_diff += time_diff.seconds / 60 / 60 else: hours_diff = time_diff.seconds / 60 / 60 retval += "Water temperature of {:.0f} degrees fahrenheit about {} hours ago".format(round(latest_temp_water), hours_diff) num_values += 1 if latest_date_air_temp != datetime.strptime('01/01/2000', "%m/%d/%Y"): # Need to make this aware of the time zone tz = pytz.timezone('US/Pacific') latest_date_tz = tz.localize(latest_date_air_temp) time_diff = datetime.now(tz) - latest_date_tz # time_diff = datetime.now() - latest_date_water_temp if time_diff.days > 0: hours_diff = time_diff.days * 24 hours_diff += time_diff.seconds / 60 / 60 else: hours_diff = time_diff.seconds / 60 / 60 if num_values > 0: retval += ", and " retval += "Air temperature of {:.0f} degrees fahrenheit, ".format(round(latest_temp_air)) retval += "wind speed of {:.0f} miles per hour ".format(round(utils.mps_to_mph(latest_wind_air_speed), 1)) retval += "coming from the {}".format(utils.compass_to_words(utils.deg_to_compass(latest_wind_air_dir))) retval += "about {} hours ago".format(hours_diff) return retval
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Gradients for operators defined in math_ops.py.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.eager import context from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import gen_array_ops from tensorflow.python.ops import gen_math_ops from tensorflow.python.ops import math_ops def _safe_shape_div(x, y): """Divides `x / y` assuming `x, y >= 0`, treating `0 / 0 = 0`.""" return x // math_ops.maximum(y, 1) @ops.RegisterGradient("Sum") def _SumGrad(op, grad): """Gradient for Sum.""" # Fast path for when reducing to a scalar and ndims is known: adds only # Reshape and Tile ops (and possibly a Shape). if op.inputs[0].get_shape().ndims is not None: axes = tensor_util.constant_value(op.inputs[1]) if axes is not None: rank = op.inputs[0].get_shape().ndims if np.array_equal(axes, np.arange(rank)): # Reduce all dims. grad = array_ops.reshape(grad, [1] * rank) # If shape is not fully defined (but rank is), we use Shape. if op.inputs[0].get_shape().is_fully_defined(): input_shape = op.inputs[0].get_shape().as_list() else: input_shape = array_ops.shape(op.inputs[0]) return [array_ops.tile(grad, input_shape), None] input_shape = array_ops.shape(op.inputs[0]) # TODO(apassos) remove this once device placement for eager ops makes more # sense. with ops.colocate_with(input_shape): output_shape_kept_dims = math_ops.reduced_shape(input_shape, op.inputs[1]) tile_scaling = _safe_shape_div(input_shape, output_shape_kept_dims) grad = array_ops.reshape(grad, output_shape_kept_dims) return [array_ops.tile(grad, tile_scaling), None] def _MinOrMaxGrad(op, grad): """Gradient for Min or Max. Amazingly it's precisely the same code.""" input_shape = array_ops.shape(op.inputs[0]) output_shape_kept_dims = math_ops.reduced_shape(input_shape, op.inputs[1]) y = op.outputs[0] y = array_ops.reshape(y, output_shape_kept_dims) grad = array_ops.reshape(grad, output_shape_kept_dims) # Compute the number of selected (maximum or minimum) elements in each # reduction dimension. If there are multiple minimum or maximum elements # then the gradient will be divided between them. indicators = math_ops.cast(math_ops.equal(y, op.inputs[0]), grad.dtype) num_selected = array_ops.reshape( math_ops.reduce_sum(indicators, op.inputs[1]), output_shape_kept_dims) return [math_ops.div(indicators, num_selected) * grad, None] @ops.RegisterGradient("Max") def _MaxGrad(op, grad): """Gradient for Max.""" return _MinOrMaxGrad(op, grad) @ops.RegisterGradient("Min") def _MinGrad(op, grad): return _MinOrMaxGrad(op, grad) @ops.RegisterGradient("Mean") def _MeanGrad(op, grad): """Gradient for Mean.""" sum_grad = _SumGrad(op, grad)[0] input_size = op.inputs[0].get_shape().num_elements() output_size = op.outputs[0].get_shape().num_elements() if input_size is not None and output_size is not None: factor = input_size // max(output_size, 1) factor = constant_op.constant(factor, dtype=sum_grad.dtype) else: input_shape = array_ops.shape(op.inputs[0]) output_shape = array_ops.shape(op.outputs[0]) factor = _safe_shape_div( math_ops.reduce_prod(input_shape), math_ops.reduce_prod(output_shape)) return sum_grad / math_ops.cast(factor, sum_grad.dtype), None @ops.RegisterGradient("Prod") def _ProdGrad(op, grad): """Gradient for Prod.""" # The gradient can be expressed by dividing the product by each entry of the # input tensor, but this approach can't deal with zeros in the input. # Here, we avoid this problem by composing the output as a product of two # cumprod operations. input_shape = array_ops.shape(op.inputs[0]) # Reshape reduction indices for the case where the parameter is a scalar reduction_indices = array_ops.reshape(op.inputs[1], [-1]) # Expand grad to full input shape output_shape_kept_dims = math_ops.reduced_shape(input_shape, op.inputs[1]) tile_scaling = _safe_shape_div(input_shape, output_shape_kept_dims) grad = array_ops.reshape(grad, output_shape_kept_dims) grad = array_ops.tile(grad, tile_scaling) # Pack all reduced dimensions into a single one, so we can perform the # cumprod ops. If the reduction dims list is empty, it defaults to float32, # so we need to cast here. We put all the shape-related ops on CPU to avoid # copying back and forth, and since listdiff is CPU only. with ops.device("/cpu:0"): rank = array_ops.rank(op.inputs[0]) reduction_indices = (reduction_indices + rank) % rank reduced = math_ops.cast(reduction_indices, dtypes.int32) idx = math_ops.range(0, rank) other, _ = array_ops.setdiff1d(idx, reduced) perm = array_ops.concat([reduced, other], 0) reduced_num = math_ops.reduce_prod(array_ops.gather(input_shape, reduced)) other_num = math_ops.reduce_prod(array_ops.gather(input_shape, other)) permuted = array_ops.transpose(op.inputs[0], perm) permuted_shape = array_ops.shape(permuted) reshaped = array_ops.reshape(permuted, (reduced_num, other_num)) # Calculate product, leaving out the current entry left = math_ops.cumprod(reshaped, axis=0, exclusive=True) right = math_ops.cumprod(reshaped, axis=0, exclusive=True, reverse=True) y = array_ops.reshape(left * right, permuted_shape) # Invert the transpose and reshape operations. # Make sure to set the statically known shape information through a reshape. out = grad * array_ops.transpose(y, array_ops.invert_permutation(perm)) return array_ops.reshape(out, input_shape), None @ops.RegisterGradient("SegmentSum") def _SegmentSumGrad(op, grad): """Gradient for SegmentSum.""" return array_ops.gather(grad, op.inputs[1]), None @ops.RegisterGradient("SegmentMean") def _SegmentMeanGrad(op, grad): """Gradient for SegmentMean.""" input_rank = array_ops.rank(op.inputs[0]) ones_shape = array_ops.concat([ array_ops.shape(op.inputs[1]), array_ops.fill(array_ops.expand_dims(input_rank - 1, 0), 1) ], 0) ones = array_ops.fill(ones_shape, constant_op.constant(1, dtype=grad.dtype)) scaled_grad = math_ops.div(grad, math_ops.segment_sum(ones, op.inputs[1])) return array_ops.gather(scaled_grad, op.inputs[1]), None @ops.RegisterGradient("SparseSegmentSum") def _SparseSegmentSumGrad(op, grad): """Gradient for SparseSegmentSum.""" input_rows = array_ops.shape(op.inputs[0])[0] return (math_ops.unsorted_segment_sum( array_ops.gather(grad, op.inputs[2]), op.inputs[1], input_rows), None, None) @ops.RegisterGradient("SparseSegmentMean") def _SparseSegmentMeanGrad(op, grad): """Gradient for SparseSegmentMean.""" dim0 = array_ops.shape(op.inputs[0])[0] return (math_ops.sparse_segment_mean_grad(grad, op.inputs[1], op.inputs[2], dim0), None, None) @ops.RegisterGradient("SparseSegmentSqrtN") def _SparseSegmentSqrtNGrad(op, grad): """Gradient for SparseSegmentSqrtN.""" dim0 = array_ops.shape(op.inputs[0])[0] return (math_ops.sparse_segment_sqrt_n_grad(grad, op.inputs[1], op.inputs[2], dim0), None, None) def _SegmentMinOrMaxGrad(op, grad, is_sorted): """Gradient for SegmentMin and (unsorted) SegmentMax. They share similar code.""" zeros = array_ops.zeros(array_ops.shape(op.inputs[0]), dtype=op.inputs[0].dtype) # Get the number of selected (minimum or maximum) elements in each segment. gathered_outputs = array_ops.gather(op.outputs[0], op.inputs[1]) is_selected = math_ops.equal(op.inputs[0], gathered_outputs) if is_sorted: num_selected = math_ops.segment_sum(math_ops.cast(is_selected, grad.dtype), op.inputs[1]) else: num_selected = math_ops.unsorted_segment_sum( math_ops.cast(is_selected, grad.dtype), op.inputs[1], op.inputs[2]) # Compute the gradient for each segment. The gradient for the ith segment is # divided evenly among the selected elements in that segment. weighted_grads = math_ops.div(grad, num_selected) gathered_grads = array_ops.gather(weighted_grads, op.inputs[1]) if is_sorted: return array_ops.where(is_selected, gathered_grads, zeros), None else: return array_ops.where(is_selected, gathered_grads, zeros), None, None @ops.RegisterGradient("SegmentMin") def _SegmentMinGrad(op, grad): """Gradient for SegmentMin.""" return _SegmentMinOrMaxGrad(op, grad, True) @ops.RegisterGradient("SegmentMax") def _SegmentMaxGrad(op, grad): """Gradient for SegmentMax.""" return _SegmentMinOrMaxGrad(op, grad, True) @ops.RegisterGradient("UnsortedSegmentSum") def _UnsortedSegmentSumGrad(op, grad): """Gradient for SegmentSum.""" return array_ops.gather(grad, op.inputs[1]), None, None @ops.RegisterGradient("UnsortedSegmentMax") def _UnsortedSegmentMaxGrad(op, grad): return _SegmentMinOrMaxGrad(op, grad, False) @ops.RegisterGradient("Abs") def _AbsGrad(op, grad): x = op.inputs[0] return grad * math_ops.sign(x) @ops.RegisterGradient("Neg") def _NegGrad(_, grad): """Returns -grad.""" return -grad @ops.RegisterGradient("Inv") def _InvGrad(op, grad): """Returns -grad * (1 / x^2).""" y = op.outputs[0] # y = 1 / x # pylint: disable=protected-access return gen_math_ops._reciprocal_grad(y, grad) @ops.RegisterGradient("Reciprocal") def _ReciprocalGrad(op, grad): """Returns -grad * (1 / x^2).""" y = op.outputs[0] # y = 1 / x # pylint: disable=protected-access return gen_math_ops._reciprocal_grad(y, grad) @ops.RegisterGradient("InvGrad") def _InvGradGrad(op, grad): b = op.inputs[1] # op.output[0]: y = -b * conj(a)^2 with ops.control_dependencies([grad]): ca = math_ops.conj(op.inputs[0]) cg = math_ops.conj(grad) # pylint: disable=protected-access return cg * -2.0 * b * ca, gen_math_ops._reciprocal_grad(ca, grad) @ops.RegisterGradient("ReciprocalGrad") def _ReciprocalGradGrad(op, grad): b = op.inputs[1] # op.output[0]: y = -b * conj(a)^2 with ops.control_dependencies([grad]): ca = math_ops.conj(op.inputs[0]) cg = math_ops.conj(grad) # pylint: disable=protected-access return cg * -2.0 * b * ca, gen_math_ops._reciprocal_grad(ca, grad) @ops.RegisterGradient("Square") def _SquareGrad(op, grad): x = op.inputs[0] # Added control dependencies to prevent 2*x from being computed too early. with ops.control_dependencies([grad]): x = math_ops.conj(x) return grad * (2.0 * x) @ops.RegisterGradient("Sqrt") def _SqrtGrad(op, grad): y = op.outputs[0] # y = x^(1/2) # pylint: disable=protected-access return gen_math_ops._sqrt_grad(y, grad) # pylint: enable=protected-access @ops.RegisterGradient("SqrtGrad") def _SqrtGradGrad(op, grad): a = op.inputs[0] y = op.outputs[0] # y = 0.5 * b / conj(a) with ops.control_dependencies([grad]): ga = grad / a return -math_ops.conj(ga) * y, 0.5 * ga @ops.RegisterGradient("Rsqrt") def _RsqrtGrad(op, grad): """Returns -0.5 * grad * conj(y)^3.""" y = op.outputs[0] # y = x^(-1/2) # pylint: disable=protected-access return gen_math_ops._rsqrt_grad(y, grad) # pylint: enable=protected-access @ops.RegisterGradient("RsqrtGrad") def _RsqrtGradGrad(op, grad): """Returns backprop gradient for f(a,b) = -0.5 * b * conj(a)^3.""" a = op.inputs[0] # a = x^{-1/2} b = op.inputs[1] # backprop gradient for a with ops.control_dependencies([grad]): ca = math_ops.conj(a) cg = math_ops.conj(grad) grad_a = -1.5 * cg * b * math_ops.square(ca) # pylint: disable=protected-access grad_b = gen_math_ops._rsqrt_grad(ca, grad) return grad_a, grad_b @ops.RegisterGradient("Exp") def _ExpGrad(op, grad): """Returns grad * exp(x).""" y = op.outputs[0] # y = e^x with ops.control_dependencies([grad]): y = math_ops.conj(y) return grad * y @ops.RegisterGradient("Expm1") def _Expm1Grad(op, grad): """Returns grad * exp(x).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) y = math_ops.exp(x) return grad * y @ops.RegisterGradient("Log") def _LogGrad(op, grad): """Returns grad * (1/x).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) return grad * math_ops.reciprocal(x) @ops.RegisterGradient("Log1p") def _Log1pGrad(op, grad): """Returns grad * (1/(1 + x)).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) return grad * math_ops.reciprocal(1 + x) @ops.RegisterGradient("Sinh") def _SinhGrad(op, grad): """Returns grad * cosh(x).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) return grad * math_ops.cosh(x) @ops.RegisterGradient("Cosh") def _CoshGrad(op, grad): """Returns grad * sinh(x).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) return grad * math_ops.sinh(x) @ops.RegisterGradient("Tanh") def _TanhGrad(op, grad): """Returns grad * (1 - tanh(x) * tanh(x)).""" y = op.outputs[0] # y = tanh(x) with ops.control_dependencies([grad]): y = math_ops.conj(y) # pylint: disable=protected-access return gen_math_ops._tanh_grad(y, grad) @ops.RegisterGradient("Asinh") def _AsinhGrad(op, grad): """Returns grad * 1/cosh(y).""" y = op.outputs[0] with ops.control_dependencies([grad]): y = math_ops.conj(y) return grad / math_ops.cosh(y) @ops.RegisterGradient("Acosh") def _AcoshGrad(op, grad): """Returns grad * 1/sinh(y).""" y = op.outputs[0] with ops.control_dependencies([grad]): y = math_ops.conj(y) return grad / math_ops.sinh(y) @ops.RegisterGradient("Atanh") def _AtanhGrad(op, grad): """Returns grad * 1/ (1 - x^2).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) x2 = math_ops.square(x) one = constant_op.constant(1, dtype=grad.dtype) inv = math_ops.reciprocal(math_ops.subtract(one, x2)) return grad * inv @ops.RegisterGradient("TanhGrad") def _TanhGradGrad(op, grad): with ops.control_dependencies([grad]): a = math_ops.conj(op.inputs[0]) b = math_ops.conj(op.inputs[1]) # pylint: disable=protected-access return grad * -2.0 * b * a, gen_math_ops._tanh_grad(a, grad) @ops.RegisterGradient("Erf") def _ErfGrad(op, grad): """Returns grad * 2/sqrt(pi) * exp(-x**2).""" x = op.inputs[0] two_over_root_pi = constant_op.constant(2 / np.sqrt(np.pi), dtype=grad.dtype) with ops.control_dependencies([grad]): x = math_ops.conj(x) return grad * two_over_root_pi * math_ops.exp(-math_ops.square(x)) @ops.RegisterGradient("Erfc") def _ErfcGrad(op, grad): """Returns -grad * 2/sqrt(pi) * exp(-x**2).""" x = op.inputs[0] minus_two_over_root_pi = constant_op.constant( -2 / np.sqrt(np.pi), dtype=grad.dtype) with ops.control_dependencies([grad]): x = math_ops.conj(x) return grad * minus_two_over_root_pi * math_ops.exp(-math_ops.square(x)) @ops.RegisterGradient("Lgamma") def _LgammaGrad(op, grad): """Returns grad * digamma(x).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) return grad * math_ops.digamma(x) @ops.RegisterGradient("Digamma") def _DigammaGrad(op, grad): """Compute gradient of the digamma function with respect to its argument.""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) return grad * math_ops.polygamma(array_ops.constant(1, dtype=x.dtype), x) @ops.RegisterGradient("Igamma") def _IgammaGrad(op, grad): """Returns gradient of igamma(a, x) with respect to x.""" # TODO(ebrevdo): Perhaps add the derivative w.r.t. a a = op.inputs[0] x = op.inputs[1] sa = array_ops.shape(a) sx = array_ops.shape(x) # pylint: disable=protected-access unused_ra, rx = gen_array_ops._broadcast_gradient_args(sa, sx) # pylint: enable=protected-access # Perform operations in log space before summing, because Gamma(a) # and Gamma'(a) can grow large. partial_x = math_ops.exp(-x + (a - 1) * math_ops.log(x) - math_ops.lgamma(a)) # TODO(b/36815900): Mark None return values as NotImplemented return (None, array_ops.reshape(math_ops.reduce_sum(partial_x * grad, rx), sx)) @ops.RegisterGradient("Igammac") def _IgammacGrad(op, grad): """Returns gradient of igammac(a, x) = 1 - igamma(a, x) w.r.t. x.""" _, igamma_grad_x = _IgammaGrad(op, grad) return None, -igamma_grad_x @ops.RegisterGradient("Betainc") def _BetaincGrad(op, grad): """Returns gradient of betainc(a, b, x) with respect to x.""" # TODO(ebrevdo): Perhaps add the derivative w.r.t. a, b a, b, x = op.inputs # two cases: x is a scalar and a/b are same-shaped tensors, or vice # versa; so its sufficient to check against shape(a). sa = array_ops.shape(a) sx = array_ops.shape(x) # pylint: disable=protected-access _, rx = gen_array_ops._broadcast_gradient_args(sa, sx) # pylint: enable=protected-access # Perform operations in log space before summing, because terms # can grow large. log_beta = (gen_math_ops.lgamma(a) + gen_math_ops.lgamma(b) - gen_math_ops.lgamma(a + b)) partial_x = math_ops.exp( (b - 1) * math_ops.log(1 - x) + (a - 1) * math_ops.log(x) - log_beta) # TODO(b/36815900): Mark None return values as NotImplemented return (None, # da None, # db array_ops.reshape(math_ops.reduce_sum(partial_x * grad, rx), sx)) @ops.RegisterGradient("Zeta") def _ZetaGrad(op, grad): """Returns gradient of zeta(x, q) with respect to x and q.""" # TODO(tillahoffmann): Add derivative with respect to x x = op.inputs[0] q = op.inputs[1] # Broadcast gradients sx = array_ops.shape(x) sq = array_ops.shape(q) # pylint: disable=protected-access unused_rx, rq = gen_array_ops._broadcast_gradient_args(sx, sq) # pylint: enable=protected-access # Evaluate gradient with ops.control_dependencies([grad]): x = math_ops.conj(x) q = math_ops.conj(q) partial_q = -x * math_ops.zeta(x + 1, q) # TODO(b/36815900): Mark None return values as NotImplemented return (None, array_ops.reshape(math_ops.reduce_sum(partial_q * grad, rq), sq)) @ops.RegisterGradient("Polygamma") def _PolygammaGrad(op, grad): """Returns gradient of psi(n, x) with respect to n and x.""" # TODO(tillahoffmann): Add derivative with respect to n n = op.inputs[0] x = op.inputs[1] # Broadcast gradients sn = array_ops.shape(n) sx = array_ops.shape(x) # pylint: disable=protected-access unused_rn, rx = gen_array_ops._broadcast_gradient_args(sn, sx) # pylint: enable=protected-access # Evaluate gradient with ops.control_dependencies([grad]): n = math_ops.conj(n) x = math_ops.conj(x) partial_x = math_ops.polygamma(n + 1, x) # TODO(b/36815900): Mark None return values as NotImplemented return (None, array_ops.reshape(math_ops.reduce_sum(partial_x * grad, rx), sx)) @ops.RegisterGradient("Sigmoid") def _SigmoidGrad(op, grad): """Returns grad * sigmoid(x) * (1 - sigmoid(x)).""" y = op.outputs[0] # y = sigmoid(x) with ops.control_dependencies([grad]): y = math_ops.conj(y) # pylint: disable=protected-access return gen_math_ops._sigmoid_grad(y, grad) @ops.RegisterGradient("SigmoidGrad") def _SigmoidGradGrad(op, grad): with ops.control_dependencies([grad]): a = math_ops.conj(op.inputs[0]) b = math_ops.conj(op.inputs[1]) gb = grad * b # pylint: disable=protected-access return gb - 2.0 * gb * a, gen_math_ops._sigmoid_grad(a, grad) @ops.RegisterGradient("Sign") def _SignGrad(op, _): """Returns 0.""" x = op.inputs[0] return array_ops.zeros(array_ops.shape(x), dtype=x.dtype) @ops.RegisterGradient("Sin") def _SinGrad(op, grad): """Returns grad * cos(x).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) return grad * math_ops.cos(x) @ops.RegisterGradient("Cos") def _CosGrad(op, grad): """Returns grad * -sin(x).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) return -grad * math_ops.sin(x) @ops.RegisterGradient("Tan") def _TanGrad(op, grad): """Returns grad * 1/sec^2(x).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) secx = math_ops.reciprocal(math_ops.cos(x)) secx2 = math_ops.square(secx) return grad * secx2 @ops.RegisterGradient("Asin") def _AsinGrad(op, grad): """Returns grad * 1/sqrt(1-x^2).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) x2 = math_ops.square(x) one = constant_op.constant(1, dtype=grad.dtype) den = math_ops.sqrt(math_ops.subtract(one, x2)) inv = math_ops.reciprocal(den) return grad * inv @ops.RegisterGradient("Acos") def _AcosGrad(op, grad): """Returns grad * -1/sqrt(1-x^2).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) x2 = math_ops.square(x) one = constant_op.constant(1, dtype=grad.dtype) den = math_ops.sqrt(math_ops.subtract(one, x2)) inv = math_ops.reciprocal(den) return -grad * inv @ops.RegisterGradient("Atan") def _AtanGrad(op, grad): """Returns grad * 1/ (1 + x^2).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) x2 = math_ops.square(x) one = constant_op.constant(1, dtype=grad.dtype) inv = math_ops.reciprocal(math_ops.add(one, x2)) return grad * inv @ops.RegisterGradient("Atan2") def _Atan2Grad(op, grad): """Returns grad * x / (x^2 + y^2), grad * -y / (x^2 + y^2).""" y = op.inputs[0] x = op.inputs[1] with ops.control_dependencies([grad]): grad_inv = grad / (math_ops.square(x) + math_ops.square(y)) return x * grad_inv, -y * grad_inv @ops.RegisterGradient("AddN") def _AddNGrad(op, grad): """Copies the gradient to all inputs.""" # Not broadcasting. return [grad] * len(op.inputs) def _ShapesFullySpecifiedAndEqual(x, y, grad): # pylint: disable=protected-access x_shape = x._shape_tuple() y_shape = y._shape_tuple() grad_shape = grad._shape_tuple() # pylint: enable=protected-access return (x_shape == y_shape and x_shape == grad_shape and x_shape is not None and None not in x_shape) @ops.RegisterGradient("Add") def _AddGrad(op, grad): """Gradient for Add.""" x = op.inputs[0] y = op.inputs[1] if (isinstance(grad, ops.Tensor) and _ShapesFullySpecifiedAndEqual(x, y, grad)): return grad, grad sx = array_ops.shape(x) sy = array_ops.shape(y) # pylint: disable=protected-access rx, ry = gen_array_ops._broadcast_gradient_args(sx, sy) # pylint: enable=protected-access return (array_ops.reshape(math_ops.reduce_sum(grad, rx), sx), array_ops.reshape(math_ops.reduce_sum(grad, ry), sy)) @ops.RegisterGradient("Sub") def _SubGrad(op, grad): x = op.inputs[0] y = op.inputs[1] sx = array_ops.shape(x) sy = array_ops.shape(y) # pylint: disable=protected-access rx, ry = gen_array_ops._broadcast_gradient_args(sx, sy) # pylint: enable=protected-access return (array_ops.reshape(math_ops.reduce_sum(grad, rx), sx), array_ops.reshape(-math_ops.reduce_sum(grad, ry), sy)) @ops.RegisterGradient("Mul") def _MulGrad(op, grad): """The gradient of scalar multiplication.""" x = op.inputs[0] y = op.inputs[1] # pylint: disable=protected-access if (isinstance(grad, ops.Tensor) and _ShapesFullySpecifiedAndEqual(x, y, grad) and grad.dtype in (dtypes.int32, dtypes.float32)): return gen_math_ops._mul(grad, y), gen_math_ops._mul(grad, x) assert x.dtype.base_dtype == y.dtype.base_dtype, (x.dtype, " vs. ", y.dtype) sx = array_ops.shape(x) sy = array_ops.shape(y) rx, ry = gen_array_ops._broadcast_gradient_args(sx, sy) # pylint: enable=protected-access x = math_ops.conj(x) y = math_ops.conj(y) return (array_ops.reshape(math_ops.reduce_sum(grad * y, rx), sx), array_ops.reshape(math_ops.reduce_sum(x * grad, ry), sy)) @ops.RegisterGradient("Div") def _DivGrad(op, grad): """The gradient for the Div operator.""" x = op.inputs[0] y = op.inputs[1] sx = array_ops.shape(x) sy = array_ops.shape(y) # pylint: disable=protected-access rx, ry = gen_array_ops._broadcast_gradient_args(sx, sy) # pylint: enable=protected-access x = math_ops.conj(x) y = math_ops.conj(y) return (array_ops.reshape(math_ops.reduce_sum(math_ops.div(grad, y), rx), sx), array_ops.reshape( math_ops.reduce_sum(grad * math_ops.div(math_ops.div(-x, y), y), ry), sy)) @ops.RegisterGradient("FloorDiv") def _FloorDivGrad(_, unused_grad): """The gradient for the FloorDiv operator.""" return None, None @ops.RegisterGradient("FloorMod") def _FloorModGrad(op, grad): """Returns grad * (1, -floor(x/y)).""" x = math_ops.conj(op.inputs[0]) y = math_ops.conj(op.inputs[1]) sx = array_ops.shape(x) sy = array_ops.shape(y) # pylint: disable=protected-access rx, ry = gen_array_ops._broadcast_gradient_args(sx, sy) # pylint: enable=protected-access floor_xy = math_ops.floor_div(x, y) gx = array_ops.reshape(math_ops.reduce_sum(grad, rx), sx) gy = array_ops.reshape( math_ops.reduce_sum(grad * math_ops.negative(floor_xy), ry), sy) return gx, gy @ops.RegisterGradient("TruncateDiv") def _TruncateDivGrad(_, unused_grad): return None, None @ops.RegisterGradient("RealDiv") def _RealDivGrad(op, grad): """RealDiv op gradient.""" x = op.inputs[0] y = op.inputs[1] sx = array_ops.shape(x) sy = array_ops.shape(y) # pylint: disable=protected-access rx, ry = gen_array_ops._broadcast_gradient_args(sx, sy) # pylint: enable=protected-access x = math_ops.conj(x) y = math_ops.conj(y) return (array_ops.reshape( math_ops.reduce_sum(math_ops.realdiv(grad, y), rx), sx), array_ops.reshape( math_ops.reduce_sum(grad * math_ops.realdiv(math_ops.realdiv(-x, y), y), ry), sy)) @ops.RegisterGradient("Pow") def _PowGrad(op, grad): """Returns grad * (y*x^(y-1), z*log(x)).""" x = op.inputs[0] y = op.inputs[1] z = op.outputs[0] sx = array_ops.shape(x) sy = array_ops.shape(y) rx, ry = gen_array_ops._broadcast_gradient_args(sx, sy) x = math_ops.conj(x) y = math_ops.conj(y) z = math_ops.conj(z) gx = array_ops.reshape( math_ops.reduce_sum(grad * y * math_ops.pow(x, y - 1), rx), sx) # Avoid false singularity at x = 0 if x.dtype.is_complex: # real(x) < 0 is fine for the complex case log_x = array_ops.where( math_ops.not_equal(x, 0), math_ops.log(x), array_ops.zeros_like(x)) else: # There's no sensible real value to return if x < 0, so return 0 log_x = array_ops.where(x > 0, math_ops.log(x), array_ops.zeros_like(x)) gy = array_ops.reshape(math_ops.reduce_sum(grad * z * log_x, ry), sy) return gx, gy def _MaximumMinimumGrad(op, grad, selector_op): """Factor out the code for the gradient of Maximum or Minimum.""" x = op.inputs[0] y = op.inputs[1] gdtype = grad.dtype sx = array_ops.shape(x) sy = array_ops.shape(y) gradshape = array_ops.shape(grad) zeros = array_ops.zeros(gradshape, gdtype) xmask = selector_op(x, y) rx, ry = gen_array_ops._broadcast_gradient_args(sx, sy) xgrad = array_ops.where(xmask, grad, zeros) ygrad = array_ops.where(xmask, zeros, grad) gx = array_ops.reshape(math_ops.reduce_sum(xgrad, rx), sx) gy = array_ops.reshape(math_ops.reduce_sum(ygrad, ry), sy) return (gx, gy) @ops.RegisterGradient("Maximum") def _MaximumGrad(op, grad): """Returns grad*(x > y, x <= y) with type of grad.""" return _MaximumMinimumGrad(op, grad, math_ops.greater_equal) @ops.RegisterGradient("Minimum") def _MinimumGrad(op, grad): """Returns grad*(x < y, x >= y) with type of grad.""" return _MaximumMinimumGrad(op, grad, math_ops.less_equal) @ops.RegisterGradient("SquaredDifference") def _SquaredDifferenceGrad(op, grad): """Returns the gradient for (x-y)^2.""" x = op.inputs[0] y = op.inputs[1] sx = array_ops.shape(x) sy = array_ops.shape(y) # pylint: disable=protected-access rx, ry = gen_array_ops._broadcast_gradient_args(sx, sy) # pylint: enable=protected-access with ops.control_dependencies([grad]): # The parens ensure that if grad is IndexedSlices, it'll get multiplied by # Tensor (not a number like 2.0) which causes it to convert to Tensor. x_grad = math_ops.scalar_mul(2.0, grad) * (x - y) return (array_ops.reshape(math_ops.reduce_sum(x_grad, rx), sx), -array_ops.reshape(math_ops.reduce_sum(x_grad, ry), sy)) # Logical operations have no gradients. ops.NotDifferentiable("Less") ops.NotDifferentiable("LessEqual") ops.NotDifferentiable("Greater") ops.NotDifferentiable("GreaterEqual") ops.NotDifferentiable("Equal") ops.NotDifferentiable("ApproximateEqual") ops.NotDifferentiable("NotEqual") ops.NotDifferentiable("LogicalAnd") ops.NotDifferentiable("LogicalOr") ops.NotDifferentiable("LogicalNot") @ops.RegisterGradient("Select") def _SelectGrad(op, grad): c = op.inputs[0] x = op.inputs[1] zeros = array_ops.zeros_like(x) return (None, array_ops.where(c, grad, zeros), array_ops.where(c, zeros, grad)) @ops.RegisterGradient("MatMul") def _MatMulGrad(op, grad): """Gradient for MatMul.""" t_a = op.get_attr("transpose_a") t_b = op.get_attr("transpose_b") a = math_ops.conj(op.inputs[0]) b = math_ops.conj(op.inputs[1]) if not t_a and not t_b: grad_a = math_ops.matmul(grad, b, transpose_b=True) grad_b = math_ops.matmul(a, grad, transpose_a=True) elif not t_a and t_b: grad_a = math_ops.matmul(grad, b) grad_b = math_ops.matmul(grad, a, transpose_a=True) elif t_a and not t_b: grad_a = math_ops.matmul(b, grad, transpose_b=True) grad_b = math_ops.matmul(a, grad) elif t_a and t_b: grad_a = math_ops.matmul(b, grad, transpose_a=True, transpose_b=True) grad_b = math_ops.matmul(grad, a, transpose_a=True, transpose_b=True) return grad_a, grad_b @ops.RegisterGradient("SparseMatMul") def _SparseMatMulGrad(op, grad): """Gradient for SparseMatMul.""" t_a = op.get_attr("transpose_a") t_b = op.get_attr("transpose_b") is_sparse = { op.inputs[0]: op.get_attr("a_is_sparse"), op.inputs[1]: op.get_attr("b_is_sparse"), # Use heuristic to figure out if grad might be sparse grad: context.in_graph_mode() and (grad.op.type == "ReluGrad") } def _SparseMatMul(t1, t2, out_dtype, transpose_a=False, transpose_b=False): """Helper function to create SparseMatMul op.""" assert t1 in is_sparse and t2 in is_sparse t1_sparse = is_sparse[t1] t2_sparse = is_sparse[t2] if transpose_b: t2 = array_ops.transpose(t2) transpose_b = False prod = math_ops.matmul( t1, t2, transpose_a=transpose_a, transpose_b=transpose_b, a_is_sparse=t1_sparse, b_is_sparse=t2_sparse) if prod.dtype != out_dtype: prod = math_ops.cast(prod, out_dtype) return prod dtype_a = op.inputs[0].dtype dtype_b = op.inputs[1].dtype if not t_a and not t_b: return (_SparseMatMul( grad, op.inputs[1], dtype_a, transpose_b=True), _SparseMatMul( op.inputs[0], grad, dtype_b, transpose_a=True)) elif not t_a and t_b: return (_SparseMatMul(grad, op.inputs[1], dtype_a), _SparseMatMul( grad, op.inputs[0], dtype_b, transpose_a=True)) elif t_a and not t_b: return (_SparseMatMul( op.inputs[1], grad, dtype_a, transpose_b=True), _SparseMatMul(op.inputs[0], grad, dtype_b)) elif t_a and t_b: return (_SparseMatMul( op.inputs[1], grad, dtype_a, transpose_a=True, transpose_b=True), _SparseMatMul( grad, op.inputs[0], dtype_b, transpose_a=True, transpose_b=True)) @ops.RegisterGradient("Floor") def _FloorGrad(_, unused_grad): return [None] @ops.RegisterGradient("Ceil") def _CeilGrad(_, unused_grad): return [None] @ops.RegisterGradient("Round") def _RoundGrad(_, unused_grad): return [None] @ops.RegisterGradient("Rint") def _RintGrad(_, unused_grad): # the gradient of Rint is zero return [None] @ops.RegisterGradient("BatchMatMul") def _BatchMatMul(op, grad): """Returns the gradient of x and y given the gradient of x * y.""" x = op.inputs[0] y = op.inputs[1] adj_x = op.get_attr("adj_x") adj_y = op.get_attr("adj_y") if not adj_x: if not adj_y: grad_x = math_ops.matmul(grad, y, adjoint_a=False, adjoint_b=True) grad_y = math_ops.matmul(x, grad, adjoint_a=True, adjoint_b=False) else: grad_x = math_ops.matmul(grad, y, adjoint_a=False, adjoint_b=False) grad_y = math_ops.matmul(grad, x, adjoint_a=True, adjoint_b=False) else: if not adj_y: grad_x = math_ops.matmul(y, grad, adjoint_a=False, adjoint_b=True) grad_y = math_ops.matmul(x, grad, adjoint_a=False, adjoint_b=False) else: grad_x = math_ops.matmul(y, grad, adjoint_a=True, adjoint_b=True) grad_y = math_ops.matmul(grad, x, adjoint_a=True, adjoint_b=True) return grad_x, grad_y ops.NotDifferentiable("Range") ops.NotDifferentiable("LinSpace") @ops.RegisterGradient("Complex") def _ComplexGrad(op, grad): """Returns the real and imaginary components of 'grad', respectively.""" x = op.inputs[0] y = op.inputs[1] sx = array_ops.shape(x) sy = array_ops.shape(y) rx, ry = gen_array_ops._broadcast_gradient_args(sx, sy) return (array_ops.reshape(math_ops.reduce_sum(math_ops.real(grad), rx), sx), array_ops.reshape(math_ops.reduce_sum(math_ops.imag(grad), ry), sy)) @ops.RegisterGradient("Real") def _RealGrad(_, grad): """Returns 'grad' as the real part and set the imaginary part 0.""" zero = constant_op.constant(0, dtype=grad.dtype) return math_ops.complex(grad, zero) @ops.RegisterGradient("Imag") def _ImagGrad(_, grad): """Returns 'grad' as the imaginary part and set the real part 0.""" zero = constant_op.constant(0, dtype=grad.dtype) return math_ops.complex(zero, grad) @ops.RegisterGradient("Angle") def _AngleGrad(op, grad): """Returns -grad / (Im(x) + iRe(x))""" x = op.inputs[0] with ops.control_dependencies([grad]): re = math_ops.real(x) im = math_ops.imag(x) z = math_ops.reciprocal(math_ops.complex(im, re)) zero = constant_op.constant(0, dtype=grad.dtype) complex_grad = math_ops.complex(grad, zero) return -complex_grad * z @ops.RegisterGradient("Conj") def _ConjGrad(_, grad): """Returns the complex conjugate of grad.""" return math_ops.conj(grad) @ops.RegisterGradient("ComplexAbs") def _ComplexAbsGrad(op, grad): """Returns the gradient of ComplexAbs.""" # TODO(b/27786104): The cast to complex could be removed once arithmetic # supports mixtures of complex64 and real values. return (math_ops.complex(grad, array_ops.zeros_like(grad)) * math_ops.sign(op.inputs[0])) @ops.RegisterGradient("Cast") def _CastGrad(op, grad): t = [ dtypes.float16, dtypes.float32, dtypes.float64, dtypes.bfloat16, dtypes.complex64, dtypes.complex128 ] src_type = op.inputs[0].dtype.base_dtype dst_type = grad.dtype.base_dtype if src_type in t and dst_type in t: return math_ops.cast(grad, src_type) else: return None @ops.RegisterGradient("Cross") def _CrossGrad(op, grad): u = op.inputs[0] v = op.inputs[1] return (math_ops.cross(v, grad), math_ops.cross(grad, u)) @ops.RegisterGradient("Cumsum") def _CumsumGrad(op, grad): axis = op.inputs[1] exclusive = op.get_attr("exclusive") reverse = op.get_attr("reverse") return [ math_ops.cumsum( grad, axis, exclusive=exclusive, reverse=not reverse), None ] @ops.RegisterGradient("Cumprod") def _CumprodGrad(op, grad): x = op.inputs[0] axis = op.inputs[1] exclusive = op.get_attr("exclusive") reverse = op.get_attr("reverse") # TODO This fails when x contains 0 and should be fixed prod = math_ops.cumprod(x, axis, exclusive=exclusive, reverse=reverse) out = math_ops.cumsum( prod * grad, axis, exclusive=exclusive, reverse=not reverse) return [out / x, None]
import paramiko import os from stat import S_ISDIR, S_ISREG class SSH(object): def __init__(self, usr='root', ip='127.0.0.1', port=22, pwd='', connect=True, logfile='/tmp/dedupe-ssh-log.txt'): self.usr = usr self.pwd = pwd self.ip = ip self.port = port self.logfile = logfile self.client = None if connect: self.connect() def connect(self): if not self.client: self.client = paramiko.SSHClient() self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.client.connect(hostname=self.ip, port=self.port, username=self.usr, password=self.pwd) def close(self): if self.client: self.client.close() self.client = None def execute(self, cmd=None, get_pty=False, old_pty=False): if old_pty: trans = self.client.get_transport() session = trans.open_session() session.set_combine_stderr(True) cmd = cmd.strip() if cmd.startswith('sudo') and (get_pty==False): print 'warning: when use sudo, get_pty should be set' if get_pty: session.get_pty() session.exec_command(cmd) stdin = session.makefile('wb', -1) stdout = session.makefile('rb', -1) #you have to check if you really need to send password here return stdin, stdout, '' else: return self.client.exec_command(cmd, get_pty=get_pty) def __del__(self): self.close() def transport(self, local, remote, method='put', rm_old=False): def recur_put(sftp, local, remote): try: stat = os.stat(local) except IOError as e: print 'remote file does not exist', e return mode = stat.st_mode & 0777 if os.path.isfile(local): print 'pushing %s' % local try: sftp.put(local, remote) sftp.chmod(remote, mode) except IOError as e: print '(assuming ', remote, 'parent directory does not exist)', e elif os.path.isdir(local): try: print 'making directory %s' % remote sftp.mkdir(remote, mode=mode) except IOError as e: print '(assuming ', remote, 'parent directory exists)', e for file in os.listdir(local): local_subpath = os.path.join(local, file) remote_subpath = os.path.join(remote, file) recur_put(sftp, local_subpath, remote_subpath) def recur_get(sftp, local, remote): try: stat = sftp.lstat(remote) except IOError as e: print 'remote file does not exist', e return mode = stat.st_mode & 0777 if S_ISREG(stat.st_mode): print 'pulling %s' % remote try: sftp.get(remote, local) os.chmod(local, mode) except IOError as e: print 'assuming ', local, 'prarent directory does not exist', e elif S_ISDIR(stat.st_mode): try: print 'making directory %s' % local os.mkdir(local, mode) except IOError as e: print '(assuming ', local, 'parent directory exists)', e for file in sftp.listdir(remote): local_subpath = os.path.join(local, file) remote_subpath = os.path.join(remote, file) recur_get(sftp, local_subpath, remote_subpath) def rmtree(sftp, remotepath): remote_tate = sftp.lstat(remotepath) if S_ISDIR(remote_tate.st_mode): for file in sftp.listdir(remotepath): subpath = remotepath + '/' + file rmtree(sftp, subpath) print 'removing directory %s' % remotepath sftp.rmdir(remotepath) elif S_ISREG(remote_tate.st_mode): print 'removing file %s' % remotepath sftp.remove(remotepath) else: print 'neither directory nor file % s' % remotepath def rmtree_local(localpath): if os.path.isdir(localpath): for file in os.listdir(localpath): subpath = os.path.join(localpath, file) rmtree_local(subpath) print 'removing directory %s' % localpath os.remove(localpath) elif os.path.isfile(localpath): print 'removing file %s' % localpath os.remove(localpath) else: print 'neither directory nor file %s' % localpath trans = self.client.get_transport() sftp = paramiko.SFTPClient.from_transport(trans) if method == 'put': try: if rm_old: rmtree(sftp, remote) print 'remove the old files' else: print 'not remove the old files' except IOError as e: print '(assuming ', remote, 'does not exists)', e recur_put(sftp, local, remote) elif method == 'get': try: if rm_old: rmtree_local(local) print 'remove the old files' else: print 'not remove the old files' except IOError as e: print '(assuming ', remote, 'does not exists)', e recur_get(sftp, local, remote) trans.close() def run_cmd(usr='root', ip='127.0.0.1', port=22, pwd=None, cmd=None): try: client = SSH(usr=usr, ip=ip, pwd=pwd, port=port) cmd = cmd.strip() if cmd.startswith('sudo'): stdin, stdout, stderr = client.execute(cmd, True, old_pty=True) stdin.write(pwd+'\n') stdin.flush() else: stdin, stdout, stderr = client.execute(cmd) try: for l in stdout: print '%s stdout: %s' % (ip, l.strip()) for l in stderr: print '%s stderr: %s' % (ip, l.strip()) except Exception as e: print 'cannot read the output %s on %s, error:' % (cmd, ip), e except Exception as e: print 'cannot execute the command %s on %s, error:' % (cmd, ip), e def run_cmds(usr='root', ip='127.0.0.1', port=22, pwd=None, cmds=None): for cmd in cmds: run_cmd(usr, ip, port, pwd, cmd) def upload(usr='root', ip='127.0.0.1', port=22, pwd=None, local=None, remote=None): try: client = SSH(usr=usr, ip=ip, port=port, pwd=pwd) client.transport(local, remote, 'put', True) except Exception as e: print 'cannot transport the file %s to %s, error:' % (local, ip), e def uploads(usr='root', ip='127.0.0.1', port=22, pwd=None, tasks=None): for local, remote in tasks: upload(usr, ip, port, pwd, local, remote) def download(usr='root', ip='127.0.0.1', port=22, pwd=None, local=None, remote=None): try: client = SSH(usr=usr, ip=ip, port=port, pwd=pwd) client.transport(local, remote, 'get', True) except Exception as e: print 'cannot transport the file %s to %s, error:' % (src, ip), e def downloads(usr='root', ip='127.0.0.1', port=22, pwd=None, tasks=None): for local, remote in tasks: download(usr, ip, port, pwd, local, remote)
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utility functions for coverage report generation.""" import os import json from common import experiment_path as exp_path from common import experiment_utils as exp_utils from common import new_process from common import benchmark_utils from common import fuzzer_utils from common import logs from common import filestore_utils from common import filesystem from database import utils as db_utils from database import models from experiment.build import build_utils logger = logs.Logger('coverage_utils') # pylint: disable=invalid-name COV_DIFF_QUEUE_GET_TIMEOUT = 1 def get_coverage_info_dir(): """Returns the directory to store coverage information including coverage report and json summary file.""" work_dir = exp_utils.get_work_dir() return os.path.join(work_dir, 'coverage') def generate_coverage_reports(experiment_config: dict): """Generates coverage reports for each benchmark and fuzzer.""" logs.initialize() logger.info('Start generating coverage reports.') benchmarks = experiment_config['benchmarks'] fuzzers = experiment_config['fuzzers'] experiment = experiment_config['experiment'] for benchmark in benchmarks: for fuzzer in fuzzers: generate_coverage_report(experiment, benchmark, fuzzer) logger.info('Finished generating coverage reports.') def generate_coverage_report(experiment, benchmark, fuzzer): """Generates the coverage report for one pair of benchmark and fuzzer.""" logger.info( ('Generating coverage report for ' 'benchmark: {benchmark} fuzzer: {fuzzer}.').format(benchmark=benchmark, fuzzer=fuzzer)) try: coverage_reporter = CoverageReporter(experiment, fuzzer, benchmark) # Merges all the profdata files. coverage_reporter.merge_profdata_files() # Generate the coverage summary json file based on merged profdata file. coverage_reporter.generate_coverage_summary_json() # Generate the coverage regions json file. coverage_reporter.generate_coverage_regions_json() # Generates the html reports using llvm-cov. coverage_reporter.generate_coverage_report() logger.info('Finished generating coverage report.') except Exception: # pylint: disable=broad-except logger.error('Error occurred when generating coverage report.') class CoverageReporter: # pylint: disable=too-many-instance-attributes """Class used to generate coverage report for a pair of fuzzer and benchmark.""" # pylint: disable=too-many-arguments def __init__(self, experiment, fuzzer, benchmark): self.fuzzer = fuzzer self.benchmark = benchmark self.experiment = experiment self.trial_ids = get_trial_ids(experiment, fuzzer, benchmark) coverage_info_dir = get_coverage_info_dir() self.report_dir = os.path.join(coverage_info_dir, 'reports', benchmark, fuzzer) self.data_dir = os.path.join(coverage_info_dir, 'data', benchmark, fuzzer) benchmark_fuzzer_dir = exp_utils.get_benchmark_fuzzer_dir( benchmark, fuzzer) work_dir = exp_utils.get_work_dir() benchmark_fuzzer_measurement_dir = os.path.join(work_dir, 'measurement-folders', benchmark_fuzzer_dir) self.merged_profdata_file = os.path.join( benchmark_fuzzer_measurement_dir, 'merged.profdata') self.merged_summary_json_file = os.path.join( benchmark_fuzzer_measurement_dir, 'merged.json') coverage_binaries_dir = build_utils.get_coverage_binaries_dir() self.source_files_dir = os.path.join(coverage_binaries_dir, benchmark) self.binary_file = get_coverage_binary(benchmark) def merge_profdata_files(self): """Merge profdata files from |src_files| to |dst_files|.""" logger.info('Merging profdata for fuzzer: ' '{fuzzer},benchmark: {benchmark}.'.format( fuzzer=self.fuzzer, benchmark=self.benchmark)) files_to_merge = [] for trial_id in self.trial_ids: profdata_file = TrialCoverage(self.fuzzer, self.benchmark, trial_id).profdata_file if not os.path.exists(profdata_file): continue files_to_merge.append(profdata_file) result = merge_profdata_files(files_to_merge, self.merged_profdata_file) if result.retcode != 0: logger.error('Profdata files merging failed.') def generate_coverage_summary_json(self): """Generates the coverage summary json from merged profdata file.""" coverage_binary = get_coverage_binary(self.benchmark) result = generate_json_summary(coverage_binary, self.merged_profdata_file, self.merged_summary_json_file, summary_only=False) if result.retcode != 0: logger.error( 'Merged coverage summary json file generation failed for ' 'fuzzer: {fuzzer},benchmark: {benchmark}.'.format( fuzzer=self.fuzzer, benchmark=self.benchmark)) def generate_coverage_report(self): """Generates the coverage report and stores in bucket.""" command = [ 'llvm-cov', 'show', '-format=html', '-path-equivalence=/,{prefix}'.format(prefix=self.source_files_dir), '-output-dir={dst_dir}'.format(dst_dir=self.report_dir), '-Xdemangler', 'c++filt', '-Xdemangler', '-n', self.binary_file, '-instr-profile={profdata}'.format( profdata=self.merged_profdata_file) ] result = new_process.execute(command, expect_zero=False) if result.retcode != 0: logger.error('Coverage report generation failed for ' 'fuzzer: {fuzzer},benchmark: {benchmark}.'.format( fuzzer=self.fuzzer, benchmark=self.benchmark)) return src_dir = self.report_dir dst_dir = exp_path.filestore(self.report_dir) filestore_utils.cp(src_dir, dst_dir, recursive=True, parallel=True) def generate_coverage_regions_json(self): """Stores the coverage data in a json file.""" covered_regions = extract_covered_regions_from_summary_json( self.merged_summary_json_file) coverage_json_src = os.path.join(self.data_dir, 'covered_regions.json') coverage_json_dst = exp_path.filestore(coverage_json_src) filesystem.create_directory(self.data_dir) with open(coverage_json_src, 'w') as file_handle: json.dump(covered_regions, file_handle) filestore_utils.cp(coverage_json_src, coverage_json_dst, expect_zero=False) def get_coverage_archive_name(benchmark): """Gets the archive name for |benchmark|.""" return 'coverage-build-%s.tar.gz' % benchmark def get_profdata_file_name(trial_id): """Returns the profdata file name for |trial_id|.""" return 'data-{id}.profdata'.format(id=trial_id) def get_coverage_binary(benchmark: str) -> str: """Gets the coverage binary for benchmark.""" coverage_binaries_dir = build_utils.get_coverage_binaries_dir() fuzz_target = benchmark_utils.get_fuzz_target(benchmark) return fuzzer_utils.get_fuzz_target_binary(coverage_binaries_dir / benchmark, fuzz_target_name=fuzz_target) def get_trial_ids(experiment: str, fuzzer: str, benchmark: str): """Gets ids of all finished trials for a pair of fuzzer and benchmark.""" with db_utils.session_scope() as session: trial_ids = [ trial_id_tuple[0] for trial_id_tuple in session.query(models.Trial.id).filter( models.Trial.experiment == experiment, models.Trial.fuzzer == fuzzer, models.Trial.benchmark == benchmark, ~models.Trial.preempted) ] return trial_ids def merge_profdata_files(src_files, dst_file): """Uses llvm-profdata to merge |src_files| to |dst_files|.""" command = ['llvm-profdata', 'merge', '-sparse'] command.extend(src_files) command.extend(['-o', dst_file]) result = new_process.execute(command, expect_zero=False) return result def get_coverage_infomation(coverage_summary_file): """Reads the coverage information from |coverage_summary_file| and skip possible warnings in the file.""" with open(coverage_summary_file) as summary: return json.loads(summary.readlines()[-1]) class TrialCoverage: # pylint: disable=too-many-instance-attributes """Base class for storing and getting coverage data for a trial.""" def __init__(self, fuzzer: str, benchmark: str, trial_num: int): self.fuzzer = fuzzer self.benchmark = benchmark self.trial_num = trial_num self.benchmark_fuzzer_trial_dir = exp_utils.get_trial_dir( fuzzer, benchmark, trial_num) self.work_dir = exp_utils.get_work_dir() self.measurement_dir = os.path.join(self.work_dir, 'measurement-folders', self.benchmark_fuzzer_trial_dir) self.report_dir = os.path.join(self.measurement_dir, 'reports') # Store the profdata file for the current trial. self.profdata_file = os.path.join(self.report_dir, 'data.profdata') def generate_json_summary(coverage_binary, profdata_file, output_file, summary_only=True): """Generates the json summary file from |coverage_binary| and |profdata_file|.""" command = [ 'llvm-cov', 'export', '-format=text', '-num-threads=1', '-region-coverage-gt=0', '-skip-expansions', coverage_binary, '-instr-profile=%s' % profdata_file ] if summary_only: command.append('-summary-only') with open(output_file, 'w') as dst_file: result = new_process.execute(command, output_file=dst_file, expect_zero=False) return result def extract_covered_regions_from_summary_json(summary_json_file): """Returns the covered regions given a coverage summary json file.""" covered_regions = [] try: coverage_info = get_coverage_infomation(summary_json_file) functions_data = coverage_info['data'][0]['functions'] # The fourth number in the region-list indicates if the region # is hit. hit_index = 4 # The last number in the region-list indicates what type of the # region it is; 'code_region' is used to obtain various code # coverage statistic and is represented by number 0. type_index = -1 # The number of index 5 represents the file number. file_index = 5 for function_data in functions_data: for region in function_data['regions']: if region[hit_index] != 0 and region[type_index] == 0: covered_regions.append(region[:hit_index] + region[file_index:]) except Exception: # pylint: disable=broad-except logger.error('Coverage summary json file defective or missing.') return covered_regions
from collections.abc import Iterable, MutableSequence, Mapping from enum import Enum from pathlib import Path from numbers import Real, Integral from xml.etree import ElementTree as ET from math import ceil import openmc.checkvalue as cv from . import VolumeCalculation, Source, RegularMesh from ._xml import clean_indentation, get_text, reorder_attributes class RunMode(Enum): EIGENVALUE = 'eigenvalue' FIXED_SOURCE = 'fixed source' PLOT = 'plot' VOLUME = 'volume' PARTICLE_RESTART = 'particle restart' _RES_SCAT_METHODS = ['dbrc', 'rvs'] class Settings: """Settings used for an OpenMC simulation. Attributes ---------- batches : int Number of batches to simulate confidence_intervals : bool If True, uncertainties on tally results will be reported as the half-width of the 95% two-sided confidence interval. If False, uncertainties on tally results will be reported as the sample standard deviation. create_fission_neutrons : bool Indicate whether fission neutrons should be created or not. cutoff : dict Dictionary defining weight cutoff and energy cutoff. The dictionary may have six keys, 'weight', 'weight_avg', 'energy_neutron', 'energy_photon', 'energy_electron', and 'energy_positron'. Value for 'weight' should be a float indicating weight cutoff below which particle undergo Russian roulette. Value for 'weight_avg' should be a float indicating weight assigned to particles that are not killed after Russian roulette. Value of energy should be a float indicating energy in eV below which particle type will be killed. dagmc : bool Indicate that a CAD-based DAGMC geometry will be used. delayed_photon_scaling : bool Indicate whether to scale the fission photon yield by (EGP + EGD)/EGP where EGP is the energy release of prompt photons and EGD is the energy release of delayed photons. .. versionadded:: 0.12 electron_treatment : {'led', 'ttb'} Whether to deposit all energy from electrons locally ('led') or create secondary bremsstrahlung photons ('ttb'). energy_mode : {'continuous-energy', 'multi-group'} Set whether the calculation should be continuous-energy or multi-group. entropy_mesh : openmc.RegularMesh Mesh to be used to calculate Shannon entropy. If the mesh dimensions are not specified, OpenMC assigns a mesh such that 20 source sites per mesh cell are to be expected on average. event_based : bool Indicate whether to use event-based parallelism instead of the default history-based parallelism. .. versionadded:: 0.12 generations_per_batch : int Number of generations per batch max_lost_particles : int Maximum number of lost particles .. versionadded:: 0.12 rel_max_lost_particles : int Maximum number of lost particles, relative to the total number of particles .. versionadded:: 0.12 inactive : int Number of inactive batches keff_trigger : dict Dictionary defining a trigger on eigenvalue. The dictionary must have two keys, 'type' and 'threshold'. Acceptable values corresponding to type are 'variance', 'std_dev', and 'rel_err'. The threshold value should be a float indicating the variance, standard deviation, or relative error used. log_grid_bins : int Number of bins for logarithmic energy grid search material_cell_offsets : bool Generate an "offset table" for material cells by default. These tables are necessary when a particular instance of a cell needs to be tallied. .. versionadded:: 0.12 max_particles_in_flight : int Number of neutrons to run concurrently when using event-based parallelism. .. versionadded:: 0.12 max_order : None or int Maximum scattering order to apply globally when in multi-group mode. no_reduce : bool Indicate that all user-defined and global tallies should not be reduced across processes in a parallel calculation. output : dict Dictionary indicating what files to output. Acceptable keys are: :path: String indicating a directory where output files should be written :summary: Whether the 'summary.h5' file should be written (bool) :tallies: Whether the 'tallies.out' file should be written (bool) particles : int Number of particles per generation photon_transport : bool Whether to use photon transport. ptables : bool Determine whether probability tables are used. resonance_scattering : dict Settings for resonance elastic scattering. Accepted keys are 'enable' (bool), 'method' (str), 'energy_min' (float), 'energy_max' (float), and 'nuclides' (list). The 'method' can be set to 'dbrc' (Doppler broadening rejection correction) or 'rvs' (relative velocity sampling). If not specified, 'rvs' is the default method. The 'energy_min' and 'energy_max' values indicate the minimum and maximum energies above and below which the resonance elastic scattering method is to be applied. The 'nuclides' list indicates what nuclides the method should be applied to. In its absence, the method will be applied to all nuclides with 0 K elastic scattering data present. run_mode : {'eigenvalue', 'fixed source', 'plot', 'volume', 'particle restart'} The type of calculation to perform (default is 'eigenvalue') seed : int Seed for the linear congruential pseudorandom number generator source : Iterable of openmc.Source Distribution of source sites in space, angle, and energy sourcepoint : dict Options for writing source points. Acceptable keys are: :batches: list of batches at which to write source :overwrite: bool indicating whether to overwrite :separate: bool indicating whether the source should be written as a separate file :write: bool indicating whether or not to write the source statepoint : dict Options for writing state points. Acceptable keys are: :batches: list of batches at which to write source survival_biasing : bool Indicate whether survival biasing is to be used tabular_legendre : dict Determines if a multi-group scattering moment kernel expanded via Legendre polynomials is to be converted to a tabular distribution or not. Accepted keys are 'enable' and 'num_points'. The value for 'enable' is a bool stating whether the conversion to tabular is performed; the value for 'num_points' sets the number of points to use in the tabular distribution, should 'enable' be True. temperature : dict Defines a default temperature and method for treating intermediate temperatures at which nuclear data doesn't exist. Accepted keys are 'default', 'method', 'range', 'tolerance', and 'multipole'. The value for 'default' should be a float representing the default temperature in Kelvin. The value for 'method' should be 'nearest' or 'interpolation'. If the method is 'nearest', 'tolerance' indicates a range of temperature within which cross sections may be used. The value for 'range' should be a pair a minimum and maximum temperatures which are used to indicate that cross sections be loaded at all temperatures within the range. 'multipole' is a boolean indicating whether or not the windowed multipole method should be used to evaluate resolved resonance cross sections. trace : tuple or list Show detailed information about a single particle, indicated by three integers: the batch number, generation number, and particle number track : tuple or list Specify particles for which track files should be written. Each particle is identified by a triplet with the batch number, generation number, and particle number. trigger_active : bool Indicate whether tally triggers are used trigger_batch_interval : int Number of batches in between convergence checks trigger_max_batches : int Maximum number of batches simulated. If this is set, the number of batches specified via ``batches`` is interpreted as the minimum number of batches ufs_mesh : openmc.RegularMesh Mesh to be used for redistributing source sites via the uniform fision site (UFS) method. verbosity : int Verbosity during simulation between 1 and 10. Verbosity levels are described in :ref:`verbosity`. volume_calculations : VolumeCalculation or iterable of VolumeCalculation Stochastic volume calculation specifications """ def __init__(self): self._run_mode = RunMode.EIGENVALUE self._batches = None self._generations_per_batch = None self._inactive = None self._max_lost_particles = None self._rel_max_lost_particles = None self._particles = None self._keff_trigger = None # Energy mode subelement self._energy_mode = None self._max_order = None # Source subelement self._source = cv.CheckedList(Source, 'source distributions') self._confidence_intervals = None self._electron_treatment = None self._photon_transport = None self._ptables = None self._seed = None self._survival_biasing = None # Shannon entropy mesh self._entropy_mesh = None # Trigger subelement self._trigger_active = None self._trigger_max_batches = None self._trigger_batch_interval = None self._output = None # Output options self._statepoint = {} self._sourcepoint = {} self._no_reduce = None self._verbosity = None self._trace = None self._track = None self._tabular_legendre = {} self._temperature = {} # Cutoff subelement self._cutoff = None # Uniform fission source subelement self._ufs_mesh = None self._resonance_scattering = {} self._volume_calculations = cv.CheckedList( VolumeCalculation, 'volume calculations') self._create_fission_neutrons = None self._delayed_photon_scaling = None self._material_cell_offsets = None self._log_grid_bins = None self._dagmc = False self._event_based = None self._max_particles_in_flight = None @property def run_mode(self): return self._run_mode.value @property def batches(self): return self._batches @property def generations_per_batch(self): return self._generations_per_batch @property def inactive(self): return self._inactive @property def max_lost_particles(self): return self._max_lost_particles @property def rel_max_lost_particles(self): return self._rel_max_lost_particles @property def particles(self): return self._particles @property def keff_trigger(self): return self._keff_trigger @property def energy_mode(self): return self._energy_mode @property def max_order(self): return self._max_order @property def source(self): return self._source @property def confidence_intervals(self): return self._confidence_intervals @property def electron_treatment(self): return self._electron_treatment @property def ptables(self): return self._ptables @property def photon_transport(self): return self._photon_transport @property def seed(self): return self._seed @property def survival_biasing(self): return self._survival_biasing @property def entropy_mesh(self): return self._entropy_mesh @property def trigger_active(self): return self._trigger_active @property def trigger_max_batches(self): return self._trigger_max_batches @property def trigger_batch_interval(self): return self._trigger_batch_interval @property def output(self): return self._output @property def sourcepoint(self): return self._sourcepoint @property def statepoint(self): return self._statepoint @property def no_reduce(self): return self._no_reduce @property def verbosity(self): return self._verbosity @property def tabular_legendre(self): return self._tabular_legendre @property def temperature(self): return self._temperature @property def trace(self): return self._trace @property def track(self): return self._track @property def cutoff(self): return self._cutoff @property def ufs_mesh(self): return self._ufs_mesh @property def resonance_scattering(self): return self._resonance_scattering @property def volume_calculations(self): return self._volume_calculations @property def create_fission_neutrons(self): return self._create_fission_neutrons @property def delayed_photon_scaling(self): return self._delayed_photon_scaling @property def material_cell_offsets(self): return self._material_cell_offsets @property def log_grid_bins(self): return self._log_grid_bins @property def dagmc(self): return self._dagmc @property def event_based(self): return self._event_based @property def max_particles_in_flight(self): return self._max_particles_in_flight @run_mode.setter def run_mode(self, run_mode): cv.check_value('run mode', run_mode, {x.value for x in RunMode}) for mode in RunMode: if mode.value == run_mode: self._run_mode = mode @batches.setter def batches(self, batches): cv.check_type('batches', batches, Integral) cv.check_greater_than('batches', batches, 0) self._batches = batches @generations_per_batch.setter def generations_per_batch(self, generations_per_batch): cv.check_type('generations per patch', generations_per_batch, Integral) cv.check_greater_than('generations per batch', generations_per_batch, 0) self._generations_per_batch = generations_per_batch @inactive.setter def inactive(self, inactive): cv.check_type('inactive batches', inactive, Integral) cv.check_greater_than('inactive batches', inactive, 0, True) self._inactive = inactive @max_lost_particles.setter def max_lost_particles(self, max_lost_particles): cv.check_type('max_lost_particles', max_lost_particles, Integral) cv.check_greater_than('max_lost_particles', max_lost_particles, 0) self._max_lost_particles = max_lost_particles @rel_max_lost_particles.setter def rel_max_lost_particles(self, rel_max_lost_particles): cv.check_type('rel_max_lost_particles', rel_max_lost_particles, Real) cv.check_greater_than('rel_max_lost_particles', rel_max_lost_particles, 0) cv.check_less_than('rel_max_lost_particles', rel_max_lost_particles, 1) self._rel_max_lost_particles = rel_max_lost_particles @particles.setter def particles(self, particles): cv.check_type('particles', particles, Integral) cv.check_greater_than('particles', particles, 0) self._particles = particles @keff_trigger.setter def keff_trigger(self, keff_trigger): if not isinstance(keff_trigger, dict): msg = 'Unable to set a trigger on keff from "{0}" which ' \ 'is not a Python dictionary'.format(keff_trigger) raise ValueError(msg) elif 'type' not in keff_trigger: msg = 'Unable to set a trigger on keff from "{0}" which ' \ 'does not have a "type" key'.format(keff_trigger) raise ValueError(msg) elif keff_trigger['type'] not in ['variance', 'std_dev', 'rel_err']: msg = 'Unable to set a trigger on keff with ' \ 'type "{0}"'.format(keff_trigger['type']) raise ValueError(msg) elif 'threshold' not in keff_trigger: msg = 'Unable to set a trigger on keff from "{0}" which ' \ 'does not have a "threshold" key'.format(keff_trigger) raise ValueError(msg) elif not isinstance(keff_trigger['threshold'], Real): msg = 'Unable to set a trigger on keff with ' \ 'threshold "{0}"'.format(keff_trigger['threshold']) raise ValueError(msg) self._keff_trigger = keff_trigger @energy_mode.setter def energy_mode(self, energy_mode): cv.check_value('energy mode', energy_mode, ['continuous-energy', 'multi-group']) self._energy_mode = energy_mode @max_order.setter def max_order(self, max_order): if max_order is not None: cv.check_type('maximum scattering order', max_order, Integral) cv.check_greater_than('maximum scattering order', max_order, 0, True) self._max_order = max_order @source.setter def source(self, source): if not isinstance(source, MutableSequence): source = [source] self._source = cv.CheckedList(Source, 'source distributions', source) @output.setter def output(self, output): cv.check_type('output', output, Mapping) for key, value in output.items(): cv.check_value('output key', key, ('summary', 'tallies', 'path')) if key in ('summary', 'tallies'): cv.check_type("output['{}']".format(key), value, bool) else: cv.check_type("output['path']", value, str) self._output = output @verbosity.setter def verbosity(self, verbosity): cv.check_type('verbosity', verbosity, Integral) cv.check_greater_than('verbosity', verbosity, 1, True) cv.check_less_than('verbosity', verbosity, 10, True) self._verbosity = verbosity @sourcepoint.setter def sourcepoint(self, sourcepoint): cv.check_type('sourcepoint options', sourcepoint, Mapping) for key, value in sourcepoint.items(): if key == 'batches': cv.check_type('sourcepoint batches', value, Iterable, Integral) for batch in value: cv.check_greater_than('sourcepoint batch', batch, 0) elif key == 'separate': cv.check_type('sourcepoint separate', value, bool) elif key == 'write': cv.check_type('sourcepoint write', value, bool) elif key == 'overwrite': cv.check_type('sourcepoint overwrite', value, bool) else: raise ValueError("Unknown key '{}' encountered when setting " "sourcepoint options.".format(key)) self._sourcepoint = sourcepoint @statepoint.setter def statepoint(self, statepoint): cv.check_type('statepoint options', statepoint, Mapping) for key, value in statepoint.items(): if key == 'batches': cv.check_type('statepoint batches', value, Iterable, Integral) for batch in value: cv.check_greater_than('statepoint batch', batch, 0) else: raise ValueError("Unknown key '{}' encountered when setting " "statepoint options.".format(key)) self._statepoint = statepoint @confidence_intervals.setter def confidence_intervals(self, confidence_intervals): cv.check_type('confidence interval', confidence_intervals, bool) self._confidence_intervals = confidence_intervals @electron_treatment.setter def electron_treatment(self, electron_treatment): cv.check_value('electron treatment', electron_treatment, ['led', 'ttb']) self._electron_treatment = electron_treatment @photon_transport.setter def photon_transport(self, photon_transport): cv.check_type('photon transport', photon_transport, bool) self._photon_transport = photon_transport @dagmc.setter def dagmc(self, dagmc): cv.check_type('dagmc geometry', dagmc, bool) self._dagmc = dagmc @ptables.setter def ptables(self, ptables): cv.check_type('probability tables', ptables, bool) self._ptables = ptables @seed.setter def seed(self, seed): cv.check_type('random number generator seed', seed, Integral) cv.check_greater_than('random number generator seed', seed, 0) self._seed = seed @survival_biasing.setter def survival_biasing(self, survival_biasing): cv.check_type('survival biasing', survival_biasing, bool) self._survival_biasing = survival_biasing @cutoff.setter def cutoff(self, cutoff): if not isinstance(cutoff, Mapping): msg = 'Unable to set cutoff from "{0}" which is not a '\ ' Python dictionary'.format(cutoff) raise ValueError(msg) for key in cutoff: if key == 'weight': cv.check_type('weight cutoff', cutoff[key], Real) cv.check_greater_than('weight cutoff', cutoff[key], 0.0) elif key == 'weight_avg': cv.check_type('average survival weight', cutoff[key], Real) cv.check_greater_than('average survival weight', cutoff[key], 0.0) elif key in ['energy_neutron', 'energy_photon', 'energy_electron', 'energy_positron']: cv.check_type('energy cutoff', cutoff[key], Real) cv.check_greater_than('energy cutoff', cutoff[key], 0.0) else: msg = 'Unable to set cutoff to "{0}" which is unsupported by '\ 'OpenMC'.format(key) self._cutoff = cutoff @entropy_mesh.setter def entropy_mesh(self, entropy): cv.check_type('entropy mesh', entropy, RegularMesh) self._entropy_mesh = entropy @trigger_active.setter def trigger_active(self, trigger_active): cv.check_type('trigger active', trigger_active, bool) self._trigger_active = trigger_active @trigger_max_batches.setter def trigger_max_batches(self, trigger_max_batches): cv.check_type('trigger maximum batches', trigger_max_batches, Integral) cv.check_greater_than('trigger maximum batches', trigger_max_batches, 0) self._trigger_max_batches = trigger_max_batches @trigger_batch_interval.setter def trigger_batch_interval(self, trigger_batch_interval): cv.check_type('trigger batch interval', trigger_batch_interval, Integral) cv.check_greater_than('trigger batch interval', trigger_batch_interval, 0) self._trigger_batch_interval = trigger_batch_interval @no_reduce.setter def no_reduce(self, no_reduce): cv.check_type('no reduction option', no_reduce, bool) self._no_reduce = no_reduce @tabular_legendre.setter def tabular_legendre(self, tabular_legendre): cv.check_type('tabular_legendre settings', tabular_legendre, Mapping) for key, value in tabular_legendre.items(): cv.check_value('tabular_legendre key', key, ['enable', 'num_points']) if key == 'enable': cv.check_type('enable tabular_legendre', value, bool) elif key == 'num_points': cv.check_type('num_points tabular_legendre', value, Integral) cv.check_greater_than('num_points tabular_legendre', value, 0) self._tabular_legendre = tabular_legendre @temperature.setter def temperature(self, temperature): cv.check_type('temperature settings', temperature, Mapping) for key, value in temperature.items(): cv.check_value('temperature key', key, ['default', 'method', 'tolerance', 'multipole', 'range']) if key == 'default': cv.check_type('default temperature', value, Real) elif key == 'method': cv.check_value('temperature method', value, ['nearest', 'interpolation']) elif key == 'tolerance': cv.check_type('temperature tolerance', value, Real) elif key == 'multipole': cv.check_type('temperature multipole', value, bool) elif key == 'range': cv.check_length('temperature range', value, 2) for T in value: cv.check_type('temperature', T, Real) self._temperature = temperature @trace.setter def trace(self, trace): cv.check_type('trace', trace, Iterable, Integral) cv.check_length('trace', trace, 3) cv.check_greater_than('trace batch', trace[0], 0) cv.check_greater_than('trace generation', trace[1], 0) cv.check_greater_than('trace particle', trace[2], 0) self._trace = trace @track.setter def track(self, track): cv.check_type('track', track, Iterable, Integral) if len(track) % 3 != 0: msg = 'Unable to set the track to "{0}" since its length is ' \ 'not a multiple of 3'.format(track) raise ValueError(msg) for t in zip(track[::3], track[1::3], track[2::3]): cv.check_greater_than('track batch', t[0], 0) cv.check_greater_than('track generation', t[0], 0) cv.check_greater_than('track particle', t[0], 0) self._track = track @ufs_mesh.setter def ufs_mesh(self, ufs_mesh): cv.check_type('UFS mesh', ufs_mesh, RegularMesh) cv.check_length('UFS mesh dimension', ufs_mesh.dimension, 3) cv.check_length('UFS mesh lower-left corner', ufs_mesh.lower_left, 3) cv.check_length('UFS mesh upper-right corner', ufs_mesh.upper_right, 3) self._ufs_mesh = ufs_mesh @resonance_scattering.setter def resonance_scattering(self, res): cv.check_type('resonance scattering settings', res, Mapping) keys = ('enable', 'method', 'energy_min', 'energy_max', 'nuclides') for key, value in res.items(): cv.check_value('resonance scattering dictionary key', key, keys) if key == 'enable': cv.check_type('resonance scattering enable', value, bool) elif key == 'method': cv.check_value('resonance scattering method', value, _RES_SCAT_METHODS) elif key == 'energy_min': name = 'resonance scattering minimum energy' cv.check_type(name, value, Real) cv.check_greater_than(name, value, 0) elif key == 'energy_max': name = 'resonance scattering minimum energy' cv.check_type(name, value, Real) cv.check_greater_than(name, value, 0) elif key == 'nuclides': cv.check_type('resonance scattering nuclides', value, Iterable, str) self._resonance_scattering = res @volume_calculations.setter def volume_calculations(self, vol_calcs): if not isinstance(vol_calcs, MutableSequence): vol_calcs = [vol_calcs] self._volume_calculations = cv.CheckedList( VolumeCalculation, 'stochastic volume calculations', vol_calcs) @create_fission_neutrons.setter def create_fission_neutrons(self, create_fission_neutrons): cv.check_type('Whether create fission neutrons', create_fission_neutrons, bool) self._create_fission_neutrons = create_fission_neutrons @delayed_photon_scaling.setter def delayed_photon_scaling(self, value): cv.check_type('delayed photon scaling', value, bool) self._delayed_photon_scaling = value @event_based.setter def event_based(self, value): cv.check_type('event based', value, bool) self._event_based = value @max_particles_in_flight.setter def max_particles_in_flight(self, value): cv.check_type('max particles in flight', value, Integral) cv.check_greater_than('max particles in flight', value, 0) self._max_particles_in_flight = value @material_cell_offsets.setter def material_cell_offsets(self, value): cv.check_type('material cell offsets', value, bool) self._material_cell_offsets = value @log_grid_bins.setter def log_grid_bins(self, log_grid_bins): cv.check_type('log grid bins', log_grid_bins, Real) cv.check_greater_than('log grid bins', log_grid_bins, 0) self._log_grid_bins = log_grid_bins def _create_run_mode_subelement(self, root): elem = ET.SubElement(root, "run_mode") elem.text = self._run_mode.value def _create_batches_subelement(self, root): if self._batches is not None: element = ET.SubElement(root, "batches") element.text = str(self._batches) def _create_generations_per_batch_subelement(self, root): if self._generations_per_batch is not None: element = ET.SubElement(root, "generations_per_batch") element.text = str(self._generations_per_batch) def _create_inactive_subelement(self, root): if self._inactive is not None: element = ET.SubElement(root, "inactive") element.text = str(self._inactive) def _create_max_lost_particles_subelement(self, root): if self._max_lost_particles is not None: element = ET.SubElement(root, "max_lost_particles") element.text = str(self._max_lost_particles) def _create_rel_max_lost_particles_subelement(self, root): if self._rel_max_lost_particles is not None: element = ET.SubElement(root, "rel_max_lost_particles") element.text = str(self._rel_max_lost_particles) def _create_particles_subelement(self, root): if self._particles is not None: element = ET.SubElement(root, "particles") element.text = str(self._particles) def _create_keff_trigger_subelement(self, root): if self._keff_trigger is not None: element = ET.SubElement(root, "keff_trigger") for key, value in sorted(self._keff_trigger.items()): subelement = ET.SubElement(element, key) subelement.text = str(value).lower() def _create_energy_mode_subelement(self, root): if self._energy_mode is not None: element = ET.SubElement(root, "energy_mode") element.text = str(self._energy_mode) def _create_max_order_subelement(self, root): if self._max_order is not None: element = ET.SubElement(root, "max_order") element.text = str(self._max_order) def _create_source_subelement(self, root): for source in self.source: root.append(source.to_xml_element()) def _create_volume_calcs_subelement(self, root): for calc in self.volume_calculations: root.append(calc.to_xml_element()) def _create_output_subelement(self, root): if self._output is not None: element = ET.SubElement(root, "output") for key, value in sorted(self._output.items()): subelement = ET.SubElement(element, key) if key in ('summary', 'tallies'): subelement.text = str(value).lower() else: subelement.text = value def _create_verbosity_subelement(self, root): if self._verbosity is not None: element = ET.SubElement(root, "verbosity") element.text = str(self._verbosity) def _create_statepoint_subelement(self, root): if self._statepoint: element = ET.SubElement(root, "state_point") if 'batches' in self._statepoint: subelement = ET.SubElement(element, "batches") subelement.text = ' '.join( str(x) for x in self._statepoint['batches']) def _create_sourcepoint_subelement(self, root): if self._sourcepoint: element = ET.SubElement(root, "source_point") if 'batches' in self._sourcepoint: subelement = ET.SubElement(element, "batches") subelement.text = ' '.join( str(x) for x in self._sourcepoint['batches']) if 'separate' in self._sourcepoint: subelement = ET.SubElement(element, "separate") subelement.text = str(self._sourcepoint['separate']).lower() if 'write' in self._sourcepoint: subelement = ET.SubElement(element, "write") subelement.text = str(self._sourcepoint['write']).lower() # Overwrite latest subelement if 'overwrite' in self._sourcepoint: subelement = ET.SubElement(element, "overwrite_latest") subelement.text = str(self._sourcepoint['overwrite']).lower() def _create_confidence_intervals(self, root): if self._confidence_intervals is not None: element = ET.SubElement(root, "confidence_intervals") element.text = str(self._confidence_intervals).lower() def _create_electron_treatment_subelement(self, root): if self._electron_treatment is not None: element = ET.SubElement(root, "electron_treatment") element.text = str(self._electron_treatment) def _create_photon_transport_subelement(self, root): if self._photon_transport is not None: element = ET.SubElement(root, "photon_transport") element.text = str(self._photon_transport).lower() def _create_ptables_subelement(self, root): if self._ptables is not None: element = ET.SubElement(root, "ptables") element.text = str(self._ptables).lower() def _create_seed_subelement(self, root): if self._seed is not None: element = ET.SubElement(root, "seed") element.text = str(self._seed) def _create_survival_biasing_subelement(self, root): if self._survival_biasing is not None: element = ET.SubElement(root, "survival_biasing") element.text = str(self._survival_biasing).lower() def _create_cutoff_subelement(self, root): if self._cutoff is not None: element = ET.SubElement(root, "cutoff") for key, value in self._cutoff.items(): subelement = ET.SubElement(element, key) subelement.text = str(value) def _create_entropy_mesh_subelement(self, root): if self.entropy_mesh is not None: # use default heuristic for entropy mesh if not set by user if self.entropy_mesh.dimension is None: if self.particles is None: raise RuntimeError("Number of particles must be set in order to " \ "use entropy mesh dimension heuristic") else: n = ceil((self.particles / 20.0)**(1.0 / 3.0)) d = len(self.entropy_mesh.lower_left) self.entropy_mesh.dimension = (n,)*d # See if a <mesh> element already exists -- if not, add it path = "./mesh[@id='{}']".format(self.entropy_mesh.id) if root.find(path) is None: root.append(self.entropy_mesh.to_xml_element()) subelement = ET.SubElement(root, "entropy_mesh") subelement.text = str(self.entropy_mesh.id) def _create_trigger_subelement(self, root): if self._trigger_active is not None: trigger_element = ET.SubElement(root, "trigger") element = ET.SubElement(trigger_element, "active") element.text = str(self._trigger_active).lower() if self._trigger_max_batches is not None: element = ET.SubElement(trigger_element, "max_batches") element.text = str(self._trigger_max_batches) if self._trigger_batch_interval is not None: element = ET.SubElement(trigger_element, "batch_interval") element.text = str(self._trigger_batch_interval) def _create_no_reduce_subelement(self, root): if self._no_reduce is not None: element = ET.SubElement(root, "no_reduce") element.text = str(self._no_reduce).lower() def _create_tabular_legendre_subelements(self, root): if self.tabular_legendre: element = ET.SubElement(root, "tabular_legendre") subelement = ET.SubElement(element, "enable") subelement.text = str(self._tabular_legendre['enable']).lower() if 'num_points' in self._tabular_legendre: subelement = ET.SubElement(element, "num_points") subelement.text = str(self._tabular_legendre['num_points']) def _create_temperature_subelements(self, root): if self.temperature: for key, value in sorted(self.temperature.items()): element = ET.SubElement(root, "temperature_{}".format(key)) if isinstance(value, bool): element.text = str(value).lower() elif key == 'range': element.text = ' '.join(str(T) for T in value) else: element.text = str(value) def _create_trace_subelement(self, root): if self._trace is not None: element = ET.SubElement(root, "trace") element.text = ' '.join(map(str, self._trace)) def _create_track_subelement(self, root): if self._track is not None: element = ET.SubElement(root, "track") element.text = ' '.join(map(str, self._track)) def _create_ufs_mesh_subelement(self, root): if self.ufs_mesh is not None: # See if a <mesh> element already exists -- if not, add it path = "./mesh[@id='{}']".format(self.ufs_mesh.id) if root.find(path) is None: root.append(self.ufs_mesh.to_xml_element()) subelement = ET.SubElement(root, "ufs_mesh") subelement.text = str(self.ufs_mesh.id) def _create_resonance_scattering_subelement(self, root): res = self.resonance_scattering if res: elem = ET.SubElement(root, 'resonance_scattering') if 'enable' in res: subelem = ET.SubElement(elem, 'enable') subelem.text = str(res['enable']).lower() if 'method' in res: subelem = ET.SubElement(elem, 'method') subelem.text = res['method'] if 'energy_min' in res: subelem = ET.SubElement(elem, 'energy_min') subelem.text = str(res['energy_min']) if 'energy_max' in res: subelem = ET.SubElement(elem, 'energy_max') subelem.text = str(res['energy_max']) if 'nuclides' in res: subelem = ET.SubElement(elem, 'nuclides') subelem.text = ' '.join(res['nuclides']) def _create_create_fission_neutrons_subelement(self, root): if self._create_fission_neutrons is not None: elem = ET.SubElement(root, "create_fission_neutrons") elem.text = str(self._create_fission_neutrons).lower() def _create_delayed_photon_scaling_subelement(self, root): if self._delayed_photon_scaling is not None: elem = ET.SubElement(root, "delayed_photon_scaling") elem.text = str(self._delayed_photon_scaling).lower() def _create_event_based_subelement(self, root): if self._event_based is not None: elem = ET.SubElement(root, "event_based") elem.text = str(self._event_based).lower() def _create_max_particles_in_flight_subelement(self, root): if self._max_particles_in_flight is not None: elem = ET.SubElement(root, "max_particles_in_flight") elem.text = str(self._max_particles_in_flight).lower() def _create_material_cell_offsets_subelement(self, root): if self._material_cell_offsets is not None: elem = ET.SubElement(root, "material_cell_offsets") elem.text = str(self._material_cell_offsets).lower() def _create_log_grid_bins_subelement(self, root): if self._log_grid_bins is not None: elem = ET.SubElement(root, "log_grid_bins") elem.text = str(self._log_grid_bins) def _create_dagmc_subelement(self, root): if self._dagmc: elem = ET.SubElement(root, "dagmc") elem.text = str(self._dagmc).lower() def _eigenvalue_from_xml_element(self, root): elem = root.find('eigenvalue') if elem is not None: self._run_mode_from_xml_element(elem) self._particles_from_xml_element(elem) self._batches_from_xml_element(elem) self._inactive_from_xml_element(elem) self._max_lost_particles_from_xml_element(elem) self._rel_max_lost_particles_from_xml_element(elem) self._generations_per_batch_from_xml_element(elem) def _run_mode_from_xml_element(self, root): text = get_text(root, 'run_mode') if text is not None: self.run_mode = text def _particles_from_xml_element(self, root): text = get_text(root, 'particles') if text is not None: self.particles = int(text) def _batches_from_xml_element(self, root): text = get_text(root, 'batches') if text is not None: self.batches = int(text) def _inactive_from_xml_element(self, root): text = get_text(root, 'inactive') if text is not None: self.inactive = int(text) def _max_lost_particles_from_xml_element(self, root): text = get_text(root, 'max_lost_particles') if text is not None: self.max_lost_particles = int(text) def _rel_max_lost_particles_from_xml_element(self, root): text = get_text(root, 'rel_max_lost_particles') if text is not None: self.rel_max_lost_particles = float(text) def _generations_per_batch_from_xml_element(self, root): text = get_text(root, 'generations_per_batch') if text is not None: self.generations_per_batch = int(text) def _keff_trigger_from_xml_element(self, root): elem = root.find('keff_trigger') if elem is not None: trigger = get_text(elem, 'type') threshold = float(get_text(elem, 'threshold')) self.keff_trigger = {'type': trigger, 'threshold': threshold} def _source_from_xml_element(self, root): for elem in root.findall('source'): self.source.append(Source.from_xml_element(elem)) def _output_from_xml_element(self, root): elem = root.find('output') if elem is not None: self.output = {} for key in ('summary', 'tallies', 'path'): value = get_text(elem, key) if value is not None: if key in ('summary', 'tallies'): value = value in ('true', '1') self.output[key] = value def _statepoint_from_xml_element(self, root): elem = root.find('state_point') if elem is not None: text = get_text(elem, 'batches') if text is not None: self.statepoint['batches'] = [int(x) for x in text.split()] def _sourcepoint_from_xml_element(self, root): elem = root.find('source_point') if elem is not None: for key in ('separate', 'write', 'overwrite_latest', 'batches'): value = get_text(elem, key) if value is not None: if key in ('separate', 'write'): value = value in ('true', '1') elif key == 'overwrite_latest': value = value in ('true', '1') key = 'overwrite' else: value = [int(x) for x in value.split()] self.sourcepoint[key] = value def _confidence_intervals_from_xml_element(self, root): text = get_text(root, 'confidence_intervals') if text is not None: self.confidence_intervals = text in ('true', '1') def _electron_treatment_from_xml_element(self, root): text = get_text(root, 'electron_treatment') if text is not None: self.electron_treatment = text def _energy_mode_from_xml_element(self, root): text = get_text(root, 'energy_mode') if text is not None: self.energy_mode = text def _max_order_from_xml_element(self, root): text = get_text(root, 'max_order') if text is not None: self.max_order = int(text) def _photon_transport_from_xml_element(self, root): text = get_text(root, 'photon_transport') if text is not None: self.photon_transport = text in ('true', '1') def _ptables_from_xml_element(self, root): text = get_text(root, 'ptables') if text is not None: self.ptables = text in ('true', '1') def _seed_from_xml_element(self, root): text = get_text(root, 'seed') if text is not None: self.seed = int(text) def _survival_biasing_from_xml_element(self, root): text = get_text(root, 'survival_biasing') if text is not None: self.survival_biasing = text in ('true', '1') def _cutoff_from_xml_element(self, root): elem = root.find('cutoff') if elem is not None: self.cutoff = {} for key in ('energy_neutron', 'energy_photon', 'energy_electron', 'energy_positron', 'weight', 'weight_avg'): value = get_text(elem, key) if value is not None: self.cutoff[key] = float(value) def _entropy_mesh_from_xml_element(self, root): text = get_text(root, 'entropy_mesh') if text is not None: path = "./mesh[@id='{}']".format(int(text)) elem = root.find(path) if elem is not None: self.entropy_mesh = RegularMesh.from_xml_element(elem) def _trigger_from_xml_element(self, root): elem = root.find('trigger') if elem is not None: self.trigger_active = get_text(elem, 'active') in ('true', '1') text = get_text(elem, 'max_batches') if text is not None: self.trigger_max_batches = int(text) text = get_text(elem, 'batch_interval') if text is not None: self.trigger_batch_interval = int(text) def _no_reduce_from_xml_element(self, root): text = get_text(root, 'no_reduce') if text is not None: self.no_reduce = text in ('true', '1') def _verbosity_from_xml_element(self, root): text = get_text(root, 'verbosity') if text is not None: self.verbosity = int(text) def _tabular_legendre_from_xml_element(self, root): elem = root.find('tabular_legendre') if elem is not None: text = get_text(elem, 'enable') self.tabular_legendre['enable'] = text in ('true', '1') text = get_text(elem, 'num_points') if text is not None: self.tabular_legendre['num_points'] = int(text) def _temperature_from_xml_element(self, root): text = get_text(root, 'temperature_default') if text is not None: self.temperature['default'] = float(text) text = get_text(root, 'temperature_tolerance') if text is not None: self.temperature['tolerance'] = float(text) text = get_text(root, 'temperature_method') if text is not None: self.temperature['method'] = text text = get_text(root, 'temperature_range') if text is not None: self.temperature['range'] = [float(x) for x in text.split()] text = get_text(root, 'temperature_multipole') if text is not None: self.temperature['multipole'] = text in ('true', '1') def _trace_from_xml_element(self, root): text = get_text(root, 'trace') if text is not None: self.trace = [int(x) for x in text.split()] def _track_from_xml_element(self, root): text = get_text(root, 'track') if text is not None: self.track = [int(x) for x in text.split()] def _ufs_mesh_from_xml_element(self, root): text = get_text(root, 'ufs_mesh') if text is not None: path = "./mesh[@id='{}']".format(int(text)) elem = root.find(path) if elem is not None: self.ufs_mesh = RegularMesh.from_xml_element(elem) def _resonance_scattering_from_xml_element(self, root): elem = root.find('resonance_scattering') if elem is not None: keys = ('enable', 'method', 'energy_min', 'energy_max', 'nuclides') for key in keys: value = get_text(elem, key) if value is not None: if key == 'enable': value = value in ('true', '1') elif key in ('energy_min', 'energy_max'): value = float(value) elif key == 'nuclides': value = value.split() self.resonance_scattering[key] = value def _create_fission_neutrons_from_xml_element(self, root): text = get_text(root, 'create_fission_neutrons') if text is not None: self.create_fission_neutrons = text in ('true', '1') def _delayed_photon_scaling_from_xml_element(self, root): text = get_text(root, 'delayed_photon_scaling') if text is not None: self.delayed_photon_scaling = text in ('true', '1') def _event_based_from_xml_element(self, root): text = get_text(root, 'event_based') if text is not None: self.event_based = text in ('true', '1') def _max_particles_in_flight_from_xml_element(self, root): text = get_text(root, 'max_particles_in_flight') if text is not None: self.max_particles_in_flight = int(text) def _material_cell_offsets_from_xml_element(self, root): text = get_text(root, 'material_cell_offsets') if text is not None: self.material_cell_offsets = text in ('true', '1') def _log_grid_bins_from_xml_element(self, root): text = get_text(root, 'log_grid_bins') if text is not None: self.log_grid_bins = int(text) def _dagmc_from_xml_element(self, root): text = get_text(root, 'dagmc') if text is not None: self.dagmc = text in ('true', '1') def export_to_xml(self, path='settings.xml'): """Export simulation settings to an XML file. Parameters ---------- path : str Path to file to write. Defaults to 'settings.xml'. """ # Reset xml element tree root_element = ET.Element("settings") self._create_run_mode_subelement(root_element) self._create_particles_subelement(root_element) self._create_batches_subelement(root_element) self._create_inactive_subelement(root_element) self._create_max_lost_particles_subelement(root_element) self._create_rel_max_lost_particles_subelement(root_element) self._create_generations_per_batch_subelement(root_element) self._create_keff_trigger_subelement(root_element) self._create_source_subelement(root_element) self._create_output_subelement(root_element) self._create_statepoint_subelement(root_element) self._create_sourcepoint_subelement(root_element) self._create_confidence_intervals(root_element) self._create_electron_treatment_subelement(root_element) self._create_energy_mode_subelement(root_element) self._create_max_order_subelement(root_element) self._create_photon_transport_subelement(root_element) self._create_ptables_subelement(root_element) self._create_seed_subelement(root_element) self._create_survival_biasing_subelement(root_element) self._create_cutoff_subelement(root_element) self._create_entropy_mesh_subelement(root_element) self._create_trigger_subelement(root_element) self._create_no_reduce_subelement(root_element) self._create_verbosity_subelement(root_element) self._create_tabular_legendre_subelements(root_element) self._create_temperature_subelements(root_element) self._create_trace_subelement(root_element) self._create_track_subelement(root_element) self._create_ufs_mesh_subelement(root_element) self._create_resonance_scattering_subelement(root_element) self._create_volume_calcs_subelement(root_element) self._create_create_fission_neutrons_subelement(root_element) self._create_delayed_photon_scaling_subelement(root_element) self._create_event_based_subelement(root_element) self._create_max_particles_in_flight_subelement(root_element) self._create_material_cell_offsets_subelement(root_element) self._create_log_grid_bins_subelement(root_element) self._create_dagmc_subelement(root_element) # Clean the indentation in the file to be user-readable clean_indentation(root_element) # Check if path is a directory p = Path(path) if p.is_dir(): p /= 'settings.xml' # Write the XML Tree to the settings.xml file reorder_attributes(root_element) # TODO: Remove when support is Python 3.8+ tree = ET.ElementTree(root_element) tree.write(str(p), xml_declaration=True, encoding='utf-8') @classmethod def from_xml(cls, path='settings.xml'): """Generate settings from XML file Parameters ---------- path : str, optional Path to settings XML file Returns ------- openmc.Settings Settings object """ tree = ET.parse(path) root = tree.getroot() settings = cls() settings._eigenvalue_from_xml_element(root) settings._run_mode_from_xml_element(root) settings._particles_from_xml_element(root) settings._batches_from_xml_element(root) settings._inactive_from_xml_element(root) settings._max_lost_particles_from_xml_element(root) settings._rel_max_lost_particles_from_xml_element(root) settings._generations_per_batch_from_xml_element(root) settings._keff_trigger_from_xml_element(root) settings._source_from_xml_element(root) settings._output_from_xml_element(root) settings._statepoint_from_xml_element(root) settings._sourcepoint_from_xml_element(root) settings._confidence_intervals_from_xml_element(root) settings._electron_treatment_from_xml_element(root) settings._energy_mode_from_xml_element(root) settings._max_order_from_xml_element(root) settings._photon_transport_from_xml_element(root) settings._ptables_from_xml_element(root) settings._seed_from_xml_element(root) settings._survival_biasing_from_xml_element(root) settings._cutoff_from_xml_element(root) settings._entropy_mesh_from_xml_element(root) settings._trigger_from_xml_element(root) settings._no_reduce_from_xml_element(root) settings._verbosity_from_xml_element(root) settings._tabular_legendre_from_xml_element(root) settings._temperature_from_xml_element(root) settings._trace_from_xml_element(root) settings._track_from_xml_element(root) settings._ufs_mesh_from_xml_element(root) settings._resonance_scattering_from_xml_element(root) settings._create_fission_neutrons_from_xml_element(root) settings._delayed_photon_scaling_from_xml_element(root) settings._event_based_from_xml_element(root) settings._max_particles_in_flight_from_xml_element(root) settings._material_cell_offsets_from_xml_element(root) settings._log_grid_bins_from_xml_element(root) settings._dagmc_from_xml_element(root) # TODO: Get volume calculations return settings
# encoding: utf-8 """ Test suite for pptx.parts.image module. """ from __future__ import absolute_import, print_function, unicode_literals import pytest from pptx.compat import BytesIO from pptx.package import Package from pptx.parts.image import Image, ImagePart from pptx.util import Px from ..unitutil.file import absjoin, test_file_dir from ..unitutil.mock import ( class_mock, initializer_mock, instance_mock, method_mock, property_mock ) images_pptx_path = absjoin(test_file_dir, 'with_images.pptx') test_image_path = absjoin(test_file_dir, 'python-icon.jpeg') test_eps_path = absjoin(test_file_dir, 'cdw-logo.eps') new_image_path = absjoin(test_file_dir, 'monty-truth.png') class DescribeImagePart(object): def it_can_construct_from_an_image_object(self, new_fixture): package_, image_, _init_, partname_ = new_fixture image_part = ImagePart.new(package_, image_) package_.next_image_partname.assert_called_once_with(image_.ext) _init_.assert_called_once_with( partname_, image_.content_type, image_.blob, package_, image_.filename ) assert isinstance(image_part, ImagePart) def it_provides_access_to_its_image(self, image_fixture): image_part, Image_, blob, desc, image_ = image_fixture image = image_part.image Image_.assert_called_once_with(blob, desc) assert image is image_ def it_can_scale_its_dimensions(self, scale_fixture): image_part, width, height, expected_values = scale_fixture assert image_part.scale(width, height) == expected_values def it_knows_its_pixel_dimensions(self, size_fixture): image, expected_size = size_fixture assert image._px_size == expected_size # fixtures ------------------------------------------------------- @pytest.fixture def image_fixture(self, Image_, image_): blob, filename = 'blob', 'foobar.png' image_part = ImagePart(None, None, blob, None, filename) return image_part, Image_, blob, filename, image_ @pytest.fixture def new_fixture(self, request, package_, image_, _init_): partname_ = package_.next_image_partname.return_value return package_, image_, _init_, partname_ @pytest.fixture(params=[ (None, None, Px(204), Px(204)), (1000, None, 1000, 1000), (None, 3000, 3000, 3000), (3337, 9999, 3337, 9999), ]) def scale_fixture(self, request): width, height, expected_width, expected_height = request.param with open(test_image_path, 'rb') as f: blob = f.read() image = ImagePart(None, None, blob, None) return image, width, height, (expected_width, expected_height) @pytest.fixture def size_fixture(self): with open(test_image_path, 'rb') as f: blob = f.read() image = ImagePart(None, None, blob, None) return image, (204, 204) # fixture components --------------------------------------------- @pytest.fixture def Image_(self, request, image_): return class_mock( request, 'pptx.parts.image.Image', return_value=image_ ) @pytest.fixture def image_(self, request): return instance_mock(request, Image) @pytest.fixture def _init_(self, request): return initializer_mock(request, ImagePart) @pytest.fixture def package_(self, request): return instance_mock(request, Package) class DescribeImage(object): def it_can_construct_from_a_path(self, from_path_fixture): image_file, blob, filename, image_ = from_path_fixture image = Image.from_file(image_file) Image.from_blob.assert_called_once_with(blob, filename) assert image is image_ def it_can_construct_from_a_stream(self, from_stream_fixture): image_file, blob, image_ = from_stream_fixture image = Image.from_file(image_file) Image.from_blob.assert_called_once_with(blob, None) assert image is image_ def it_can_construct_from_a_blob(self, from_blob_fixture): blob, filename = from_blob_fixture image = Image.from_blob(blob, filename) Image.__init__.assert_called_once_with(blob, filename) assert isinstance(image, Image) def it_knows_its_blob(self, blob_fixture): image, expected_value = blob_fixture assert image.blob == expected_value def it_knows_its_content_type(self, content_type_fixture): image, expected_value = content_type_fixture assert image.content_type == expected_value def it_knows_its_canonical_filename_extension(self, ext_fixture): image, expected_value = ext_fixture assert image.ext == expected_value def it_knows_its_dpi(self, dpi_fixture): image, expected_value = dpi_fixture assert image.dpi == expected_value def it_knows_its_filename(self, filename_fixture): image, expected_value = filename_fixture assert image.filename == expected_value def it_knows_its_sha1_hash(self): image = Image(b'foobar', None) assert image.sha1 == '8843d7f92416211de9ebb963ff4ce28125932878' def it_knows_its_PIL_properties_to_help(self, pil_fixture): image, size, format, dpi = pil_fixture assert image.size == size assert image._format == format assert image.dpi == dpi assert image._pil_props == (format, size, None) # fixtures ------------------------------------------------------- @pytest.fixture def blob_fixture(self): blob = b'foobar' image = Image(blob, None) return image, blob @pytest.fixture(params=[ ('BMP', 'image/bmp'), ('GIF', 'image/gif'), ('JPEG', 'image/jpeg'), ('PNG', 'image/png'), ('TIFF', 'image/tiff'), ('WMF', 'image/x-wmf') ]) def content_type_fixture(self, request, _format_): format, expected_value = request.param image = Image(None, None) _format_.return_value = format return image, expected_value @pytest.fixture(params=[ ((42, 24), (42, 24)), ((42.1, 23.6), (42, 24)), (None, (72, 72)), ((3047, 2388), (72, 72)), ('foobar', (72, 72)), ]) def dpi_fixture(self, request, _pil_props_): raw_dpi, expected_dpi = request.param image = Image(None, None) _pil_props_.return_value = (None, None, raw_dpi) return image, expected_dpi @pytest.fixture(params=[ ('BMP', 'bmp'), ('GIF', 'gif'), ('JPEG', 'jpg'), ('PNG', 'png'), ('TIFF', 'tiff'), ('WMF', 'wmf'), ]) def ext_fixture(self, request, _format_): format, expected_value = request.param image = Image(None, None) _format_.return_value = format return image, expected_value @pytest.fixture(params=['foo.bar', None]) def filename_fixture(self, request): filename = request.param image = Image(None, filename) return image, filename @pytest.fixture def from_blob_fixture(self, _init_): blob, filename = b'foobar', 'foo.png' return blob, filename @pytest.fixture def from_path_fixture(self, from_blob_, image_): image_file = test_image_path with open(test_image_path, 'rb') as f: blob = f.read() filename = 'python-icon.jpeg' from_blob_.return_value = image_ return image_file, blob, filename, image_ @pytest.fixture def from_stream_fixture(self, from_blob_, image_): with open(test_image_path, 'rb') as f: blob = f.read() image_file = BytesIO(blob) from_blob_.return_value = image_ return image_file, blob, image_ @pytest.fixture def pil_fixture(self): with open(test_image_path, 'rb') as f: blob = f.read() image = Image(blob, None) size = (204, 204) format = 'JPEG' dpi = (72, 72) return image, size, format, dpi # fixture components --------------------------------------------- @pytest.fixture def _format_(self, request): return property_mock(request, Image, '_format') @pytest.fixture def from_blob_(self, request): return method_mock(request, Image, 'from_blob') @pytest.fixture def image_(self, request): return instance_mock(request, Image) @pytest.fixture def _init_(self, request): return initializer_mock(request, Image) @pytest.fixture def _pil_props_(self, request): return property_mock(request, Image, '_pil_props')
import numpy as np llf = np.array([-240.29558272688]) nobs = np.array([ 202]) k = np.array([ 5]) k_exog = np.array([ 1]) sigma = np.array([ .79494581155191]) chi2 = np.array([ 1213.6019521322]) df_model = np.array([ 3]) k_ar = np.array([ 2]) k_ma = np.array([ 1]) params = np.array([ .72428568600554, 1.1464248419014, -.17024528879204, -.87113675466923, .63193884330392]) cov_params = np.array([ .31218565961764, -.01618380799341, .00226345462929, .01386291798401, -.0036338799176, -.01618380799341, .00705713030623, -.00395404914463, -.00685704952799, -.00018629958479, .00226345462929, -.00395404914463, .00255884492061, .00363586332269, .00039879711931, .01386291798401, -.00685704952799, .00363586332269, .00751765532203, .00008982556101, -.0036338799176, -.00018629958479, .00039879711931, .00008982556101, .00077550533053]).reshape(5,5) xb = np.array([ .72428566217422, .72428566217422, .56208884716034, .53160965442657, .45030161738396, .45229381322861, .38432359695435, .40517011284828, .36063131690025, .30754271149635, .32044330239296, .29408219456673, .27966624498367, .29743707180023, .25011941790581, .27747189998627, .24822402000427, .23426930606365, .27233305573463, .23524768650532, .26427435874939, .21787133812904, .22461311519146, .22853142023087, .24335558712482, .22953669726849, .25524401664734, .22482520341873, .26450532674789, .31863233447075, .27352628111839, .33670437335968, .25623551011086, .28701293468475, .315819054842, .3238864839077, .35844340920448, .34399557113647, .40348997712135, .39373970031738, .4022718667984, .46476069092751, .45762005448341, .46842387318611, .50536489486694, .52051961421967, .47866532206535, .50378143787384, .50863671302795, .4302790760994, .49568024277687, .44652271270752, .43774726986885, .43010330200195, .42344436049461, .44517293572426, .47460499405861, .62086409330368, .52550911903381, .77532315254211, .78466820716858, .85438597202301, .87056696414948, 1.0393311977386, .99110960960388, .85202795267105, .91560190916061, .89238166809082, .88917690515518, .72121334075928, .84221452474594, .8454754948616, .82078683376312, .95394861698151, .84718400239944, .839300096035, .91501939296722, .95743554830551, 1.0874761343002, 1.1326615810394, 1.1169674396515, 1.3300451040268, 1.4790810346603, 1.5027786493301, 1.7226468324661, 1.8395622968674, 1.5940405130386, 1.694568157196, 1.8241587877274, 1.7037791013718, 1.838702917099, 1.7334734201431, 1.4791669845581, 1.3007366657257, 1.7364456653595, 1.2694935798645, .96595168113708, 1.1405370235443, 1.1328836679459, 1.1091921329498, 1.171138882637, 1.1465038061142, 1.0319484472275, 1.055313706398, .93150246143341, 1.0844472646713, .93333613872528, .93137633800507, 1.0778160095215, .38748729228973, .77933365106583, .75266307592392, .88410103321075, .94100385904312, .91849637031555, .96046274900436, .92494148015976, .98310285806656, 1.0272513628006, 1.0762135982513, 1.0743116140366, 1.254854798317, 1.1723403930664, 1.0479376316071, 1.3550333976746, 1.2255589962006, 1.2870025634766, 1.6643482446671, 1.3312928676605, 1.0657893419266, 1.1804157495499, 1.1335761547089, 1.137326002121, 1.1235628128052, 1.1115798950195, 1.1286649703979, 1.0989991426468, 1.0626485347748, .96542054414749, 1.0419135093689, .93033194541931, .95628559589386, 1.027433514595, .98328214883804, 1.0063992738724, 1.0645687580109, .94354963302612, .95077443122864, 1.0226324796677, 1.089217543602, .97552293539047, 1.0441918373108, 1.052937746048, .86785578727722, .82579529285431, .95432937145233, .79897737503052, .68320548534393, .85365778207779, .78336101770401, .80072748661041, .9089440703392, .82500487565994, .98515397310257, .96745657920837, 1.0962044000626, 1.195325255394, 1.0824474096298, 1.2239117622375, 1.0142554044724, 1.0399018526077, .80796521902084, .7145761847496, 1.0631860494614, .86374056339264, .98086261749268, 1.0528303384781, .86123734712601, .80300676822662, .96200370788574, 1.0364016294479, .98456978797913, 1.1556725502014, 1.2025715112686, 1.0507286787033, 1.312912106514, 1.0682457685471, 2.0334177017212, 1.0775905847549, 1.2798084020615, 1.461397767067, .72960823774338, 1.2498733997345, 1.466894865036, 1.286082983017, 1.3903408050537, 1.8483582735062, 1.4685434103012, 2.3107523918152, .7711226940155, -.31598940491676, .68151205778122, 1.0212944746017]) y = np.array([np.nan, 29.704284667969, 29.712087631226, 29.881610870361, 29.820302963257, 29.992294311523, 29.934322357178, 30.155170440674, 30.200632095337, 30.117542266846, 30.24044418335, 30.274082183838, 30.319667816162, 30.507436752319, 30.470119476318, 30.657470703125, 30.68822479248, 30.714269638062, 30.962333679199, 30.985248565674, 31.204275131226, 31.16787147522, 31.244613647461, 31.348531723022, 31.523355484009, 31.609535217285, 31.835243225098, 31.874824523926, 32.144504547119, 32.5986328125, 32.723526000977, 33.186702728271, 33.156238555908, 33.387012481689, 33.7158203125, 34.023887634277, 34.458442687988, 34.743995666504, 35.303489685059, 35.693740844727, 36.102272033691, 36.764759063721, 37.257617950439, 37.768424987793, 38.405364990234, 39.020519256592, 39.378665924072, 39.903781890869, 40.408638000488, 40.530277252197, 41.095680236816, 41.346523284912, 41.637748718262, 41.930103302002, 42.223442077637, 42.645172119141, 43.174606323242, 44.320865631104, 44.725509643555, 46.37532043457, 47.584667205811, 48.954383850098, 50.170566558838, 52.039329528809, 53.291107177734, 53.852027893066, 54.915603637695, 55.792385101318, 56.6891746521, 56.821212768555, 57.842212677002, 58.745475769043, 59.5207862854, 60.953948974609, 61.6471824646, 62.439296722412, 63.615020751953, 64.857437133789, 66.587478637695, 68.23265838623, 69.616966247559, 71.930046081543, 74.479080200195, 76.702774047852, 79.722648620605, 82.739562988281, 84.194038391113, 86.394561767578, 89.024154663086, 90.803779602051, 93.33869934082, 95.133476257324, 95.879165649414, 96.300735473633, 99.236442565918, 99.369491577148, 98.865951538086, 99.940536499023, 100.93288421631, 101.90919494629, 103.27114105225, 104.44651031494, 105.13195037842, 106.15531158447, 106.63150024414, 108.08444976807, 108.63333129883, 109.43137359619, 110.9778137207, 109.08748626709, 110.27933502197, 110.95265960693, 112.28410339355, 113.64099884033, 114.71849822998, 115.96046447754, 116.9249420166, 118.18309783936, 119.52725219727, 120.97621154785, 122.27430725098, 124.35485076904, 125.67234039307, 126.44793701172, 128.85502624512, 130.12554931641, 131.78700256348, 135.06434631348, 136.03129577637, 136.16580200195, 137.38041687012, 138.3335723877, 139.43733215332, 140.52355957031, 141.61158752441, 142.82865905762, 143.8990020752, 144.86265563965, 145.46542358398, 146.64192199707, 147.2303314209, 148.15628051758, 149.42742919922, 150.38327026367, 151.50639343262, 152.86457824707, 153.54354858398, 154.45077514648, 155.72262573242, 157.18922424316, 157.97552490234, 159.24418640137, 160.45292663574, 160.7678527832, 161.22578430176, 162.45433044434, 162.79898071289, 162.88320922852, 164.05364990234, 164.68334960938, 165.50071716309, 166.80894470215, 167.52500915527, 169.08515930176, 170.26745605469, 171.99620056152, 173.89532470703, 174.98243713379, 176.82391357422, 177.41424560547, 178.43989562988, 178.40797424316, 178.41456604004, 180.36318969727, 180.86373901367, 182.18086242676, 183.65283203125, 184.06123352051, 184.50300598145, 185.86199951172, 187.33641052246, 188.38456726074, 190.25567626953, 192.00257873535, 192.85073852539, 195.11291503906, 195.76824951172, 201.23341369629, 200.47758483887, 201.97981262207, 204.16139221191, 202.6296081543, 204.82388305664, 207.38688659668, 208.62408447266, 210.52333068848, 214.34335327148, 215.46553039551, 220.92074584961, 217.66012573242, 211.85800170898, 213.35252380371, 215.49029541016]) resid = np.array([np.nan, -.55428558588028, -.36208805441856, -.5116091966629, -.28030154109001, -.4422954916954, -.18432281911373, -.31516996026039, -.39063200354576, -.19754208624363, -.26044383645058, -.23408082127571, -.10966806858778, -.2874368429184, -.09011957794428, -.21747054159641, -.20822501182556, -.02426831051707, -.21233357489109, -.0452471524477, -.25427412986755, -.14787164330482, -.12461274117231, -.06853157281876, -.14335711300373, -.02953593060374, -.18524432182312, .00517434487119, .13549427688122, -.14863033592701, .12647144496441, -.28670132160187, -.05623856931925, .01299012638628, -.01581981778145, .07611121237278, -.05844036862254, .15600442886353, -.00349225639366, .0062618162483, .19772660732269, .03523930162191, .04237993061543, .13157841563225, .09463357180357, -.12051809579134, .021334676072, -.00378143391572, -.30863979458809, .06972090899944, -.19567719101906, -.14652347564697, -.13774801790714, -.13010406494141, -.02344283089042, .05482704937458, .52539497613907, -.12086410820484, .87448859214783, .42467761039734, .51533102989197, .34561482071877, .82943379878998, .2606680393219, -.29110881686211, .14797207713127, -.01560037955642, .00761602073908, -.58917766809464, .17878817021847, .05778701230884, -.04547626897693, .47921240329742, -.15394935011864, -.0471847653389, .26070219278336, .28498136997223, .64256292581558, .51252233982086, .2673399746418, .9830310344696, 1.0699564218521, .72091597318649, 1.2972244024277, 1.1773546934128, -.13956540822983, .50595796108246, .80543184280396, .07584273815155, .6962223649025, .06129856407642, -.73347336053848, -.87916851043701, 1.1992633342743, -1.1364471912384, -1.4694905281067, -.0659501478076, -.14053705334663, -.13288362324238, .19080325961113, .02886573970318, -.34650835394859, -.03194846212864, -.45531520247459, .36850056052208, -.38445034623146, -.13333308696747, .46862518787384, -2.2778205871582, .41251575946808, -.07933671027422, .4473415017128, .4158943593502, .1590022444725, .28150060772896, .03953726217151, .27505549788475, .31690016388893, .37275013327599, .22378182411194, .82568991184235, .14514668285847, -.27233889698982, 1.052060842514, .04496052488685, .37444713711739, 1.6129913330078, -.36434525251389, -.93128365278244, .03420155867934, -.1804157346487, -.03357006236911, -.03733511269093, -.02355666831136, .08841699361801, -.02865886501968, -.09899909794331, -.36265158653259, .13458555936813, -.34191656112671, -.03033804148436, .24371138215065, -.02743346057832, .1167239844799, .29360374808311, -.26456567645073, -.04355576634407, .24922250211239, .37737664580345, -.18922370672226, .22447402775288, .15580512583256, -.55293774604797, -.36785578727722, .27421084046364, -.45432937145233, -.59898042678833, .31679451465607, -.1536608338356, .01664204336703, .39926943182945, -.10894102603197, .57500427961349, .21484296023846, .63253426551819, .7037987112999, .00467173522338, .61756485700607, -.4239239692688, -.014255377464, -.83988964557648, -.70797437429428, .88542991876602, -.36318910121918, .33625638484955, .41914650797844, -.4528394639492, -.36123737692833, .39699018001556, .43800541758537, .06358920782804, .71544241905212, .54432433843613, -.20257151126862, .94927132129669, -.41291815042496, 3.4317541122437, -1.8334206342697, .22241242229939, .72019159793854, -2.2614006996155, .94440299272537, 1.0961196422577, -.04889564588666, .50891524553299, 1.971658706665, -.34635934233665, 3.1444630622864, -4.0317454338074, -5.4861345291138, .81299871206284, 1.1164767742157, .89470589160919]) yr = np.array([np.nan, -.55428558588028, -.36208805441856, -.5116091966629, -.28030154109001, -.4422954916954, -.18432281911373, -.31516996026039, -.39063200354576, -.19754208624363, -.26044383645058, -.23408082127571, -.10966806858778, -.2874368429184, -.09011957794428, -.21747054159641, -.20822501182556, -.02426831051707, -.21233357489109, -.0452471524477, -.25427412986755, -.14787164330482, -.12461274117231, -.06853157281876, -.14335711300373, -.02953593060374, -.18524432182312, .00517434487119, .13549427688122, -.14863033592701, .12647144496441, -.28670132160187, -.05623856931925, .01299012638628, -.01581981778145, .07611121237278, -.05844036862254, .15600442886353, -.00349225639366, .0062618162483, .19772660732269, .03523930162191, .04237993061543, .13157841563225, .09463357180357, -.12051809579134, .021334676072, -.00378143391572, -.30863979458809, .06972090899944, -.19567719101906, -.14652347564697, -.13774801790714, -.13010406494141, -.02344283089042, .05482704937458, .52539497613907, -.12086410820484, .87448859214783, .42467761039734, .51533102989197, .34561482071877, .82943379878998, .2606680393219, -.29110881686211, .14797207713127, -.01560037955642, .00761602073908, -.58917766809464, .17878817021847, .05778701230884, -.04547626897693, .47921240329742, -.15394935011864, -.0471847653389, .26070219278336, .28498136997223, .64256292581558, .51252233982086, .2673399746418, .9830310344696, 1.0699564218521, .72091597318649, 1.2972244024277, 1.1773546934128, -.13956540822983, .50595796108246, .80543184280396, .07584273815155, .6962223649025, .06129856407642, -.73347336053848, -.87916851043701, 1.1992633342743, -1.1364471912384, -1.4694905281067, -.0659501478076, -.14053705334663, -.13288362324238, .19080325961113, .02886573970318, -.34650835394859, -.03194846212864, -.45531520247459, .36850056052208, -.38445034623146, -.13333308696747, .46862518787384, -2.2778205871582, .41251575946808, -.07933671027422, .4473415017128, .4158943593502, .1590022444725, .28150060772896, .03953726217151, .27505549788475, .31690016388893, .37275013327599, .22378182411194, .82568991184235, .14514668285847, -.27233889698982, 1.052060842514, .04496052488685, .37444713711739, 1.6129913330078, -.36434525251389, -.93128365278244, .03420155867934, -.1804157346487, -.03357006236911, -.03733511269093, -.02355666831136, .08841699361801, -.02865886501968, -.09899909794331, -.36265158653259, .13458555936813, -.34191656112671, -.03033804148436, .24371138215065, -.02743346057832, .1167239844799, .29360374808311, -.26456567645073, -.04355576634407, .24922250211239, .37737664580345, -.18922370672226, .22447402775288, .15580512583256, -.55293774604797, -.36785578727722, .27421084046364, -.45432937145233, -.59898042678833, .31679451465607, -.1536608338356, .01664204336703, .39926943182945, -.10894102603197, .57500427961349, .21484296023846, .63253426551819, .7037987112999, .00467173522338, .61756485700607, -.4239239692688, -.014255377464, -.83988964557648, -.70797437429428, .88542991876602, -.36318910121918, .33625638484955, .41914650797844, -.4528394639492, -.36123737692833, .39699018001556, .43800541758537, .06358920782804, .71544241905212, .54432433843613, -.20257151126862, .94927132129669, -.41291815042496, 3.4317541122437, -1.8334206342697, .22241242229939, .72019159793854, -2.2614006996155, .94440299272537, 1.0961196422577, -.04889564588666, .50891524553299, 1.971658706665, -.34635934233665, 3.1444630622864, -4.0317454338074, -5.4861345291138, .81299871206284, 1.1164767742157, .89470589160919]) mse = np.array([ 1.1115040779114, .69814515113831, .63478744029999, .63409090042114, .63356643915176, .63317084312439, .63287192583084, .63264590501785, .63247483968735, .63234525918961, .63224703073502, .63217264413834, .63211619853973, .63207340240479, .63204091787338, .63201630115509, .63199764490128, .63198345899582, .63197267055511, .63196450471878, .63195830583572, .63195365667343, .63195008039474, .63194733858109, .63194531202316, .6319437623024, .6319425702095, .63194167613983, .63194096088409, .63194048404694, .63194006681442, .6319397687912, .63193953037262, .63193941116333, .6319392323494, .63193917274475, .63193905353546, .63193899393082, .63193899393082, .63193893432617, .63193893432617, .63193887472153, .63193887472153, .63193887472153, .63193887472153, .63193887472153, .63193887472153, .63193887472153, .63193887472153, .63193887472153, .63193887472153, .63193887472153, .63193887472153, .63193887472153, .63193887472153, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688, .63193881511688]) stdp = np.array([ .72428566217422, .72428566217422, .56208884716034, .53160965442657, .45030161738396, .45229381322861, .38432359695435, .40517011284828, .36063131690025, .30754271149635, .32044330239296, .29408219456673, .27966624498367, .29743707180023, .25011941790581, .27747189998627, .24822402000427, .23426930606365, .27233305573463, .23524768650532, .26427435874939, .21787133812904, .22461311519146, .22853142023087, .24335558712482, .22953669726849, .25524401664734, .22482520341873, .26450532674789, .31863233447075, .27352628111839, .33670437335968, .25623551011086, .28701293468475, .315819054842, .3238864839077, .35844340920448, .34399557113647, .40348997712135, .39373970031738, .4022718667984, .46476069092751, .45762005448341, .46842387318611, .50536489486694, .52051961421967, .47866532206535, .50378143787384, .50863671302795, .4302790760994, .49568024277687, .44652271270752, .43774726986885, .43010330200195, .42344436049461, .44517293572426, .47460499405861, .62086409330368, .52550911903381, .77532315254211, .78466820716858, .85438597202301, .87056696414948, 1.0393311977386, .99110960960388, .85202795267105, .91560190916061, .89238166809082, .88917690515518, .72121334075928, .84221452474594, .8454754948616, .82078683376312, .95394861698151, .84718400239944, .839300096035, .91501939296722, .95743554830551, 1.0874761343002, 1.1326615810394, 1.1169674396515, 1.3300451040268, 1.4790810346603, 1.5027786493301, 1.7226468324661, 1.8395622968674, 1.5940405130386, 1.694568157196, 1.8241587877274, 1.7037791013718, 1.838702917099, 1.7334734201431, 1.4791669845581, 1.3007366657257, 1.7364456653595, 1.2694935798645, .96595168113708, 1.1405370235443, 1.1328836679459, 1.1091921329498, 1.171138882637, 1.1465038061142, 1.0319484472275, 1.055313706398, .93150246143341, 1.0844472646713, .93333613872528, .93137633800507, 1.0778160095215, .38748729228973, .77933365106583, .75266307592392, .88410103321075, .94100385904312, .91849637031555, .96046274900436, .92494148015976, .98310285806656, 1.0272513628006, 1.0762135982513, 1.0743116140366, 1.254854798317, 1.1723403930664, 1.0479376316071, 1.3550333976746, 1.2255589962006, 1.2870025634766, 1.6643482446671, 1.3312928676605, 1.0657893419266, 1.1804157495499, 1.1335761547089, 1.137326002121, 1.1235628128052, 1.1115798950195, 1.1286649703979, 1.0989991426468, 1.0626485347748, .96542054414749, 1.0419135093689, .93033194541931, .95628559589386, 1.027433514595, .98328214883804, 1.0063992738724, 1.0645687580109, .94354963302612, .95077443122864, 1.0226324796677, 1.089217543602, .97552293539047, 1.0441918373108, 1.052937746048, .86785578727722, .82579529285431, .95432937145233, .79897737503052, .68320548534393, .85365778207779, .78336101770401, .80072748661041, .9089440703392, .82500487565994, .98515397310257, .96745657920837, 1.0962044000626, 1.195325255394, 1.0824474096298, 1.2239117622375, 1.0142554044724, 1.0399018526077, .80796521902084, .7145761847496, 1.0631860494614, .86374056339264, .98086261749268, 1.0528303384781, .86123734712601, .80300676822662, .96200370788574, 1.0364016294479, .98456978797913, 1.1556725502014, 1.2025715112686, 1.0507286787033, 1.312912106514, 1.0682457685471, 2.0334177017212, 1.0775905847549, 1.2798084020615, 1.461397767067, .72960823774338, 1.2498733997345, 1.466894865036, 1.286082983017, 1.3903408050537, 1.8483582735062, 1.4685434103012, 2.3107523918152, .7711226940155, -.31598940491676, .68151205778122, 1.0212944746017]) icstats = np.array([ 202, np.nan, -240.29558272688, 5, 490.59116545376, 507.13250394077]) class Bunch(dict): def __init__(self, **kw): dict.__init__(self, kw) self.__dict__ = self results = Bunch(llf=llf, nobs=nobs, k=k, k_exog=k_exog, sigma=sigma, chi2=chi2, df_model=df_model, k_ar=k_ar, k_ma=k_ma, params=params, cov_params=cov_params, xb=xb, y=y, resid=resid, yr=yr, mse=mse, stdp=stdp, icstats=icstats, )
#from django.contrib.auth import authenticate, login, logout #import urllib.request import requests, json, urllib, array import urllib.request from Crypto.Cipher import ARC4 from Crypto.PublicKey import RSA from Crypto.Hash import SHA256 from Crypto import Random def list_reports(user, password): r2 = requests.get('http://127.0.0.1:8000/fda_index/', params={'username':user}) #Must NOT provide the username here but get it from request data = json.loads(r2.text)#may not be necessary #print(data) if data == []: print("There are no reports for you.") return None i = 0 for f in data: file_dict = f['fields'] report_name = file_dict['name'] #print all the lists print(i, report_name) i += 1 return data def filedownload(file_index): resp = requests.get('http://127.0.0.1:8000/fda_index/', params={'username':user}) resp_data = json.loads(resp.text) #print(resp_data) which_report = (resp_data[file_index]) file_url = 'http://127.0.0.1:8000/media/' + which_report['fields']['path'] print(file_url) download_file_url = which_report['fields']['path'].split('/')[1] #extract name print(download_file_url) with urllib.request.urlopen(file_url) as url: s = url.read() with open(download_file_url, 'wb') as code: code.write(s) def encrypt_file(file, key): cipher_gen = ARC4.new(key) try: file_reader = open(file, 'rb') hash = SHA256.new(file_reader.read()).digest() print("actual signature: ", hash) #file_writer = open(file, 'ab') #file_writer.write(hash) #append hash to file file_reader = open(file, 'rb') file_writer = open(file + ".enc", 'wb') for line in file_reader: enc_line = cipher_gen.encrypt(line) file_writer.write(enc_line) enc_hash = cipher_gen.encrypt(hash)#append hash to file file_writer.write(enc_hash) print("encrypted signature: ",enc_hash) #cipher_gen = ARC4.new(key) #dec_hash = cipher_gen.decrypt(enc_hash) #print("attempt to decrypt right after: ", dec_hash) file_reader.close() file_writer.close() return True except: print("Error opening file: %s!" % file) return False def decrypt_file(file, key): decipher = ARC4.new(key) try: if (file[-4:] != ".enc"): return None file_reader = open(file, 'rb') file_writer = open("DEC_" + file[0:-4], 'wb') file_length = len(file_reader.read()) file_reader = open(file, 'rb') #reopens the file #print("file size", file_length) #another writer clear_signature = [] while(True): b = file_reader.read(1) if b: dec_b = decipher.decrypt(b) if file_reader.tell() > file_length-32: #print(dec_b) #clear_signature += str(dec_b) clear_signature.append(int.from_bytes(dec_b,'big')) #print(clear_signature) else: file_writer.write(dec_b) else: break #print((clear_signature)) """ file_reader2 = open("DEC_" + file,'rb') print("hi",file_reader2.tell()) hash = SHA256.new(file_reader2.read()).digest() print(len(hash), hash) file_reader2.close() """ file_writer.close()#the file is ready file_reader.close() return clear_signature except: return None if __name__ == "__main__": URL = "http://localhost:8000/users/fda_login" URL_download = "http://localhost:8000/fda_index" client = requests.session() #====AUTHENTICATION==== user = input("username: ") pwd = input("password: ") #user = 'marco' #DEBUG #pwd = 'marco' #DEBUG login = {'username':user,'password':pwd} r = client.post(URL, data=login) if r.text == "success": #If login is successful print("Welcome", login['username']) print() else: print("Login failed") exit() print("Commands:") print('"v" - View reports') print('"d" - View a report\'s detail') print('"do" - Download report\'s files') print('"e" - Encrypt a file in the current folder') print('"dc" - Decrypt a file') print('"h" - Help') print('"q" - Quit\n') data = list_reports(user, pwd) while(1): command = input("What would you like to do?") #command = 'dc' #DEBUG #====LIST REPORTS==== if command == 'v': data = list_reports(user, pwd) #refresh reports data #====DETAILS==== if (command == 'd'): while(True): file_index = int(input("Select report to view (use its number):")) if file_index >= len(data): print("Not a valid number...") continue print() """ for f in data: file_dict = f['fields'] if which_report == file_dict['name']: for field in file_dict: print(field,":",file_dict[field]) not_found=False """ which_report = data[file_index] for field in which_report['fields']: print(field,":",which_report['fields'][field]) break #====DOWNLOAD==== if command == 'do': which_report = int(input("Select a report (using its number) to download:")) filedownload(which_report) #====ENCRYPTION==== if command == 'e': file_name = input("Enter filename including extension:") enc_key = input("Enter a password for the file:") if encrypt_file(file_name,enc_key): print("Done!") else: print("An error has occurred encrypting your file!") #====DECRYPTION==== if command == 'dc': file_name = input("Enter filename including extension:") if file_name == "": #MUST HANDLE I/O pass enc_key = input("Enter the file's password:") #file_name = "marco.png.enc" #enc_key = "123" signature = decrypt_file(file_name,enc_key) #print(signature) with open("DEC_"+file_name[:-4], 'rb') as file_reader: hash = SHA256.new(file_reader.read()).digest() #print("hash: ", str.encode(str(hash))) corrupted = False j = 0 if signature: print("Comparing signatures: ") for h in hash: print(int(h), signature[j])#DEBUG if(int(h) != signature[j]): corrupted = True break j += 1 if (not corrupted): print("Done!") else: print("The file was corrupted...") else: print("An error has occurred decrypting your file!") #print(file_dict) """# Tried passing a request with current session to avoid passing username in the script req = requests.Request('GET', URL_download)#create request prep_req = req.prepare()#prepare request resp=client.send(prep_req) print(resp.text) """ if command == 'h': print("Commands:") print('"v" - View reports') print('"d" - View a report\'s detail') print('"do" - Donwnload report\'s files') print('"e" - Encrypt a file in the current folder') print('"dc" - Decrypt a file') print('"h" - Help') print('"q" - Quit\n') if command == 'q': break print()
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2011 X.commerce, a business unit of eBay Inc. # 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. """ SQLAlchemy models for nova data. """ from sqlalchemy import Column, Index, Integer, BigInteger, Enum, String, schema from sqlalchemy.dialects.mysql import MEDIUMTEXT from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import ForeignKey, DateTime, Boolean, Text, Float from sqlalchemy.orm import relationship, backref, object_mapper from oslo.config import cfg from nova.db.sqlalchemy import types from nova.openstack.common.db.sqlalchemy import models from nova.openstack.common import timeutils CONF = cfg.CONF BASE = declarative_base() def MediumText(): return Text().with_variant(MEDIUMTEXT(), 'mysql') class NovaBase(models.SoftDeleteMixin, models.TimestampMixin, models.ModelBase): metadata = None class Service(BASE, NovaBase): """Represents a running service on a host.""" __tablename__ = 'services' __table_args__ = ( schema.UniqueConstraint("host", "topic", "deleted", name="uniq_services0host0topic0deleted"), schema.UniqueConstraint("host", "binary", "deleted", name="uniq_services0host0binary0deleted") ) id = Column(Integer, primary_key=True) host = Column(String(255), nullable=True) # , ForeignKey('hosts.id')) binary = Column(String(255), nullable=True) topic = Column(String(255), nullable=True) report_count = Column(Integer, nullable=False, default=0) disabled = Column(Boolean, default=False) disabled_reason = Column(String(255)) class ComputeNode(BASE, NovaBase): """Represents a running compute service on a host.""" __tablename__ = 'compute_nodes' __table_args__ = () id = Column(Integer, primary_key=True) service_id = Column(Integer, ForeignKey('services.id'), nullable=False) service = relationship(Service, backref=backref('compute_node'), foreign_keys=service_id, primaryjoin='and_(' 'ComputeNode.service_id == Service.id,' 'ComputeNode.deleted == 0)') vcpus = Column(Integer, nullable=False) memory_mb = Column(Integer, nullable=False) local_gb = Column(Integer, nullable=False) vcpus_used = Column(Integer, nullable=False) memory_mb_used = Column(Integer, nullable=False) local_gb_used = Column(Integer, nullable=False) hypervisor_type = Column(MediumText(), nullable=False) hypervisor_version = Column(Integer, nullable=False) hypervisor_hostname = Column(String(255), nullable=True) # Free Ram, amount of activity (resize, migration, boot, etc) and # the number of running VM's are a good starting point for what's # important when making scheduling decisions. free_ram_mb = Column(Integer, nullable=True) free_disk_gb = Column(Integer, nullable=True) current_workload = Column(Integer, nullable=True) running_vms = Column(Integer, nullable=True) # Note(masumotok): Expected Strings example: # # '{"arch":"x86_64", # "model":"Nehalem", # "topology":{"sockets":1, "threads":2, "cores":3}, # "features":["tdtscp", "xtpr"]}' # # Points are "json translatable" and it must have all dictionary keys # above, since it is copied from <cpu> tag of getCapabilities() # (See libvirt.virtConnection). cpu_info = Column(MediumText(), nullable=False) disk_available_least = Column(Integer, nullable=True) class ComputeNodeStat(BASE, NovaBase): """Stats related to the current workload of a compute host that are intended to aid in making scheduler decisions. """ __tablename__ = 'compute_node_stats' __table_args__ = ( Index('ix_compute_node_stats_compute_node_id', 'compute_node_id'), Index('compute_node_stats_node_id_and_deleted_idx', 'compute_node_id', 'deleted') ) id = Column(Integer, primary_key=True) key = Column(String(255), nullable=False) value = Column(String(255), nullable=True) compute_node_id = Column(Integer, ForeignKey('compute_nodes.id'), nullable=False) primary_join = ('and_(ComputeNodeStat.compute_node_id == ' 'ComputeNode.id, ComputeNodeStat.deleted == 0)') stats = relationship("ComputeNode", backref="stats", primaryjoin=primary_join) def __str__(self): return "{%d: %s = %s}" % (self.compute_node_id, self.key, self.value) class Certificate(BASE, NovaBase): """Represents a x509 certificate.""" __tablename__ = 'certificates' __table_args__ = ( Index('certificates_project_id_deleted_idx', 'project_id', 'deleted'), Index('certificates_user_id_deleted_idx', 'user_id', 'deleted') ) id = Column(Integer, primary_key=True) user_id = Column(String(255), nullable=True) project_id = Column(String(255), nullable=True) file_name = Column(String(255), nullable=True) class Instance(BASE, NovaBase): """Represents a guest VM.""" __tablename__ = 'instances' __table_args__ = ( Index('uuid', 'uuid', unique=True), Index('project_id', 'project_id'), Index('instances_host_deleted_idx', 'host', 'deleted'), Index('instances_reservation_id_idx', 'reservation_id'), Index('instances_terminated_at_launched_at_idx', 'terminated_at', 'launched_at'), Index('instances_uuid_deleted_idx', 'uuid', 'deleted'), Index('instances_task_state_updated_at_idx', 'task_state', 'updated_at'), Index('instances_host_node_deleted_idx', 'host', 'node', 'deleted'), Index('instances_host_deleted_cleaned_idx', 'host', 'deleted', 'cleaned'), ) injected_files = [] id = Column(Integer, primary_key=True, autoincrement=True) @property def name(self): try: base_name = CONF.instance_name_template % self.id except TypeError: # Support templates like "uuid-%(uuid)s", etc. info = {} # NOTE(russellb): Don't use self.iteritems() here, as it will # result in infinite recursion on the name property. for column in iter(object_mapper(self).columns): key = column.name # prevent recursion if someone specifies %(name)s # %(name)s will not be valid. if key == 'name': continue info[key] = self[key] try: base_name = CONF.instance_name_template % info except KeyError: base_name = self.uuid return base_name def _extra_keys(self): return ['name'] user_id = Column(String(255), nullable=True) project_id = Column(String(255), nullable=True) image_ref = Column(String(255), nullable=True) kernel_id = Column(String(255), nullable=True) ramdisk_id = Column(String(255), nullable=True) hostname = Column(String(255), nullable=True) launch_index = Column(Integer, nullable=True) key_name = Column(String(255), nullable=True) key_data = Column(MediumText()) power_state = Column(Integer, nullable=True) vm_state = Column(String(255), nullable=True) task_state = Column(String(255), nullable=True) memory_mb = Column(Integer, nullable=True) vcpus = Column(Integer, nullable=True) root_gb = Column(Integer, nullable=True) ephemeral_gb = Column(Integer, nullable=True) # This is not related to hostname, above. It refers # to the nova node. host = Column(String(255), nullable=True) # , ForeignKey('hosts.id')) # To identify the "ComputeNode" which the instance resides in. # This equals to ComputeNode.hypervisor_hostname. node = Column(String(255), nullable=True) # *not* flavorid, this is the internal primary_key instance_type_id = Column(Integer, nullable=True) user_data = Column(MediumText(), nullable=True) reservation_id = Column(String(255), nullable=True) scheduled_at = Column(DateTime, nullable=True) launched_at = Column(DateTime, nullable=True) terminated_at = Column(DateTime, nullable=True) availability_zone = Column(String(255), nullable=True) # User editable field for display in user-facing UIs display_name = Column(String(255), nullable=True) display_description = Column(String(255), nullable=True) # To remember on which host an instance booted. # An instance may have moved to another host by live migration. launched_on = Column(MediumText(), nullable=True) # NOTE(jdillaman): locked deprecated in favor of locked_by, # to be removed in Icehouse locked = Column(Boolean, nullable=True) locked_by = Column(Enum('owner', 'admin'), nullable=True) os_type = Column(String(255), nullable=True) architecture = Column(String(255), nullable=True) vm_mode = Column(String(255), nullable=True) uuid = Column(String(36)) root_device_name = Column(String(255), nullable=True) default_ephemeral_device = Column(String(255), nullable=True) default_swap_device = Column(String(255), nullable=True) config_drive = Column(String(255), nullable=True) # User editable field meant to represent what ip should be used # to connect to the instance access_ip_v4 = Column(types.IPAddress(), nullable=True) access_ip_v6 = Column(types.IPAddress(), nullable=True) auto_disk_config = Column(Boolean(), nullable=True) progress = Column(Integer, nullable=True) # EC2 instance_initiated_shutdown_terminate # True: -> 'terminate' # False: -> 'stop' # Note(maoy): currently Nova will always stop instead of terminate # no matter what the flag says. So we set the default to False. shutdown_terminate = Column(Boolean(), default=False, nullable=True) # EC2 disable_api_termination disable_terminate = Column(Boolean(), default=False, nullable=True) # OpenStack compute cell name. This will only be set at the top of # the cells tree and it'll be a full cell name such as 'api!hop1!hop2' cell_name = Column(String(255), nullable=True) internal_id = Column(Integer, nullable=True) # Records whether an instance has been deleted from disk cleaned = Column(Integer, default=0) class InstanceInfoCache(BASE, NovaBase): """ Represents a cache of information about an instance """ __tablename__ = 'instance_info_caches' __table_args__ = ( schema.UniqueConstraint( "instance_uuid", name="uniq_instance_info_caches0instance_uuid"),) id = Column(Integer, primary_key=True, autoincrement=True) # text column used for storing a json object of network data for api network_info = Column(MediumText()) instance_uuid = Column(String(36), ForeignKey('instances.uuid'), nullable=False) instance = relationship(Instance, backref=backref('info_cache', uselist=False), foreign_keys=instance_uuid, primaryjoin=instance_uuid == Instance.uuid) class InstanceTypes(BASE, NovaBase): """Represents possible flavors for instances. Note: instance_type and flavor are synonyms and the term instance_type is deprecated and in the process of being removed. """ __tablename__ = "instance_types" __table_args__ = ( schema.UniqueConstraint("flavorid", "deleted", name="uniq_instance_types0flavorid0deleted"), schema.UniqueConstraint("name", "deleted", name="uniq_instance_types0name0deleted") ) # Internal only primary key/id id = Column(Integer, primary_key=True) name = Column(String(255)) memory_mb = Column(Integer, nullable=False) vcpus = Column(Integer, nullable=False) root_gb = Column(Integer) ephemeral_gb = Column(Integer) # Public facing id will be renamed public_id flavorid = Column(String(255)) swap = Column(Integer, nullable=False, default=0) rxtx_factor = Column(Float, nullable=True, default=1) vcpu_weight = Column(Integer, nullable=True) disabled = Column(Boolean, default=False) is_public = Column(Boolean, default=True) class Volume(BASE, NovaBase): """Represents a block storage device that can be attached to a VM.""" __tablename__ = 'volumes' __table_args__ = ( Index('volumes_instance_uuid_idx', 'instance_uuid'), ) id = Column(String(36), primary_key=True, nullable=False) deleted = Column(String(36), default="") @property def name(self): return CONF.volume_name_template % self.id ec2_id = Column(String(255)) user_id = Column(String(255)) project_id = Column(String(255)) snapshot_id = Column(String(36)) host = Column(String(255)) size = Column(Integer) availability_zone = Column(String(255)) instance_uuid = Column(String(36)) mountpoint = Column(String(255)) attach_time = Column(DateTime) status = Column(String(255)) # TODO(vish): enum? attach_status = Column(String(255)) # TODO(vish): enum scheduled_at = Column(DateTime) launched_at = Column(DateTime) terminated_at = Column(DateTime) display_name = Column(String(255)) display_description = Column(String(255)) provider_location = Column(String(256)) provider_auth = Column(String(256)) volume_type_id = Column(Integer) class Quota(BASE, NovaBase): """Represents a single quota override for a project. If there is no row for a given project id and resource, then the default for the quota class is used. If there is no row for a given quota class and resource, then the default for the deployment is used. If the row is present but the hard limit is Null, then the resource is unlimited. """ __tablename__ = 'quotas' __table_args__ = ( schema.UniqueConstraint("project_id", "resource", "deleted", name="uniq_quotas0project_id0resource0deleted" ), ) id = Column(Integer, primary_key=True) project_id = Column(String(255), nullable=True) resource = Column(String(255), nullable=False) hard_limit = Column(Integer, nullable=True) class ProjectUserQuota(BASE, NovaBase): """Represents a single quota override for a user with in a project.""" __tablename__ = 'project_user_quotas' uniq_name = "uniq_project_user_quotas0user_id0project_id0resource0deleted" __table_args__ = ( schema.UniqueConstraint("user_id", "project_id", "resource", "deleted", name=uniq_name), Index('project_user_quotas_project_id_deleted_idx', 'project_id', 'deleted'), Index('project_user_quotas_user_id_deleted_idx', 'user_id', 'deleted') ) id = Column(Integer, primary_key=True, nullable=False) project_id = Column(String(255), nullable=False) user_id = Column(String(255), nullable=False) resource = Column(String(255), nullable=False) hard_limit = Column(Integer, nullable=True) class QuotaClass(BASE, NovaBase): """Represents a single quota override for a quota class. If there is no row for a given quota class and resource, then the default for the deployment is used. If the row is present but the hard limit is Null, then the resource is unlimited. """ __tablename__ = 'quota_classes' __table_args__ = ( Index('ix_quota_classes_class_name', 'class_name'), ) id = Column(Integer, primary_key=True) class_name = Column(String(255), nullable=True) resource = Column(String(255), nullable=True) hard_limit = Column(Integer, nullable=True) class QuotaUsage(BASE, NovaBase): """Represents the current usage for a given resource.""" __tablename__ = 'quota_usages' __table_args__ = ( Index('ix_quota_usages_project_id', 'project_id'), ) id = Column(Integer, primary_key=True) project_id = Column(String(255), nullable=True) user_id = Column(String(255), nullable=True) resource = Column(String(255), nullable=False) in_use = Column(Integer, nullable=False) reserved = Column(Integer, nullable=False) @property def total(self): return self.in_use + self.reserved until_refresh = Column(Integer, nullable=True) class Reservation(BASE, NovaBase): """Represents a resource reservation for quotas.""" __tablename__ = 'reservations' __table_args__ = ( Index('ix_reservations_project_id', 'project_id'), Index('reservations_uuid_idx', 'uuid'), ) id = Column(Integer, primary_key=True, nullable=False) uuid = Column(String(36), nullable=False) usage_id = Column(Integer, ForeignKey('quota_usages.id'), nullable=False) project_id = Column(String(255)) user_id = Column(String(255)) resource = Column(String(255)) delta = Column(Integer, nullable=False) expire = Column(DateTime, nullable=True) usage = relationship( "QuotaUsage", foreign_keys=usage_id, primaryjoin='and_(Reservation.usage_id == QuotaUsage.id,' 'QuotaUsage.deleted == 0)') class Snapshot(BASE, NovaBase): """Represents a block storage device that can be attached to a VM.""" __tablename__ = 'snapshots' __table_args__ = () id = Column(String(36), primary_key=True, nullable=False) deleted = Column(String(36), default="", nullable=True) @property def name(self): return CONF.snapshot_name_template % self.id @property def volume_name(self): return CONF.volume_name_template % self.volume_id user_id = Column(String(255), nullable=True) project_id = Column(String(255), nullable=True) volume_id = Column(String(36), nullable=False) status = Column(String(255), nullable=True) progress = Column(String(255), nullable=True) volume_size = Column(Integer, nullable=True) scheduled_at = Column(DateTime, nullable=True) display_name = Column(String(255), nullable=True) display_description = Column(String(255), nullable=True) class BlockDeviceMapping(BASE, NovaBase): """Represents block device mapping that is defined by EC2.""" __tablename__ = "block_device_mapping" __table_args__ = ( Index('snapshot_id', 'snapshot_id'), Index('volume_id', 'volume_id'), Index('block_device_mapping_instance_uuid_device_name_idx', 'instance_uuid', 'device_name'), Index('block_device_mapping_instance_uuid_volume_id_idx', 'instance_uuid', 'volume_id'), Index('block_device_mapping_instance_uuid_idx', 'instance_uuid'), #TODO(sshturm) Should be dropped. `virtual_name` was dropped #in 186 migration, #Duplicates `block_device_mapping_instance_uuid_device_name_idx` index. Index("block_device_mapping_instance_uuid_virtual_name" "_device_name_idx", 'instance_uuid', 'device_name'), ) id = Column(Integer, primary_key=True, autoincrement=True) instance_uuid = Column(String(36), ForeignKey('instances.uuid')) instance = relationship(Instance, backref=backref('block_device_mapping'), foreign_keys=instance_uuid, primaryjoin='and_(BlockDeviceMapping.' 'instance_uuid==' 'Instance.uuid,' 'BlockDeviceMapping.deleted==' '0)') source_type = Column(String(255)) destination_type = Column(String(255)) guest_format = Column(String(255)) device_type = Column(String(255)) disk_bus = Column(String(255)) boot_index = Column(Integer) device_name = Column(String(255)) # default=False for compatibility of the existing code. # With EC2 API, # default True for ami specified device. # default False for created with other timing. #TODO(sshturm) add default in db delete_on_termination = Column(Boolean, default=False) snapshot_id = Column(String(36)) volume_id = Column(String(36), nullable=True) volume_size = Column(Integer, nullable=True) image_id = Column('image_id', String(36)) # for no device to suppress devices. no_device = Column(Boolean, nullable=True) connection_info = Column(MediumText()) class IscsiTarget(BASE, NovaBase): """Represents an iscsi target for a given host.""" __tablename__ = 'iscsi_targets' __table_args__ = ( Index('iscsi_targets_volume_id_fkey', 'volume_id'), Index('iscsi_targets_host_idx', 'host'), Index('iscsi_targets_host_volume_id_deleted_idx', 'host', 'volume_id', 'deleted') ) id = Column(Integer, primary_key=True, nullable=False) target_num = Column(Integer) host = Column(String(255)) volume_id = Column(String(36), ForeignKey('volumes.id'), nullable=True) volume = relationship(Volume, backref=backref('iscsi_target', uselist=False), foreign_keys=volume_id, primaryjoin='and_(IscsiTarget.volume_id==Volume.id,' 'IscsiTarget.deleted==0)') class SecurityGroupInstanceAssociation(BASE, NovaBase): __tablename__ = 'security_group_instance_association' __table_args__ = ( Index('security_group_instance_association_instance_uuid_idx', 'instance_uuid'), ) id = Column(Integer, primary_key=True, nullable=False) security_group_id = Column(Integer, ForeignKey('security_groups.id')) instance_uuid = Column(String(36), ForeignKey('instances.uuid')) class SecurityGroup(BASE, NovaBase): """Represents a security group.""" __tablename__ = 'security_groups' __table_args__ = ( Index('uniq_security_groups0project_id0name0deleted', 'project_id', 'name', 'deleted'), ) id = Column(Integer, primary_key=True) name = Column(String(255)) description = Column(String(255)) user_id = Column(String(255)) project_id = Column(String(255)) instances = relationship(Instance, secondary="security_group_instance_association", primaryjoin='and_(' 'SecurityGroup.id == ' 'SecurityGroupInstanceAssociation.security_group_id,' 'SecurityGroupInstanceAssociation.deleted == 0,' 'SecurityGroup.deleted == 0)', secondaryjoin='and_(' 'SecurityGroupInstanceAssociation.instance_uuid == Instance.uuid,' # (anthony) the condition below shouldn't be necessary now that the # association is being marked as deleted. However, removing this # may cause existing deployments to choke, so I'm leaving it 'Instance.deleted == 0)', backref='security_groups') class SecurityGroupIngressRule(BASE, NovaBase): """Represents a rule in a security group.""" __tablename__ = 'security_group_rules' __table_args__ = () id = Column(Integer, primary_key=True) parent_group_id = Column(Integer, ForeignKey('security_groups.id')) parent_group = relationship("SecurityGroup", backref="rules", foreign_keys=parent_group_id, primaryjoin='and_(' 'SecurityGroupIngressRule.parent_group_id == SecurityGroup.id,' 'SecurityGroupIngressRule.deleted == 0)') protocol = Column(String(255)) from_port = Column(Integer) to_port = Column(Integer) cidr = Column(types.CIDR()) # Note: This is not the parent SecurityGroup. It's SecurityGroup we're # granting access for. group_id = Column(Integer, ForeignKey('security_groups.id')) grantee_group = relationship("SecurityGroup", foreign_keys=group_id, primaryjoin='and_(' 'SecurityGroupIngressRule.group_id == SecurityGroup.id,' 'SecurityGroupIngressRule.deleted == 0)') class SecurityGroupIngressDefaultRule(BASE, NovaBase): __tablename__ = 'security_group_default_rules' __table_args__ = () id = Column(Integer, primary_key=True, nullable=False) protocol = Column(String(5)) # "tcp", "udp" or "icmp" from_port = Column(Integer) to_port = Column(Integer) cidr = Column(types.CIDR()) class ProviderFirewallRule(BASE, NovaBase): """Represents a rule in a security group.""" __tablename__ = 'provider_fw_rules' __table_args__ = () id = Column(Integer, primary_key=True, nullable=False) protocol = Column(String(5)) # "tcp", "udp", or "icmp" from_port = Column(Integer) to_port = Column(Integer) cidr = Column(types.CIDR()) class KeyPair(BASE, NovaBase): """Represents a public key pair for ssh.""" __tablename__ = 'key_pairs' __table_args__ = ( schema.UniqueConstraint("user_id", "name", "deleted", name="uniq_key_pairs0user_id0name0deleted"), ) id = Column(Integer, primary_key=True, nullable=False) name = Column(String(255)) user_id = Column(String(255)) fingerprint = Column(String(255)) public_key = Column(MediumText()) class Migration(BASE, NovaBase): """Represents a running host-to-host migration.""" __tablename__ = 'migrations' __table_args__ = ( Index('migrations_instance_uuid_and_status_idx', 'instance_uuid', 'status'), Index('migrations_by_host_nodes_and_status_idx', 'deleted', 'source_compute', 'dest_compute', 'source_node', 'dest_node', 'status'), ) id = Column(Integer, primary_key=True, nullable=False) # NOTE(tr3buchet): the ____compute variables are instance['host'] source_compute = Column(String(255)) dest_compute = Column(String(255)) # nodes are equivalent to a compute node's 'hypvervisor_hostname' source_node = Column(String(255)) dest_node = Column(String(255)) # NOTE(tr3buchet): dest_host, btw, is an ip address dest_host = Column(String(255)) old_instance_type_id = Column(Integer()) new_instance_type_id = Column(Integer()) instance_uuid = Column(String(36), ForeignKey('instances.uuid'), nullable=True) #TODO(_cerberus_): enum status = Column(String(255)) instance = relationship("Instance", foreign_keys=instance_uuid, primaryjoin='and_(Migration.instance_uuid == ' 'Instance.uuid, Instance.deleted == ' '0)') class Network(BASE, NovaBase): """Represents a network.""" __tablename__ = 'networks' __table_args__ = ( schema.UniqueConstraint("vlan", "deleted", name="uniq_networks0vlan0deleted"), Index('networks_bridge_deleted_idx', 'bridge', 'deleted'), Index('networks_host_idx', 'host'), Index('networks_project_id_deleted_idx', 'project_id', 'deleted'), Index('networks_uuid_project_id_deleted_idx', 'uuid', 'project_id', 'deleted'), Index('networks_vlan_deleted_idx', 'vlan', 'deleted'), Index('networks_cidr_v6_idx', 'cidr_v6') ) id = Column(Integer, primary_key=True, nullable=False) label = Column(String(255)) injected = Column(Boolean, default=False) cidr = Column(types.CIDR()) cidr_v6 = Column(types.CIDR()) multi_host = Column(Boolean, default=False) gateway_v6 = Column(types.IPAddress()) netmask_v6 = Column(types.IPAddress()) netmask = Column(types.IPAddress()) bridge = Column(String(255)) bridge_interface = Column(String(255)) gateway = Column(types.IPAddress()) broadcast = Column(types.IPAddress()) dns1 = Column(types.IPAddress()) dns2 = Column(types.IPAddress()) vlan = Column(Integer) vpn_public_address = Column(types.IPAddress()) vpn_public_port = Column(Integer) vpn_private_address = Column(types.IPAddress()) dhcp_start = Column(types.IPAddress()) rxtx_base = Column(Integer) project_id = Column(String(255)) priority = Column(Integer) host = Column(String(255)) # , ForeignKey('hosts.id')) uuid = Column(String(36)) class VirtualInterface(BASE, NovaBase): """Represents a virtual interface on an instance.""" __tablename__ = 'virtual_interfaces' __table_args__ = ( schema.UniqueConstraint("address", "deleted", name="uniq_virtual_interfaces0address0deleted"), Index('network_id', 'network_id'), Index('virtual_interfaces_instance_uuid_fkey', 'instance_uuid'), ) id = Column(Integer, primary_key=True, nullable=False) address = Column(String(255), nullable=True) network_id = Column(Integer, nullable=True) instance_uuid = Column(String(36), ForeignKey('instances.uuid'), nullable=True) uuid = Column(String(36), nullable=True) # TODO(vish): can these both come from the same baseclass? class FixedIp(BASE, NovaBase): """Represents a fixed ip for an instance.""" __tablename__ = 'fixed_ips' __table_args__ = ( schema.UniqueConstraint( "address", "deleted", name="uniq_fixed_ips0address0deleted"), Index('fixed_ips_virtual_interface_id_fkey', 'virtual_interface_id'), Index('network_id', 'network_id'), Index('address', 'address'), Index('fixed_ips_instance_uuid_fkey', 'instance_uuid'), Index('fixed_ips_host_idx', 'host'), Index('fixed_ips_network_id_host_deleted_idx', 'network_id', 'host', 'deleted'), Index('fixed_ips_address_reserved_network_id_deleted_idx', 'address', 'reserved', 'network_id', 'deleted'), Index('fixed_ips_deleted_allocated_idx', 'address', 'deleted', 'allocated') ) id = Column(Integer, primary_key=True) address = Column(types.IPAddress()) network_id = Column(Integer, nullable=True) virtual_interface_id = Column(Integer, nullable=True) instance_uuid = Column(String(36), ForeignKey('instances.uuid'), nullable=True) # associated means that a fixed_ip has its instance_id column set # allocated means that a fixed_ip has its virtual_interface_id column set #TODO(sshturm) add default in db allocated = Column(Boolean, default=False) # leased means dhcp bridge has leased the ip #TODO(sshturm) add default in db leased = Column(Boolean, default=False) #TODO(sshturm) add default in db reserved = Column(Boolean, default=False) host = Column(String(255)) network = relationship(Network, backref=backref('fixed_ips'), foreign_keys=network_id, primaryjoin='and_(' 'FixedIp.network_id == Network.id,' 'FixedIp.deleted == 0,' 'Network.deleted == 0)') instance = relationship(Instance, foreign_keys=instance_uuid, primaryjoin='and_(' 'FixedIp.instance_uuid == Instance.uuid,' 'FixedIp.deleted == 0,' 'Instance.deleted == 0)') class FloatingIp(BASE, NovaBase): """Represents a floating ip that dynamically forwards to a fixed ip.""" __tablename__ = 'floating_ips' __table_args__ = ( schema.UniqueConstraint("address", "deleted", name="uniq_floating_ips0address0deleted"), Index('fixed_ip_id', 'fixed_ip_id'), Index('floating_ips_host_idx', 'host'), Index('floating_ips_project_id_idx', 'project_id'), Index('floating_ips_pool_deleted_fixed_ip_id_project_id_idx', 'pool', 'deleted', 'fixed_ip_id', 'project_id') ) id = Column(Integer, primary_key=True) address = Column(types.IPAddress()) fixed_ip_id = Column(Integer, nullable=True) project_id = Column(String(255)) host = Column(String(255)) # , ForeignKey('hosts.id')) auto_assigned = Column(Boolean, default=False, nullable=True) #TODO(sshturm) add default in db pool = Column(String(255)) interface = Column(String(255)) fixed_ip = relationship(FixedIp, backref=backref('floating_ips'), foreign_keys=fixed_ip_id, primaryjoin='and_(' 'FloatingIp.fixed_ip_id == FixedIp.id,' 'FloatingIp.deleted == 0,' 'FixedIp.deleted == 0)') class DNSDomain(BASE, NovaBase): """Represents a DNS domain with availability zone or project info.""" __tablename__ = 'dns_domains' __table_args__ = ( Index('project_id', 'project_id'), Index('dns_domains_domain_deleted_idx', 'domain', 'deleted'), ) deleted = Column(Boolean, default=False) domain = Column(String(255), primary_key=True) scope = Column(String(255), nullable=True) availability_zone = Column(String(255), nullable=True) project_id = Column(String(255), nullable=True) class ConsolePool(BASE, NovaBase): """Represents pool of consoles on the same physical node.""" __tablename__ = 'console_pools' __table_args__ = ( schema.UniqueConstraint( "host", "console_type", "compute_host", "deleted", name="uniq_console_pools0host0console_type0compute_host0deleted"), ) id = Column(Integer, primary_key=True) address = Column(types.IPAddress(), nullable=True) username = Column(String(255), nullable=True) password = Column(String(255), nullable=True) console_type = Column(String(255), nullable=True) public_hostname = Column(String(255), nullable=True) host = Column(String(255), nullable=True) compute_host = Column(String(255), nullable=True) class Console(BASE, NovaBase): """Represents a console session for an instance.""" __tablename__ = 'consoles' __table_args__ = ( Index('consoles_instance_uuid_idx', 'instance_uuid'), ) id = Column(Integer, primary_key=True) instance_name = Column(String(255), nullable=True) instance_uuid = Column(String(36), ForeignKey('instances.uuid'), nullable=True) password = Column(String(255), nullable=True) port = Column(Integer, nullable=True) pool_id = Column(Integer, ForeignKey('console_pools.id'), nullable=True) pool = relationship(ConsolePool, backref=backref('consoles')) class InstanceMetadata(BASE, NovaBase): """Represents a user-provided metadata key/value pair for an instance.""" __tablename__ = 'instance_metadata' __table_args__ = ( Index('instance_metadata_instance_uuid_idx', 'instance_uuid'), ) id = Column(Integer, primary_key=True) key = Column(String(255), nullable=True) value = Column(String(255), nullable=True) instance_uuid = Column(String(36), ForeignKey('instances.uuid'), nullable=True) instance = relationship(Instance, backref="metadata", foreign_keys=instance_uuid, primaryjoin='and_(' 'InstanceMetadata.instance_uuid == ' 'Instance.uuid,' 'InstanceMetadata.deleted == 0)') class InstanceSystemMetadata(BASE, NovaBase): """Represents a system-owned metadata key/value pair for an instance.""" __tablename__ = 'instance_system_metadata' __table_args__ = () id = Column(Integer, primary_key=True) key = Column(String(255), nullable=False) value = Column(String(255)) instance_uuid = Column(String(36), ForeignKey('instances.uuid'), nullable=False) primary_join = ('and_(InstanceSystemMetadata.instance_uuid == ' 'Instance.uuid, InstanceSystemMetadata.deleted == 0)') instance = relationship(Instance, backref="system_metadata", foreign_keys=instance_uuid, primaryjoin=primary_join) class InstanceTypeProjects(BASE, NovaBase): """Represent projects associated instance_types.""" __tablename__ = "instance_type_projects" __table_args__ = (schema.UniqueConstraint( "instance_type_id", "project_id", "deleted", name="uniq_instance_type_projects0instance_type_id0project_id0deleted" ), ) id = Column(Integer, primary_key=True) instance_type_id = Column(Integer, ForeignKey('instance_types.id'), nullable=False) project_id = Column(String(255)) instance_type = relationship(InstanceTypes, backref="projects", foreign_keys=instance_type_id, primaryjoin='and_(' 'InstanceTypeProjects.instance_type_id == InstanceTypes.id,' 'InstanceTypeProjects.deleted == 0)') class InstanceTypeExtraSpecs(BASE, NovaBase): """Represents additional specs as key/value pairs for an instance_type.""" __tablename__ = 'instance_type_extra_specs' __table_args__ = ( Index('instance_type_extra_specs_instance_type_id_key_idx', 'instance_type_id', 'key'), schema.UniqueConstraint( "instance_type_id", "key", "deleted", name=("uniq_instance_type_extra_specs0" "instance_type_id0key0deleted") ), ) id = Column(Integer, primary_key=True) key = Column(String(255)) value = Column(String(255)) instance_type_id = Column(Integer, ForeignKey('instance_types.id'), nullable=False) instance_type = relationship(InstanceTypes, backref="extra_specs", foreign_keys=instance_type_id, primaryjoin='and_(' 'InstanceTypeExtraSpecs.instance_type_id == InstanceTypes.id,' 'InstanceTypeExtraSpecs.deleted == 0)') class Cell(BASE, NovaBase): """Represents parent and child cells of this cell. Cells can have multiple parents and children, so there could be any number of entries with is_parent=True or False """ __tablename__ = 'cells' __table_args__ = (schema.UniqueConstraint( "name", "deleted", name="uniq_cells0name0deleted" ), ) id = Column(Integer, primary_key=True) # Name here is the 'short name' of a cell. For instance: 'child1' name = Column(String(255)) api_url = Column(String(255)) transport_url = Column(String(255), nullable=False) weight_offset = Column(Float(), default=0.0) weight_scale = Column(Float(), default=1.0) is_parent = Column(Boolean()) class AggregateHost(BASE, NovaBase): """Represents a host that is member of an aggregate.""" __tablename__ = 'aggregate_hosts' __table_args__ = (schema.UniqueConstraint( "host", "aggregate_id", "deleted", name="uniq_aggregate_hosts0host0aggregate_id0deleted" ), ) id = Column(Integer, primary_key=True, autoincrement=True) host = Column(String(255)) aggregate_id = Column(Integer, ForeignKey('aggregates.id'), nullable=False) class AggregateMetadata(BASE, NovaBase): """Represents a metadata key/value pair for an aggregate.""" __tablename__ = 'aggregate_metadata' __table_args__ = ( Index('aggregate_metadata_key_idx', 'key'), ) id = Column(Integer, primary_key=True) key = Column(String(255), nullable=False) value = Column(String(255), nullable=False) aggregate_id = Column(Integer, ForeignKey('aggregates.id'), nullable=False) class Aggregate(BASE, NovaBase): """Represents a cluster of hosts that exists in this zone.""" __tablename__ = 'aggregates' __table_args__ = () id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(255)) _hosts = relationship(AggregateHost, primaryjoin='and_(' 'Aggregate.id == AggregateHost.aggregate_id,' 'AggregateHost.deleted == 0,' 'Aggregate.deleted == 0)') _metadata = relationship(AggregateMetadata, primaryjoin='and_(' 'Aggregate.id == AggregateMetadata.aggregate_id,' 'AggregateMetadata.deleted == 0,' 'Aggregate.deleted == 0)') def _extra_keys(self): return ['hosts', 'metadetails', 'availability_zone'] @property def hosts(self): return [h.host for h in self._hosts] @property def metadetails(self): return dict([(m.key, m.value) for m in self._metadata]) @property def availability_zone(self): if 'availability_zone' not in self.metadetails: return None return self.metadetails['availability_zone'] class AgentBuild(BASE, NovaBase): """Represents an agent build.""" __tablename__ = 'agent_builds' __table_args__ = ( Index('agent_builds_hypervisor_os_arch_idx', 'hypervisor', 'os', 'architecture'), schema.UniqueConstraint("hypervisor", "os", "architecture", "deleted", name="uniq_agent_builds0hypervisor0os0architecture0deleted"), ) id = Column(Integer, primary_key=True) hypervisor = Column(String(255)) os = Column(String(255)) architecture = Column(String(255)) version = Column(String(255)) url = Column(String(255)) md5hash = Column(String(255)) class BandwidthUsage(BASE, NovaBase): """Cache for instance bandwidth usage data pulled from the hypervisor.""" __tablename__ = 'bw_usage_cache' __table_args__ = ( Index('bw_usage_cache_uuid_start_period_idx', 'uuid', 'start_period'), ) id = Column(Integer, primary_key=True, nullable=False) uuid = Column(String(36), nullable=True) mac = Column(String(255), nullable=True) start_period = Column(DateTime, nullable=False) last_refreshed = Column(DateTime, nullable=True) bw_in = Column(BigInteger, nullable=True) bw_out = Column(BigInteger, nullable=True) last_ctr_in = Column(BigInteger, nullable=True) last_ctr_out = Column(BigInteger, nullable=True) class VolumeUsage(BASE, NovaBase): """Cache for volume usage data pulled from the hypervisor.""" __tablename__ = 'volume_usage_cache' __table_args__ = () id = Column(Integer, primary_key=True, nullable=False) volume_id = Column(String(36), nullable=False) instance_uuid = Column(String(36)) project_id = Column(String(36)) user_id = Column(String(36)) availability_zone = Column(String(255)) tot_last_refreshed = Column(DateTime) tot_reads = Column(BigInteger, default=0) tot_read_bytes = Column(BigInteger, default=0) tot_writes = Column(BigInteger, default=0) tot_write_bytes = Column(BigInteger, default=0) curr_last_refreshed = Column(DateTime) curr_reads = Column(BigInteger, default=0) curr_read_bytes = Column(BigInteger, default=0) curr_writes = Column(BigInteger, default=0) curr_write_bytes = Column(BigInteger, default=0) class S3Image(BASE, NovaBase): """Compatibility layer for the S3 image service talking to Glance.""" __tablename__ = 's3_images' __table_args__ = () id = Column(Integer, primary_key=True, nullable=False, autoincrement=True) uuid = Column(String(36), nullable=False) class VolumeIdMapping(BASE, NovaBase): """Compatibility layer for the EC2 volume service.""" __tablename__ = 'volume_id_mappings' __table_args__ = () id = Column(Integer, primary_key=True, nullable=False, autoincrement=True) uuid = Column(String(36), nullable=False) class SnapshotIdMapping(BASE, NovaBase): """Compatibility layer for the EC2 snapshot service.""" __tablename__ = 'snapshot_id_mappings' __table_args__ = () id = Column(Integer, primary_key=True, nullable=False, autoincrement=True) uuid = Column(String(36), nullable=False) class InstanceFault(BASE, NovaBase): __tablename__ = 'instance_faults' __table_args__ = ( Index('instance_faults_host_idx', 'host'), Index('instance_faults_instance_uuid_deleted_created_at_idx', 'instance_uuid', 'deleted', 'created_at') ) id = Column(Integer, primary_key=True, nullable=False) instance_uuid = Column(String(36), ForeignKey('instances.uuid'), nullable=True) code = Column(Integer(), nullable=False) message = Column(String(255), nullable=True) details = Column(MediumText(), nullable=True) host = Column(String(255), nullable=True) class InstanceAction(BASE, NovaBase): """Track client actions on an instance. The intention is that there will only be one of these per user request. A lookup by (instance_uuid, request_id) should always return a single result. """ __tablename__ = 'instance_actions' __table_args__ = ( Index('instance_uuid_idx', 'instance_uuid'), Index('request_id_idx', 'request_id') ) id = Column(Integer, primary_key=True, nullable=False, autoincrement=True) action = Column(String(255), nullable=True) instance_uuid = Column(String(36), ForeignKey('instances.uuid'), nullable=True) request_id = Column(String(255), nullable=True) user_id = Column(String(255), nullable=True) project_id = Column(String(255), nullable=True) start_time = Column(DateTime, default=timeutils.utcnow, nullable=True) finish_time = Column(DateTime, nullable=True) message = Column(String(255), nullable=True) class InstanceActionEvent(BASE, NovaBase): """Track events that occur during an InstanceAction.""" __tablename__ = 'instance_actions_events' __table_args__ = () id = Column(Integer, primary_key=True, nullable=False, autoincrement=True) event = Column(String(255), nullable=True) action_id = Column(Integer, ForeignKey('instance_actions.id'), nullable=True) start_time = Column(DateTime, default=timeutils.utcnow, nullable=True) finish_time = Column(DateTime, nullable=True) result = Column(String(255), nullable=True) traceback = Column(Text, nullable=True) class InstanceIdMapping(BASE, NovaBase): """Compatibility layer for the EC2 instance service.""" __tablename__ = 'instance_id_mappings' __table_args__ = ( Index('ix_instance_id_mappings_uuid', 'uuid'), ) id = Column(Integer, primary_key=True, nullable=False, autoincrement=True) uuid = Column(String(36), nullable=False) class TaskLog(BASE, NovaBase): """Audit log for background periodic tasks.""" __tablename__ = 'task_log' __table_args__ = ( schema.UniqueConstraint( 'task_name', 'host', 'period_beginning', 'period_ending', name="uniq_task_log0task_name0host0period_beginning0period_ending" ), Index('ix_task_log_period_beginning', 'period_beginning'), Index('ix_task_log_host', 'host'), Index('ix_task_log_period_ending', 'period_ending'), ) id = Column(Integer, primary_key=True, nullable=False, autoincrement=True) task_name = Column(String(255), nullable=False) state = Column(String(255), nullable=False) host = Column(String(255), nullable=False) period_beginning = Column(DateTime, default=timeutils.utcnow, nullable=False) period_ending = Column(DateTime, default=timeutils.utcnow, nullable=False) message = Column(String(255), nullable=False) task_items = Column(Integer(), default=0, nullable=True) errors = Column(Integer(), default=0, nullable=True) class InstanceGroupMember(BASE, NovaBase): """Represents the members for an instance group.""" __tablename__ = 'instance_group_member' __table_args__ = ( Index('instance_group_member_instance_idx', 'instance_id'), ) id = Column(Integer, primary_key=True, nullable=False) instance_id = Column(String(255), nullable=True) group_id = Column(Integer, ForeignKey('instance_groups.id'), nullable=False) class InstanceGroupPolicy(BASE, NovaBase): """Represents the policy type for an instance group.""" __tablename__ = 'instance_group_policy' __table_args__ = ( Index('instance_group_policy_policy_idx', 'policy'), ) id = Column(Integer, primary_key=True, nullable=False) policy = Column(String(255), nullable=True) group_id = Column(Integer, ForeignKey('instance_groups.id'), nullable=False) class InstanceGroupMetadata(BASE, NovaBase): """Represents a key/value pair for an instance group.""" __tablename__ = 'instance_group_metadata' __table_args__ = ( Index('instance_group_metadata_key_idx', 'key'), ) id = Column(Integer, primary_key=True, nullable=False) key = Column(String(255), nullable=True) value = Column(String(255), nullable=True) group_id = Column(Integer, ForeignKey('instance_groups.id'), nullable=False) class InstanceGroup(BASE, NovaBase): """Represents an instance group. A group will maintain a collection of instances and the relationship between them. """ __tablename__ = 'instance_groups' __table_args__ = ( schema.UniqueConstraint("uuid", "deleted", name="uniq_instance_groups0uuid0deleted"), ) id = Column(Integer, primary_key=True, autoincrement=True) user_id = Column(String(255)) project_id = Column(String(255)) uuid = Column(String(36), nullable=False) name = Column(String(255)) _policies = relationship(InstanceGroupPolicy, primaryjoin='and_(' 'InstanceGroup.id == InstanceGroupPolicy.group_id,' 'InstanceGroupPolicy.deleted == 0,' 'InstanceGroup.deleted == 0)') _metadata = relationship(InstanceGroupMetadata, primaryjoin='and_(' 'InstanceGroup.id == InstanceGroupMetadata.group_id,' 'InstanceGroupMetadata.deleted == 0,' 'InstanceGroup.deleted == 0)') _members = relationship(InstanceGroupMember, primaryjoin='and_(' 'InstanceGroup.id == InstanceGroupMember.group_id,' 'InstanceGroupMember.deleted == 0,' 'InstanceGroup.deleted == 0)') @property def policies(self): return [p.policy for p in self._policies] @property def metadetails(self): return dict((m.key, m.value) for m in self._metadata) @property def members(self): return [m.instance_id for m in self._members]
# Copyright 2015 gRPC 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. """Run a group of subprocesses and then finish.""" from __future__ import print_function import logging import multiprocessing import os import platform import re import signal import subprocess import sys import tempfile import time import errno # cpu cost measurement measure_cpu_costs = False _DEFAULT_MAX_JOBS = 16 * multiprocessing.cpu_count() _MAX_RESULT_SIZE = 8192 # NOTE: If you change this, please make sure to test reviewing the # github PR with http://reviewable.io, which is known to add UTF-8 # characters to the PR description, which leak into the environment here # and cause failures. def strip_non_ascii_chars(s): return ''.join(c for c in s if ord(c) < 128) def sanitized_environment(env): sanitized = {} for key, value in env.items(): sanitized[strip_non_ascii_chars(key)] = strip_non_ascii_chars(value) return sanitized def platform_string(): if platform.system() == 'Windows': return 'windows' elif platform.system()[:7] == 'MSYS_NT': return 'windows' elif platform.system() == 'Darwin': return 'mac' elif platform.system() == 'Linux': return 'linux' else: return 'posix' # setup a signal handler so that signal.pause registers 'something' # when a child finishes # not using futures and threading to avoid a dependency on subprocess32 if platform_string() == 'windows': pass else: have_alarm = False def alarm_handler(unused_signum, unused_frame): global have_alarm have_alarm = False signal.signal(signal.SIGCHLD, lambda unused_signum, unused_frame: None) signal.signal(signal.SIGALRM, alarm_handler) _SUCCESS = object() _FAILURE = object() _RUNNING = object() _KILLED = object() _COLORS = { 'red': [ 31, 0 ], 'green': [ 32, 0 ], 'yellow': [ 33, 0 ], 'lightgray': [ 37, 0], 'gray': [ 30, 1 ], 'purple': [ 35, 0 ], 'cyan': [ 36, 0 ] } _BEGINNING_OF_LINE = '\x1b[0G' _CLEAR_LINE = '\x1b[2K' _TAG_COLOR = { 'FAILED': 'red', 'FLAKE': 'purple', 'TIMEOUT_FLAKE': 'purple', 'WARNING': 'yellow', 'TIMEOUT': 'red', 'PASSED': 'green', 'START': 'gray', 'WAITING': 'yellow', 'SUCCESS': 'green', 'IDLE': 'gray', 'SKIPPED': 'cyan' } _FORMAT = '%(asctime)-15s %(message)s' logging.basicConfig(level=logging.INFO, format=_FORMAT) def eintr_be_gone(fn): """Run fn until it doesn't stop because of EINTR""" while True: try: return fn() except IOError, e: if e.errno != errno.EINTR: raise def message(tag, msg, explanatory_text=None, do_newline=False): if message.old_tag == tag and message.old_msg == msg and not explanatory_text: return message.old_tag = tag message.old_msg = msg while True: try: if platform_string() == 'windows' or not sys.stdout.isatty(): if explanatory_text: logging.info(explanatory_text) logging.info('%s: %s', tag, msg) else: sys.stdout.write('%s%s%s\x1b[%d;%dm%s\x1b[0m: %s%s' % ( _BEGINNING_OF_LINE, _CLEAR_LINE, '\n%s' % explanatory_text if explanatory_text is not None else '', _COLORS[_TAG_COLOR[tag]][1], _COLORS[_TAG_COLOR[tag]][0], tag, msg, '\n' if do_newline or explanatory_text is not None else '')) sys.stdout.flush() return except IOError, e: if e.errno != errno.EINTR: raise message.old_tag = '' message.old_msg = '' def which(filename): if '/' in filename: return filename for path in os.environ['PATH'].split(os.pathsep): if os.path.exists(os.path.join(path, filename)): return os.path.join(path, filename) raise Exception('%s not found' % filename) class JobSpec(object): """Specifies what to run for a job.""" def __init__(self, cmdline, shortname=None, environ=None, cwd=None, shell=False, timeout_seconds=5*60, flake_retries=0, timeout_retries=0, kill_handler=None, cpu_cost=1.0, verbose_success=False): """ Arguments: cmdline: a list of arguments to pass as the command line environ: a dictionary of environment variables to set in the child process kill_handler: a handler that will be called whenever job.kill() is invoked cpu_cost: number of cores per second this job needs """ if environ is None: environ = {} self.cmdline = cmdline self.environ = environ self.shortname = cmdline[0] if shortname is None else shortname self.cwd = cwd self.shell = shell self.timeout_seconds = timeout_seconds self.flake_retries = flake_retries self.timeout_retries = timeout_retries self.kill_handler = kill_handler self.cpu_cost = cpu_cost self.verbose_success = verbose_success def identity(self): return '%r %r' % (self.cmdline, self.environ) def __hash__(self): return hash(self.identity()) def __cmp__(self, other): return self.identity() == other.identity() def __repr__(self): return 'JobSpec(shortname=%s, cmdline=%s)' % (self.shortname, self.cmdline) def __str__(self): return '%s: %s %s' % (self.shortname, ' '.join('%s=%s' % kv for kv in self.environ.items()), ' '.join(self.cmdline)) class JobResult(object): def __init__(self): self.state = 'UNKNOWN' self.returncode = -1 self.elapsed_time = 0 self.num_failures = 0 self.retries = 0 self.message = '' self.cpu_estimated = 1 self.cpu_measured = 0 def read_from_start(f): f.seek(0) return f.read() class Job(object): """Manages one job.""" def __init__(self, spec, newline_on_success, travis, add_env, quiet_success=False): self._spec = spec self._newline_on_success = newline_on_success self._travis = travis self._add_env = add_env.copy() self._retries = 0 self._timeout_retries = 0 self._suppress_failure_message = False self._quiet_success = quiet_success if not self._quiet_success: message('START', spec.shortname, do_newline=self._travis) self.result = JobResult() self.start() def GetSpec(self): return self._spec def start(self): self._tempfile = tempfile.TemporaryFile() env = dict(os.environ) env.update(self._spec.environ) env.update(self._add_env) env = sanitized_environment(env) self._start = time.time() cmdline = self._spec.cmdline # The Unix time command is finicky when used with MSBuild, so we don't use it # with jobs that run MSBuild. global measure_cpu_costs if measure_cpu_costs and not 'vsprojects\\build' in cmdline[0]: cmdline = ['time', '-p'] + cmdline else: measure_cpu_costs = False try_start = lambda: subprocess.Popen(args=cmdline, stderr=subprocess.STDOUT, stdout=self._tempfile, cwd=self._spec.cwd, shell=self._spec.shell, env=env) delay = 0.3 for i in range(0, 4): try: self._process = try_start() break except OSError: message('WARNING', 'Failed to start %s, retrying in %f seconds' % (self._spec.shortname, delay)) time.sleep(delay) delay *= 2 else: self._process = try_start() self._state = _RUNNING def state(self): """Poll current state of the job. Prints messages at completion.""" def stdout(self=self): stdout = read_from_start(self._tempfile) self.result.message = stdout[-_MAX_RESULT_SIZE:] return stdout if self._state == _RUNNING and self._process.poll() is not None: elapsed = time.time() - self._start self.result.elapsed_time = elapsed if self._process.returncode != 0: if self._retries < self._spec.flake_retries: message('FLAKE', '%s [ret=%d, pid=%d]' % ( self._spec.shortname, self._process.returncode, self._process.pid), stdout(), do_newline=True) self._retries += 1 self.result.num_failures += 1 self.result.retries = self._timeout_retries + self._retries self.start() else: self._state = _FAILURE if not self._suppress_failure_message: message('FAILED', '%s [ret=%d, pid=%d]' % ( self._spec.shortname, self._process.returncode, self._process.pid), stdout(), do_newline=True) self.result.state = 'FAILED' self.result.num_failures += 1 self.result.returncode = self._process.returncode else: self._state = _SUCCESS measurement = '' if measure_cpu_costs: m = re.search(r'real\s+([0-9.]+)\nuser\s+([0-9.]+)\nsys\s+([0-9.]+)', stdout()) real = float(m.group(1)) user = float(m.group(2)) sys = float(m.group(3)) if real > 0.5: cores = (user + sys) / real self.result.cpu_measured = float('%.01f' % cores) self.result.cpu_estimated = float('%.01f' % self._spec.cpu_cost) measurement = '; cpu_cost=%.01f; estimated=%.01f' % (self.result.cpu_measured, self.result.cpu_estimated) if not self._quiet_success: message('PASSED', '%s [time=%.1fsec; retries=%d:%d%s]' % ( self._spec.shortname, elapsed, self._retries, self._timeout_retries, measurement), stdout() if self._spec.verbose_success else None, do_newline=self._newline_on_success or self._travis) self.result.state = 'PASSED' elif (self._state == _RUNNING and self._spec.timeout_seconds is not None and time.time() - self._start > self._spec.timeout_seconds): if self._timeout_retries < self._spec.timeout_retries: message('TIMEOUT_FLAKE', '%s [pid=%d]' % (self._spec.shortname, self._process.pid), stdout(), do_newline=True) self._timeout_retries += 1 self.result.num_failures += 1 self.result.retries = self._timeout_retries + self._retries if self._spec.kill_handler: self._spec.kill_handler(self) self._process.terminate() self.start() else: message('TIMEOUT', '%s [pid=%d]' % (self._spec.shortname, self._process.pid), stdout(), do_newline=True) self.kill() self.result.state = 'TIMEOUT' self.result.num_failures += 1 return self._state def kill(self): if self._state == _RUNNING: self._state = _KILLED if self._spec.kill_handler: self._spec.kill_handler(self) self._process.terminate() def suppress_failure_message(self): self._suppress_failure_message = True class Jobset(object): """Manages one run of jobs.""" def __init__(self, check_cancelled, maxjobs, newline_on_success, travis, stop_on_failure, add_env, quiet_success, max_time): self._running = set() self._check_cancelled = check_cancelled self._cancelled = False self._failures = 0 self._completed = 0 self._maxjobs = maxjobs self._newline_on_success = newline_on_success self._travis = travis self._stop_on_failure = stop_on_failure self._add_env = add_env self._quiet_success = quiet_success self._max_time = max_time self.resultset = {} self._remaining = None self._start_time = time.time() def set_remaining(self, remaining): self._remaining = remaining def get_num_failures(self): return self._failures def cpu_cost(self): c = 0 for job in self._running: c += job._spec.cpu_cost return c def start(self, spec): """Start a job. Return True on success, False on failure.""" while True: if self._max_time > 0 and time.time() - self._start_time > self._max_time: skipped_job_result = JobResult() skipped_job_result.state = 'SKIPPED' message('SKIPPED', spec.shortname, do_newline=True) self.resultset[spec.shortname] = [skipped_job_result] return True if self.cancelled(): return False current_cpu_cost = self.cpu_cost() if current_cpu_cost == 0: break if current_cpu_cost + spec.cpu_cost <= self._maxjobs: break self.reap() if self.cancelled(): return False job = Job(spec, self._newline_on_success, self._travis, self._add_env, self._quiet_success) self._running.add(job) if job.GetSpec().shortname not in self.resultset: self.resultset[job.GetSpec().shortname] = [] return True def reap(self): """Collect the dead jobs.""" while self._running: dead = set() for job in self._running: st = eintr_be_gone(lambda: job.state()) if st == _RUNNING: continue if st == _FAILURE or st == _KILLED: self._failures += 1 if self._stop_on_failure: self._cancelled = True for job in self._running: job.kill() dead.add(job) break for job in dead: self._completed += 1 if not self._quiet_success or job.result.state != 'PASSED': self.resultset[job.GetSpec().shortname].append(job.result) self._running.remove(job) if dead: return if not self._travis and platform_string() != 'windows': rstr = '' if self._remaining is None else '%d queued, ' % self._remaining if self._remaining is not None and self._completed > 0: now = time.time() sofar = now - self._start_time remaining = sofar / self._completed * (self._remaining + len(self._running)) rstr = 'ETA %.1f sec; %s' % (remaining, rstr) message('WAITING', '%s%d jobs running, %d complete, %d failed' % ( rstr, len(self._running), self._completed, self._failures)) if platform_string() == 'windows': time.sleep(0.1) else: global have_alarm if not have_alarm: have_alarm = True signal.alarm(10) signal.pause() def cancelled(self): """Poll for cancellation.""" if self._cancelled: return True if not self._check_cancelled(): return False for job in self._running: job.kill() self._cancelled = True return True def finish(self): while self._running: if self.cancelled(): pass # poll cancellation self.reap() return not self.cancelled() and self._failures == 0 def _never_cancelled(): return False def tag_remaining(xs): staging = [] for x in xs: staging.append(x) if len(staging) > 5000: yield (staging.pop(0), None) n = len(staging) for i, x in enumerate(staging): yield (x, n - i - 1) def run(cmdlines, check_cancelled=_never_cancelled, maxjobs=None, newline_on_success=False, travis=False, infinite_runs=False, stop_on_failure=False, add_env={}, skip_jobs=False, quiet_success=False, max_time=-1): if skip_jobs: resultset = {} skipped_job_result = JobResult() skipped_job_result.state = 'SKIPPED' for job in cmdlines: message('SKIPPED', job.shortname, do_newline=True) resultset[job.shortname] = [skipped_job_result] return 0, resultset js = Jobset(check_cancelled, maxjobs if maxjobs is not None else _DEFAULT_MAX_JOBS, newline_on_success, travis, stop_on_failure, add_env, quiet_success, max_time) for cmdline, remaining in tag_remaining(cmdlines): if not js.start(cmdline): break if remaining is not None: js.set_remaining(remaining) js.finish() return js.get_num_failures(), js.resultset
"""Metrics to assess performance on classification task given scores Functions named as ``*_score`` return a scalar value to maximize: the higher the better Function named as ``*_error`` or ``*_loss`` return a scalar value to minimize: the lower the better """ # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Mathieu Blondel <mathieu@mblondel.org> # Olivier Grisel <olivier.grisel@ensta.org> # Arnaud Joly <a.joly@ulg.ac.be> # Jochen Wersdorfer <jochen@wersdoerfer.de> # Lars Buitinck # Joel Nothman <joel.nothman@gmail.com> # Noel Dawe <noel@dawe.me> # License: BSD 3 clause from __future__ import division import warnings import numpy as np from scipy.sparse import csr_matrix from ..utils import assert_all_finite from ..utils import check_consistent_length from ..utils import column_or_1d, check_array from ..utils.multiclass import type_of_target from ..utils.fixes import isclose from ..utils.fixes import bincount from ..utils.fixes import array_equal from ..utils.stats import rankdata from ..utils.sparsefuncs import count_nonzero from ..exceptions import UndefinedMetricWarning from .base import _average_binary_score def auc(x, y, reorder=False): """Compute Area Under the Curve (AUC) using the trapezoidal rule This is a general function, given points on a curve. For computing the area under the ROC-curve, see :func:`roc_auc_score`. Parameters ---------- x : array, shape = [n] x coordinates. y : array, shape = [n] y coordinates. reorder : boolean, optional (default=False) If True, assume that the curve is ascending in the case of ties, as for an ROC curve. If the curve is non-ascending, the result will be wrong. Returns ------- auc : float Examples -------- >>> import numpy as np >>> from sklearn import metrics >>> y = np.array([1, 1, 2, 2]) >>> pred = np.array([0.1, 0.4, 0.35, 0.8]) >>> fpr, tpr, thresholds = metrics.roc_curve(y, pred, pos_label=2) >>> metrics.auc(fpr, tpr) 0.75 See also -------- roc_auc_score : Computes the area under the ROC curve precision_recall_curve : Compute precision-recall pairs for different probability thresholds """ check_consistent_length(x, y) x = column_or_1d(x) y = column_or_1d(y) if x.shape[0] < 2: raise ValueError('At least 2 points are needed to compute' ' area under curve, but x.shape = %s' % x.shape) direction = 1 if reorder: # reorder the data points according to the x axis and using y to # break ties order = np.lexsort((y, x)) x, y = x[order], y[order] else: dx = np.diff(x) if np.any(dx < 0): if np.all(dx <= 0): direction = -1 else: raise ValueError("Reordering is not turned on, and " "the x array is not increasing: %s" % x) area = direction * np.trapz(y, x) if isinstance(area, np.memmap): # Reductions such as .sum used internally in np.trapz do not return a # scalar by default for numpy.memmap instances contrary to # regular numpy.ndarray instances. area = area.dtype.type(area) return area def average_precision_score(y_true, y_score, average="macro", sample_weight=None): """Compute average precision (AP) from prediction scores This score corresponds to the area under the precision-recall curve. Note: this implementation is restricted to the binary classification task or multilabel classification task. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. Parameters ---------- y_true : array, shape = [n_samples] or [n_samples, n_classes] True binary labels in binary label indicators. y_score : array, shape = [n_samples] or [n_samples, n_classes] Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). average : string, [None, 'micro', 'macro' (default), 'samples', 'weighted'] If ``None``, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'micro'``: Calculate metrics globally by considering each element of the label indicator matrix as a label. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average, weighted by support (the number of true instances for each label). ``'samples'``: Calculate metrics for each instance, and find their average. sample_weight : array-like of shape = [n_samples], optional Sample weights. Returns ------- average_precision : float References ---------- .. [1] `Wikipedia entry for the Average precision <https://en.wikipedia.org/wiki/Average_precision>`_ See also -------- roc_auc_score : Area under the ROC curve precision_recall_curve : Compute precision-recall pairs for different probability thresholds Examples -------- >>> import numpy as np >>> from sklearn.metrics import average_precision_score >>> y_true = np.array([0, 0, 1, 1]) >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) >>> average_precision_score(y_true, y_scores) # doctest: +ELLIPSIS 0.79... """ def _binary_average_precision(y_true, y_score, sample_weight=None): precision, recall, thresholds = precision_recall_curve( y_true, y_score, sample_weight=sample_weight) return auc(recall, precision) return _average_binary_score(_binary_average_precision, y_true, y_score, average, sample_weight=sample_weight) def roc_auc_score(y_true, y_score, average="macro", sample_weight=None): """Compute Area Under the Curve (AUC) from prediction scores Note: this implementation is restricted to the binary classification task or multilabel classification task in label indicator format. Read more in the :ref:`User Guide <roc_metrics>`. Parameters ---------- y_true : array, shape = [n_samples] or [n_samples, n_classes] True binary labels in binary label indicators. y_score : array, shape = [n_samples] or [n_samples, n_classes] Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). average : string, [None, 'micro', 'macro' (default), 'samples', 'weighted'] If ``None``, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'micro'``: Calculate metrics globally by considering each element of the label indicator matrix as a label. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average, weighted by support (the number of true instances for each label). ``'samples'``: Calculate metrics for each instance, and find their average. sample_weight : array-like of shape = [n_samples], optional Sample weights. Returns ------- auc : float References ---------- .. [1] `Wikipedia entry for the Receiver operating characteristic <https://en.wikipedia.org/wiki/Receiver_operating_characteristic>`_ See also -------- average_precision_score : Area under the precision-recall curve roc_curve : Compute Receiver operating characteristic (ROC) Examples -------- >>> import numpy as np >>> from sklearn.metrics import roc_auc_score >>> y_true = np.array([0, 0, 1, 1]) >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) >>> roc_auc_score(y_true, y_scores) 0.75 """ def _binary_roc_auc_score(y_true, y_score, sample_weight=None): if len(np.unique(y_true)) != 2: raise ValueError("Only one class present in y_true. ROC AUC score " "is not defined in that case.") fpr, tpr, tresholds = roc_curve(y_true, y_score, sample_weight=sample_weight) return auc(fpr, tpr, reorder=True) return _average_binary_score( _binary_roc_auc_score, y_true, y_score, average, sample_weight=sample_weight) def _binary_clf_curve(y_true, y_score, pos_label=None, sample_weight=None): """Calculate true and false positives per binary classification threshold. Parameters ---------- y_true : array, shape = [n_samples] True targets of binary classification y_score : array, shape = [n_samples] Estimated probabilities or decision function pos_label : int, optional (default=None) The label of the positive class sample_weight : array-like of shape = [n_samples], optional Sample weights. Returns ------- fps : array, shape = [n_thresholds] A count of false positives, at index i being the number of negative samples assigned a score >= thresholds[i]. The total number of negative samples is equal to fps[-1] (thus true negatives are given by fps[-1] - fps). tps : array, shape = [n_thresholds <= len(np.unique(y_score))] An increasing count of true positives, at index i being the number of positive samples assigned a score >= thresholds[i]. The total number of positive samples is equal to tps[-1] (thus false negatives are given by tps[-1] - tps). thresholds : array, shape = [n_thresholds] Decreasing score values. """ check_consistent_length(y_true, y_score) y_true = column_or_1d(y_true) y_score = column_or_1d(y_score) assert_all_finite(y_true) assert_all_finite(y_score) if sample_weight is not None: sample_weight = column_or_1d(sample_weight) # ensure binary classification if pos_label is not specified classes = np.unique(y_true) if (pos_label is None and not (array_equal(classes, [0, 1]) or array_equal(classes, [-1, 1]) or array_equal(classes, [0]) or array_equal(classes, [-1]) or array_equal(classes, [1]))): raise ValueError("Data is not binary and pos_label is not specified") elif pos_label is None: pos_label = 1. # make y_true a boolean vector y_true = (y_true == pos_label) # sort scores and corresponding truth values desc_score_indices = np.argsort(y_score, kind="mergesort")[::-1] y_score = y_score[desc_score_indices] y_true = y_true[desc_score_indices] if sample_weight is not None: weight = sample_weight[desc_score_indices] else: weight = 1. # y_score typically has many tied values. Here we extract # the indices associated with the distinct values. We also # concatenate a value for the end of the curve. # We need to use isclose to avoid spurious repeated thresholds # stemming from floating point roundoff errors. distinct_value_indices = np.where(np.logical_not(isclose( np.diff(y_score), 0)))[0] threshold_idxs = np.r_[distinct_value_indices, y_true.size - 1] # accumulate the true positives with decreasing threshold tps = (y_true * weight).cumsum()[threshold_idxs] if sample_weight is not None: fps = weight.cumsum()[threshold_idxs] - tps else: fps = 1 + threshold_idxs - tps return fps, tps, y_score[threshold_idxs] def precision_recall_curve(y_true, probas_pred, pos_label=None, sample_weight=None): """Compute precision-recall pairs for different probability thresholds Note: this implementation is restricted to the binary classification task. The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of true positives and ``fp`` the number of false positives. The precision is intuitively the ability of the classifier not to label as positive a sample that is negative. The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of true positives and ``fn`` the number of false negatives. The recall is intuitively the ability of the classifier to find all the positive samples. The last precision and recall values are 1. and 0. respectively and do not have a corresponding threshold. This ensures that the graph starts on the x axis. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. Parameters ---------- y_true : array, shape = [n_samples] True targets of binary classification in range {-1, 1} or {0, 1}. probas_pred : array, shape = [n_samples] Estimated probabilities or decision function. pos_label : int, optional (default=None) The label of the positive class sample_weight : array-like of shape = [n_samples], optional Sample weights. Returns ------- precision : array, shape = [n_thresholds + 1] Precision values such that element i is the precision of predictions with score >= thresholds[i] and the last element is 1. recall : array, shape = [n_thresholds + 1] Decreasing recall values such that element i is the recall of predictions with score >= thresholds[i] and the last element is 0. thresholds : array, shape = [n_thresholds <= len(np.unique(probas_pred))] Increasing thresholds on the decision function used to compute precision and recall. Examples -------- >>> import numpy as np >>> from sklearn.metrics import precision_recall_curve >>> y_true = np.array([0, 0, 1, 1]) >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) >>> precision, recall, thresholds = precision_recall_curve( ... y_true, y_scores) >>> precision # doctest: +ELLIPSIS array([ 0.66..., 0.5 , 1. , 1. ]) >>> recall array([ 1. , 0.5, 0.5, 0. ]) >>> thresholds array([ 0.35, 0.4 , 0.8 ]) """ fps, tps, thresholds = _binary_clf_curve(y_true, probas_pred, pos_label=pos_label, sample_weight=sample_weight) precision = tps / (tps + fps) recall = tps / tps[-1] # stop when full recall attained # and reverse the outputs so recall is decreasing last_ind = tps.searchsorted(tps[-1]) sl = slice(last_ind, None, -1) return np.r_[precision[sl], 1], np.r_[recall[sl], 0], thresholds[sl] def roc_curve(y_true, y_score, pos_label=None, sample_weight=None, drop_intermediate=True): """Compute Receiver operating characteristic (ROC) Note: this implementation is restricted to the binary classification task. Read more in the :ref:`User Guide <roc_metrics>`. Parameters ---------- y_true : array, shape = [n_samples] True binary labels in range {0, 1} or {-1, 1}. If labels are not binary, pos_label should be explicitly given. y_score : array, shape = [n_samples] Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). pos_label : int Label considered as positive and others are considered negative. sample_weight : array-like of shape = [n_samples], optional Sample weights. drop_intermediate : boolean, optional (default=True) Whether to drop some suboptimal thresholds which would not appear on a plotted ROC curve. This is useful in order to create lighter ROC curves. .. versionadded:: 0.17 parameter *drop_intermediate*. Returns ------- fpr : array, shape = [>2] Increasing false positive rates such that element i is the false positive rate of predictions with score >= thresholds[i]. tpr : array, shape = [>2] Increasing true positive rates such that element i is the true positive rate of predictions with score >= thresholds[i]. thresholds : array, shape = [n_thresholds] Decreasing thresholds on the decision function used to compute fpr and tpr. `thresholds[0]` represents no instances being predicted and is arbitrarily set to `max(y_score) + 1`. See also -------- roc_auc_score : Compute Area Under the Curve (AUC) from prediction scores Notes ----- Since the thresholds are sorted from low to high values, they are reversed upon returning them to ensure they correspond to both ``fpr`` and ``tpr``, which are sorted in reversed order during their calculation. References ---------- .. [1] `Wikipedia entry for the Receiver operating characteristic <https://en.wikipedia.org/wiki/Receiver_operating_characteristic>`_ Examples -------- >>> import numpy as np >>> from sklearn import metrics >>> y = np.array([1, 1, 2, 2]) >>> scores = np.array([0.1, 0.4, 0.35, 0.8]) >>> fpr, tpr, thresholds = metrics.roc_curve(y, scores, pos_label=2) >>> fpr array([ 0. , 0.5, 0.5, 1. ]) >>> tpr array([ 0.5, 0.5, 1. , 1. ]) >>> thresholds array([ 0.8 , 0.4 , 0.35, 0.1 ]) """ fps, tps, thresholds = _binary_clf_curve( y_true, y_score, pos_label=pos_label, sample_weight=sample_weight) # Attempt to drop thresholds corresponding to points in between and # collinear with other points. These are always suboptimal and do not # appear on a plotted ROC curve (and thus do not affect the AUC). # Here np.diff(_, 2) is used as a "second derivative" to tell if there # is a corner at the point. Both fps and tps must be tested to handle # thresholds with multiple data points (which are combined in # _binary_clf_curve). This keeps all cases where the point should be kept, # but does not drop more complicated cases like fps = [1, 3, 7], # tps = [1, 2, 4]; there is no harm in keeping too many thresholds. if drop_intermediate and len(fps) > 2: optimal_idxs = np.where(np.r_[True, np.logical_or(np.diff(fps, 2), np.diff(tps, 2)), True])[0] fps = fps[optimal_idxs] tps = tps[optimal_idxs] thresholds = thresholds[optimal_idxs] if tps.size == 0 or fps[0] != 0: # Add an extra threshold position if necessary tps = np.r_[0, tps] fps = np.r_[0, fps] thresholds = np.r_[thresholds[0] + 1, thresholds] if fps[-1] <= 0: warnings.warn("No negative samples in y_true, " "false positive value should be meaningless", UndefinedMetricWarning) fpr = np.repeat(np.nan, fps.shape) else: fpr = fps / fps[-1] if tps[-1] <= 0: warnings.warn("No positive samples in y_true, " "true positive value should be meaningless", UndefinedMetricWarning) tpr = np.repeat(np.nan, tps.shape) else: tpr = tps / tps[-1] return fpr, tpr, thresholds def label_ranking_average_precision_score(y_true, y_score): """Compute ranking-based average precision Label ranking average precision (LRAP) is the average over each ground truth label assigned to each sample, of the ratio of true vs. total labels with lower score. This metric is used in multilabel ranking problem, where the goal is to give better rank to the labels associated to each sample. The obtained score is always strictly greater than 0 and the best value is 1. Read more in the :ref:`User Guide <label_ranking_average_precision>`. Parameters ---------- y_true : array or sparse matrix, shape = [n_samples, n_labels] True binary labels in binary indicator format. y_score : array, shape = [n_samples, n_labels] Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). Returns ------- score : float Examples -------- >>> import numpy as np >>> from sklearn.metrics import label_ranking_average_precision_score >>> y_true = np.array([[1, 0, 0], [0, 0, 1]]) >>> y_score = np.array([[0.75, 0.5, 1], [1, 0.2, 0.1]]) >>> label_ranking_average_precision_score(y_true, y_score) \ # doctest: +ELLIPSIS 0.416... """ check_consistent_length(y_true, y_score) y_true = check_array(y_true, ensure_2d=False) y_score = check_array(y_score, ensure_2d=False) if y_true.shape != y_score.shape: raise ValueError("y_true and y_score have different shape") # Handle badly formated array and the degenerate case with one label y_type = type_of_target(y_true) if (y_type != "multilabel-indicator" and not (y_type == "binary" and y_true.ndim == 2)): raise ValueError("{0} format is not supported".format(y_type)) y_true = csr_matrix(y_true) y_score = -y_score n_samples, n_labels = y_true.shape out = 0. for i, (start, stop) in enumerate(zip(y_true.indptr, y_true.indptr[1:])): relevant = y_true.indices[start:stop] if (relevant.size == 0 or relevant.size == n_labels): # If all labels are relevant or unrelevant, the score is also # equal to 1. The label ranking has no meaning. out += 1. continue scores_i = y_score[i] rank = rankdata(scores_i, 'max')[relevant] L = rankdata(scores_i[relevant], 'max') out += (L / rank).mean() return out / n_samples def coverage_error(y_true, y_score, sample_weight=None): """Coverage error measure Compute how far we need to go through the ranked scores to cover all true labels. The best value is equal to the average number of labels in ``y_true`` per sample. Ties in ``y_scores`` are broken by giving maximal rank that would have been assigned to all tied values. Read more in the :ref:`User Guide <coverage_error>`. Parameters ---------- y_true : array, shape = [n_samples, n_labels] True binary labels in binary indicator format. y_score : array, shape = [n_samples, n_labels] Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). sample_weight : array-like of shape = [n_samples], optional Sample weights. Returns ------- coverage_error : float References ---------- .. [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010). Mining multi-label data. In Data mining and knowledge discovery handbook (pp. 667-685). Springer US. """ y_true = check_array(y_true, ensure_2d=False) y_score = check_array(y_score, ensure_2d=False) check_consistent_length(y_true, y_score, sample_weight) y_type = type_of_target(y_true) if y_type != "multilabel-indicator": raise ValueError("{0} format is not supported".format(y_type)) if y_true.shape != y_score.shape: raise ValueError("y_true and y_score have different shape") y_score_mask = np.ma.masked_array(y_score, mask=np.logical_not(y_true)) y_min_relevant = y_score_mask.min(axis=1).reshape((-1, 1)) coverage = (y_score >= y_min_relevant).sum(axis=1) coverage = coverage.filled(0) return np.average(coverage, weights=sample_weight) def label_ranking_loss(y_true, y_score, sample_weight=None): """Compute Ranking loss measure Compute the average number of label pairs that are incorrectly ordered given y_score weighted by the size of the label set and the number of labels not in the label set. This is similar to the error set size, but weighted by the number of relevant and irrelevant labels. The best performance is achieved with a ranking loss of zero. Read more in the :ref:`User Guide <label_ranking_loss>`. .. versionadded:: 0.17 A function *label_ranking_loss* Parameters ---------- y_true : array or sparse matrix, shape = [n_samples, n_labels] True binary labels in binary indicator format. y_score : array, shape = [n_samples, n_labels] Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). sample_weight : array-like of shape = [n_samples], optional Sample weights. Returns ------- loss : float References ---------- .. [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010). Mining multi-label data. In Data mining and knowledge discovery handbook (pp. 667-685). Springer US. """ y_true = check_array(y_true, ensure_2d=False, accept_sparse='csr') y_score = check_array(y_score, ensure_2d=False) check_consistent_length(y_true, y_score, sample_weight) y_type = type_of_target(y_true) if y_type not in ("multilabel-indicator",): raise ValueError("{0} format is not supported".format(y_type)) if y_true.shape != y_score.shape: raise ValueError("y_true and y_score have different shape") n_samples, n_labels = y_true.shape y_true = csr_matrix(y_true) loss = np.zeros(n_samples) for i, (start, stop) in enumerate(zip(y_true.indptr, y_true.indptr[1:])): # Sort and bin the label scores unique_scores, unique_inverse = np.unique(y_score[i], return_inverse=True) true_at_reversed_rank = bincount( unique_inverse[y_true.indices[start:stop]], minlength=len(unique_scores)) all_at_reversed_rank = bincount(unique_inverse, minlength=len(unique_scores)) false_at_reversed_rank = all_at_reversed_rank - true_at_reversed_rank # if the scores are ordered, it's possible to count the number of # incorrectly ordered paires in linear time by cumulatively counting # how many false labels of a given score have a score higher than the # accumulated true labels with lower score. loss[i] = np.dot(true_at_reversed_rank.cumsum(), false_at_reversed_rank) n_positives = count_nonzero(y_true, axis=1) with np.errstate(divide="ignore", invalid="ignore"): loss /= ((n_labels - n_positives) * n_positives) # When there is no positive or no negative labels, those values should # be consider as correct, i.e. the ranking doesn't matter. loss[np.logical_or(n_positives == 0, n_positives == n_labels)] = 0. return np.average(loss, weights=sample_weight)
from blocks.extensions import SimpleExtension from matplotlib import pylab as plt from copy import deepcopy import numpy as np class VariableModifier(SimpleExtension): def __init__(self, parameter): self.parameter = parameter kwargs = dict() kwargs.setdefault("after_batch", True) self.initial_value = np.copy(parameter.get_value()) super(VariableModifier, self).__init__(**kwargs) def compute_value(self, iterations): pass def do(self, which_callback, *args): iterations_done = self.main_loop.log.status['iterations_done'] new_value = self.compute_value(iterations_done) self.parameter.set_value(new_value) if self.parameter.name: self.main_loop.log.current_row["shared_variable_%s"%self.parameter.name] = new_value def debug_plot(self, max_iter=10000): x = np.linspace(0, max_iter, 10000) y = [self.compute_value(xx) for xx in x] plt.plot(x, y) plt.title(str(self)) plt.xlabel("iterations") plt.ylabel("variable value") plt.show() class ExponentialDecay(VariableModifier): """ Modifies shared variable according to function v_0*e^(-n*exp_decay) Parameters --------- parameter: shared float variable updated by modifer exp_decay: float parameter which controls decay rate """ def __init__(self, parameter, exp_decay): self.exp_decay = exp_decay super(ExponentialDecay, self).__init__(parameter) def compute_value(self, iterations): val = self.initial_value * np.exp(-iterations * self.exp_decay) return np.cast[np.float32](val) class StepDecay(VariableModifier): """ Modifies shared variable according to function v_0*multiplier^p where p is the number of steps passed in the current iteration Parameters --------- parameter: shared float variable updated by modifer steps: list intervals to decrease the decay rate on multiplier: float rate to step the shared variable """ def __init__(self, parameter, steps, multiplier=0.5): self.steps = steps self.multiplier = multiplier super(StepDecay, self).__init__(parameter) def compute_value(self, iterations): c = np.copy(self.initial_value) for s in self.steps: if iterations >= s: c *= self.multiplier return np.cast[np.float32](c) class InverseDecay(VariableModifier): """ Modifies shared variable according to function v_0*(1.0+inv_decay*n)^-power Parameters --------- parameter: shared float variable updated by modifer inv_decay: float parameter which controls decay rate power: float parameter which controls decay rate """ def __init__(self, parameter, inv_decay, power): self.inv_decay = inv_decay self.power = power super(InverseDecay, self).__init__(parameter) def compute_value(self, iterations): val = self.initial_value*(1.0+self.inv_decay*iterations)**-self.power return np.cast[np.float32](val) class PolynomialDecay(VariableModifier): """ Modifies shared variable according to function v_0*(1.0-n/max_iter)^power Parameters --------- parameter: shared float variable updated by modifer max_iter: float parameter which controls when shared variable should equal 0 power: float parameter which controls decay rate """ def __init__(self, parameter, max_iter, power): self.max_iter = max_iter self.power = power super(PolynomialDecay, self).__init__(parameter) def compute_value(self, iterations): if iterations >= self.max_iter: val = 0.0 else: val = self.initial_value*(1.0 - (iterations/np.float32(self.max_iter)))**self.power return np.cast[np.float32](val) class SigmoidDecay(VariableModifier): """ Modifies shared variable according to function v_0-v_0*(1.0/(1.0+e^(-sig_decay*n-step_size))) Parameters --------- parameter: shared float variable updated by modifer sig_decay: float parameter which controls decay rate step_size: float parameter which controls inflection point of decay rate """ def __init__(self, parameter, sig_decay, step_size): self.sig_decay = sig_decay self.step_size = step_size super(SigmoidDecay, self).__init__(parameter) def compute_value(self, iterations): val = self.initial_value - self.initial_value * (1.0/(1.0 + np.exp(-self.sig_decay * (iterations - self.step_size)))) return np.cast[np.float32](val) class LinearDecay(VariableModifier): """ Modifies shared variable according to function v_0-(rate*n) Parameters --------- parameter: shared float variable updated by modifer rate: float parameter which controls decay rate clip_at_zero: boolean if set to true, shared variable will never decrease to a value below 0.0 """ def __init__(self, parameter, rate, clip_at_zero=True): self.rate = rate self.clip_at_zero = clip_at_zero super(LinearDecay, self).__init__(parameter) def compute_value(self, iterations): val = self.initial_value-(self.rate*iterations) if self.clip_at_zero: val = max(0.0, val) return np.cast[np.float32](val) class ComposeDecay(VariableModifier): """ Modifies shared variable according to the composition of variable modifiers Each modifier's initial value is set to the final value of the predecessor modifier The first modifier is used from iteration=0 to iteration=steps[0] Parameters --------- parameter: shared float variable updated by modifer variable_modifiers: list sequence of shared variable modifiers steps: list intervals to change which modifier is used on a given iteration """ def __init__(self, variable_modifiers, steps): self.variable_modifiers = deepcopy(variable_modifiers) self.steps = steps assert (len(steps) == (len(self.variable_modifiers)-1)) assert all(self.variable_modifiers[0].parameter == variable_modifier.parameter for variable_modifier in self.variable_modifiers[1:]) deltas = [steps[0]] for i in xrange(1, len(steps)): deltas.append(steps[i]-steps[i-1]) for i in xrange(1, len(self.variable_modifiers)): self.variable_modifiers[i].initial_value = self.variable_modifiers[i-1].compute_value(deltas[i-1]) super(ComposeDecay, self).__init__(variable_modifiers[0].parameter) def compute_value(self, iterations): step_index = 0 for step in self.steps: if step > iterations: break step_index += 1 if step_index > 0: return self.variable_modifiers[step_index].compute_value(iterations-self.steps[step_index-1]) return self.variable_modifiers[step_index].compute_value(iterations)
from copy import deepcopy from time import sleep from property_caching import ( cached_property, clear_property_cache, set_property_cache) from six import iteritems, itervalues from pycloudflare.exceptions import SSLUnavailable from pycloudflare.services import ( CloudFlareHostService, CloudFlareService, cloudflare_paginated_results) from pycloudflare.utils import translate_errors class User(object): def __init__(self, email, api_key): self.email = email self._service = self.get_service(api_key, email) @classmethod def get_host_service(cls): return CloudFlareHostService() @classmethod def get_service(cls, api_key, email): return CloudFlareService(api_key, email) @classmethod def get_or_create(cls, email, password, username=None, unique_id=None): service = cls.get_host_service() data = service.user_create(email, password, username, unique_id) return cls.create_from_host_api_response(data) @classmethod def get(cls, email=None, unique_id=None): service = cls.get_host_service() data = service.user_lookup(email=email, unique_id=unique_id) return cls.create_from_host_api_response(data) @classmethod def create_from_host_api_response(cls, data): user = User(data['cloudflare_email'], data['user_api_key']) set_property_cache(user, '_host_api_data', data) return user @cached_property def _host_api_data(self): service = self.get_host_service() return service.user_lookup(email=self.email) @property def user_key(self): return self._host_api_data['user_key'] @cached_property def zones(self): return list(self.iter_zones()) def iter_zones(self): for zone in cloudflare_paginated_results(self._service.get_zones): yield Zone(self, zone) def get_zone_by_name(self, name): zone = self._service.get_zone_by_name(name) return Zone(self, zone) def create_host_zone(self, name, jump_start=False): host_service = self.get_host_service() host_service.full_zone_set(name, self.user_key, jump_start) zone = self.get_zone_by_name(name) # Zone created by using Host API contains some garbage records. # We should remove them before creating our owns. for record in zone.iter_records(): record.delete() return zone def create_cname_zone(self, zone_name, subdomains, resolve_to): host_service = self.get_host_service() result = host_service.zone_set( zone_name, self.user_key, subdomains, resolve_to) return result def create_zone(self, name, jump_start=False, organization=None): zone = self._service.create_zone(name=name, jump_start=jump_start, organization=organization) return Zone(self, zone) def __repr__(self): return 'User<%s>' % self.email class Zone(object): def __init__(self, user, data): self.user = user self._service = user._service self._data = data def __getattr__(self, name): if name in self._data: return self._data[name] raise AttributeError() def delete(self): self._service.delete_zone(self.id) clear_property_cache(self.user, 'zones') @cached_property def settings(self): return ZoneSettings(self) def iter_records(self): for record in cloudflare_paginated_results( self._service.get_dns_records, args=(self.id,)): yield Record(self, record) @cached_property def records(self): by_name = {} for record in self.iter_records(): by_name.setdefault(record.name, []).append(record) for value in itervalues(by_name): value.sort(key=lambda r: (r.type, r.content)) return by_name def create_record(self, name, record_type, content=None, ttl=1, proxied=False, **kwargs): data = { 'name': name, 'type': record_type, 'ttl': ttl, 'proxied': proxied, } if content: data['content'] = content if record_type == 'MX': data['priority'] = kwargs['priority'] elif record_type == 'SRV': data['data'] = { 'name': name, 'service': kwargs['service'], 'proto': kwargs['protocol'], 'priority': kwargs['priority'], 'weight': kwargs['weight'], 'port': kwargs['port'], 'target': kwargs['target'], } record = self._service.create_dns_record(self.id, data) clear_property_cache(self, 'records') return Record(self, record) def iter_page_rules(self): for page_rule in cloudflare_paginated_results( self._service.get_page_rules, args=(self.id,)): yield PageRule(self, page_rule) @cached_property def page_rules(self): return sorted(self.iter_page_rules(), key=lambda pr: pr.priority) def create_page_rule(self, targets=None, url_matches=None, actions=(), priority=1, status='active'): """ Create a PageRule. Either the targets can be explicitly spelled out (the JSON dictionary in the CF API), or the convenience parameter url_matches can be used to generate the targets parameter. The other parameters map directly to the CF API. """ if url_matches: if targets: raise ValueError( 'Only one of targets and url_matches can be specified') targets = [{ 'target': 'url', 'constraint': { 'operator': 'matches', 'value': url_matches, }, }] data = { 'targets': targets, 'actions': actions, 'priority': priority, 'status': status, } page_rule = self._service.create_page_rule(self.id, data) clear_property_cache(self, 'page_rules') return PageRule(self, page_rule) def purge_cache(self, files=None, tags=None, hosts=None): self._service.purge_cache( self.id, files=files, tags=tags, hosts=hosts) @translate_errors(1001, SSLUnavailable) def get_ssl_verification_info(self): return self._service.get_ssl_verification_info(self.id) def re_verify(self): """Toggle Universal SSL off and on, to trigger re-verification. This will leave SSL enabled, regardless of the previous state. """ self._service.update_ssl_universal_settings( self.id, {'enabled': False}) # This is asynchronous on CF's side. So probe until it seems to have # been deprovisioned, and then wait a little longer to be safe. for i in range(5): sleep(1) try: self.get_ssl_verification_info() except SSLUnavailable: sleep(1) break self._service.update_ssl_universal_settings( self.id, {'enabled': True}) def __repr__(self): return 'Zone<%s>' % self.name class ZoneSettings(object): def __init__(self, zone): self.zone = zone self._service = zone._service self._get_settings() self._updates = {} def _get_settings(self): self._settings = {} for setting in self._service.get_zone_settings(self.zone.id): self._settings[setting['id']] = setting def __getattr__(self, name): if name in self._updates: return self._updates[name] if name in self._settings: return self._settings[name]['value'] raise AttributeError() def __setattr__(self, name, value): if name in ('zone', '_service', '_settings', '_updates'): return super(ZoneSettings, self).__setattr__(name, value) if name not in self._settings: raise AttributeError('Not a valid setting') if not self._settings[name]['editable']: raise ValueError('Not an editeable setting') self._updates[name] = value def save(self): if not self._updates: return items = [{'id': name, 'value': value} for name, value in iteritems(self._updates)] self._service.set_zone_settings(self.zone.id, items) self._get_settings() self._updates = {} def __iter__(self): return iter(sorted(self._settings)) def __repr__(self): return 'ZoneSettings<%s>' % self.zone.name class PerZoneObject(object): _data = () _own_attrs = ('zone', '_service', '_data', '_saved_data') def __init__(self, zone, data): self.zone = zone self._service = zone._service self._set_data(data) def __getattr__(self, name): if name in self._data: return self._data[name] raise AttributeError() def __setattr__(self, name, value): if name in self._own_attrs: return super(PerZoneObject, self).__setattr__(name, value) if name in self._data: self._data[name] = value else: raise AttributeError() def _set_data(self, data): self._saved_data = data self._data = deepcopy(data) def save(self): if self._saved_data != self._data: self._set_data(self._save()) def _save(self): """Save _data to CloudFlare, and return the result""" raise NotImplemented() def delete(self): raise NotImplemented() def __repr__(self): raise NotImplemented() class Record(PerZoneObject): def _save(self): result = self._service.update_dns_record(self.zone.id, self.id, self._data) if result['name'] != self._saved_data['name']: clear_property_cache(self.zone, 'records') return result def delete(self): self._service.delete_dns_record(self.zone.id, self.id) clear_property_cache(self.zone, 'records') def __repr__(self): return 'Record<%s %s IN %s %s>' % (self.name, self.ttl, self.type, self.content) class PageRule(PerZoneObject): def _save(self): result = self._service.update_page_rule( self.zone.id, self.id, self._data) if result['priority'] != self._saved_data['priority']: clear_property_cache(self.zone, 'page_rules') return result def delete(self): self._service.delete_page_rule(self.zone.id, self.id) clear_property_cache(self.zone, 'page_rules') def __repr__(self): return 'PageRule <%s>' % self.id
# Copyright 2016 MongoDB, 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. """Serve GridFS files with Motor and aiohttp. Requires Python 3.5 or later and aiohttp 3.0 or later. See the :doc:`/examples/aiohttp_gridfs_example`. """ import asyncio import datetime import mimetypes import aiohttp.web import gridfs from motor.motor_asyncio import (AsyncIOMotorDatabase, AsyncIOMotorGridFSBucket) def get_gridfs_file(bucket, filename, request): """Override to choose a GridFS file to serve at a URL. By default, if a URL pattern like ``/fs/{filename}`` is mapped to this :class:`AIOHTTPGridFS`, then the filename portion of the URL is used as the filename, so a request for "/fs/image.png" results in a call to :meth:`.AsyncIOMotorGridFSBucket.open_download_stream_by_name` with "image.png" as the ``filename`` argument. To customize the mapping of path to GridFS file, override ``get_gridfs_file`` and return a :class:`asyncio.Future` that resolves to a :class:`~motor.motor_asyncio.AsyncIOMotorGridOut`. For example, to retrieve the file by ``_id`` instead of filename:: def get_gridfile_by_id(bucket, filename, request): # "filename" is interpreted as _id instead of name. # Return a Future AsyncIOMotorGridOut. return bucket.open_download_stream(file_id=filename) client = AsyncIOMotorClient() gridfs_handler = AIOHTTPGridFS(client.my_database, get_gridfs_file=get_gridfile_by_id) :Parameters: - `bucket`: An :class:`~motor.motor_asyncio.AsyncIOMotorGridFSBucket` - `filename`: A string, the URL portion matching {filename} in the URL pattern - `request`: An :class:`aiohttp.web.Request` """ # A Future AsyncIOMotorGridOut. return bucket.open_download_stream_by_name(filename) def get_cache_time(filename, modified, mime_type): """Override to customize cache control behavior. Return a positive number of seconds to trigger aggressive caching or 0 to mark resource as cacheable, only. 0 is the default. For example, to allow image caching:: def image_cache_time(filename, modified, mime_type): if mime_type.startswith('image/'): return 3600 return 0 client = AsyncIOMotorClient() gridfs_handler = AIOHTTPGridFS(client.my_database, get_cache_time=image_cache_time) :Parameters: - `filename`: A string, the URL portion matching {filename} in the URL pattern - `modified`: A datetime, when the matching GridFS file was created - `mime_type`: The file's type, a string like "application/octet-stream" """ return 0 def set_extra_headers(response, gridout): """Override to modify the response before sending to client. For example, to allow image caching:: def gzip_header(response, gridout): response.headers['Content-Encoding'] = 'gzip' client = AsyncIOMotorClient() gridfs_handler = AIOHTTPGridFS(client.my_database, set_extra_headers=gzip_header) :Parameters: - `response`: An :class:`aiohttp.web.Response` - `gridout`: The :class:`~motor.motor_asyncio.AsyncIOMotorGridOut` we will serve to the client """ pass def _config_error(request): try: formatter = request.match_info.route.resource.get_info()['formatter'] msg = ('Bad AIOHTTPGridFS route "%s", requires a {filename} variable' % formatter) except (KeyError, AttributeError): # aiohttp API changed? Fall back to simpler error message. msg = ('Bad AIOHTTPGridFS route for request: %s' % request) raise aiohttp.web.HTTPInternalServerError(text=msg) from None class AIOHTTPGridFS: """Serve files from `GridFS`_. This class is a :ref:`request handler <aiohttp-web-handler>` that serves GridFS files, similar to aiohttp's built-in static file server. .. code-block:: python client = AsyncIOMotorClient() gridfs_handler = AIOHTTPGridFS(client.my_database) app = aiohttp.web.Application() # The GridFS URL pattern must have a "{filename}" variable. resource = app.router.add_resource('/fs/{filename}') resource.add_route('GET', gridfs_handler) resource.add_route('HEAD', gridfs_handler) app_handler = app.make_handler() server = loop.create_server(app_handler, port=80) By default, requests' If-Modified-Since headers are honored, but no specific cache-control timeout is sent to clients. Thus each request for a GridFS file requires a quick check of the file's ``uploadDate`` in MongoDB. Pass a custom :func:`get_cache_time` to customize this. :Parameters: - `database`: An :class:`AsyncIOMotorDatabase` - `get_gridfs_file`: Optional override for :func:`get_gridfs_file` - `get_cache_time`: Optional override for :func:`get_cache_time` - `set_extra_headers`: Optional override for :func:`set_extra_headers` .. _GridFS: https://docs.mongodb.com/manual/core/gridfs/ """ def __init__(self, database, root_collection='fs', get_gridfs_file=get_gridfs_file, get_cache_time=get_cache_time, set_extra_headers=set_extra_headers): if not isinstance(database, AsyncIOMotorDatabase): raise TypeError("First argument to AIOHTTPGridFS must be " "AsyncIOMotorDatabase, not %r" % database) self._database = database self._bucket = AsyncIOMotorGridFSBucket(self._database, root_collection) self._get_gridfs_file = get_gridfs_file self._get_cache_time = get_cache_time self._set_extra_headers = set_extra_headers @asyncio.coroutine def __call__(self, request): """Send filepath to client using request.""" try: filename = request.match_info['filename'] except KeyError: _config_error(request) if request.method not in ('GET', 'HEAD'): raise aiohttp.web.HTTPMethodNotAllowed( method=request.method, allowed_methods={'GET', 'HEAD'}) try: gridout = yield from self._get_gridfs_file(self._bucket, filename, request) except gridfs.NoFile: raise aiohttp.web.HTTPNotFound(text=request.path) resp = aiohttp.web.StreamResponse() self._set_standard_headers(request.path, resp, gridout) # Overridable method set_extra_headers. self._set_extra_headers(resp, gridout) # Check the If-Modified-Since, and don't send the result if the # content has not been modified ims_value = request.if_modified_since if ims_value is not None: # If our MotorClient is tz-aware, assume the naive ims_value is in # its time zone. if_since = ims_value.replace(tzinfo=gridout.upload_date.tzinfo) modified = gridout.upload_date.replace(microsecond=0) if if_since >= modified: resp.set_status(304) return resp # Same for Etag etag = request.headers.get("If-None-Match") if etag is not None and etag.strip('"') == gridout.md5: resp.set_status(304) return resp resp.content_length = gridout.length yield from resp.prepare(request) if request.method == 'GET': written = 0 while written < gridout.length: # Reading chunk_size at a time minimizes buffering. chunk = yield from gridout.read(gridout.chunk_size) yield from resp.write(chunk) written += len(chunk) return resp def _set_standard_headers(self, path, resp, gridout): resp.last_modified = gridout.upload_date content_type = gridout.content_type if content_type is None: content_type, encoding = mimetypes.guess_type(path) if content_type: resp.content_type = content_type # MD5 is calculated on the MongoDB server when GridFS file is created. resp.headers["Etag"] = '"%s"' % gridout.md5 # Overridable method get_cache_time. cache_time = self._get_cache_time(path, gridout.upload_date, gridout.content_type) if cache_time > 0: resp.headers["Expires"] = ( datetime.datetime.utcnow() + datetime.timedelta(seconds=cache_time) ).strftime("%a, %d %b %Y %H:%M:%S GMT") resp.headers["Cache-Control"] = "max-age=" + str(cache_time) else: resp.headers["Cache-Control"] = "public"
# Copyright (c) 2009-2021 Arm Limited # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import os import platform import random import shlex import re from chip.setup_payload import SetupPayload from chip import exceptions if platform.system() == 'Darwin': from chip.ChipCoreBluetoothMgr import CoreBluetoothManager as BleManager elif sys.platform.startswith('linux'): from chip.ChipBluezMgr import BluezManager as BleManager import logging log = logging.getLogger(__name__) class ParsingError(exceptions.ChipStackException): def __init__(self, msg=None): self.msg = "Parsing Error: " + msg def __str__(self): return self.msg def get_device_details(device): """ Get device details from logs :param device: serial device instance :return: device details dictionary or None """ ret = device.wait_for_output("SetupQRCode") if ret == None or len(ret) < 2: return None qr_code = re.sub( r"[\[\]]", "", ret[-1].partition("SetupQRCode:")[2]).strip() try: device_details = dict(SetupPayload().ParseQrCode( "VP:vendorpayload%{}".format(qr_code)).attributes) except exceptions.ChipStackError as ex: log.error(ex.msg) return None return device_details def ParseEncodedString(value): if value.find(":") < 0: raise ParsingError( "Value should be encoded in encoding:encodedvalue format") enc, encValue = value.split(":", 1) if enc == "str": return encValue.encode("utf-8") + b'\x00' elif enc == "hex": return bytes.fromhex(encValue) raise ParsingError("Only str and hex encoding is supported") def ParseValueWithType(value, type): if type == 'int': return int(value) elif type == 'str': return value elif type == 'bytes': return ParseEncodedString(value) elif type == 'bool': return (value.upper() not in ['F', 'FALSE', '0']) else: raise ParsingError('Cannot recognize type: {}'.format(type)) def FormatZCLArguments(args, command): commandArgs = {} for kvPair in args: if kvPair.find("=") < 0: raise ParsingError("Argument should in key=value format") key, value = kvPair.split("=", 1) valueType = command.get(key, None) commandArgs[key] = ParseValueWithType(value, valueType) return commandArgs def send_zcl_command(devCtrl, line): """ Send ZCL message to device: <cluster> <command> <nodeid> <endpoint> <groupid> [key=value]... :param devCtrl: device controller instance :param line: command line :return: error code and command responde """ res = None err = 0 try: args = shlex.split(line) all_commands = devCtrl.ZCLCommandList() if len(args) < 5: raise exceptions.InvalidArgumentCount(5, len(args)) if args[0] not in all_commands: raise exceptions.UnknownCluster(args[0]) command = all_commands.get(args[0]).get(args[1], None) # When command takes no arguments, (not command) is True if command == None: raise exceptions.UnknownCommand(args[0], args[1]) err, res = devCtrl.ZCLSend(args[0], args[1], int( args[2]), int(args[3]), int(args[4]), FormatZCLArguments(args[5:], command), blocking=True) if err != 0: log.error("Failed to send ZCL command [{}] {}.".format(err, res)) elif res != None: log.info("Success, received command response:") log.info(res) else: log.info("Success, no command response.") except exceptions.ChipStackException as ex: log.error("An exception occurred during processing ZCL command:") log.error(str(ex)) err = -1 except Exception as ex: log.error("An exception occurred during processing input:") log.error(str(ex)) err = -1 return (err, res) def scan_chip_ble_devices(devCtrl): """ BLE scan CHIP device BLE scanning for 10 seconds and collect the results :param devCtrl: device controller instance :return: List of visible BLE devices """ devices = [] bleMgr = BleManager(devCtrl) bleMgr.scan("-t 10") for device in bleMgr.peripheral_list: devIdInfo = bleMgr.get_peripheral_devIdInfo(device) if devIdInfo: devInfo = devIdInfo.__dict__ devInfo["name"] = device.Name devices.append(devInfo) return devices def check_chip_ble_devices_advertising(devCtrl, name, deviceDetails=None): """ Check if CHIP device advertise BLE scanning for 10 seconds and compare with device details :param devCtrl: device controller instance :param name: device advertising name :param name: device details :return: True if device advertise else False """ ble_chip_device = scan_chip_ble_devices(devCtrl) if ble_chip_device == None or len(ble_chip_device) == 0: log.info("No BLE CHIP device found") return False chip_device_found = False for ble_device in ble_chip_device: if deviceDetails != None: if (ble_device["name"] == name and int(ble_device["discriminator"]) == int(deviceDetails["Discriminator"]) and int(ble_device["vendorId"]) == int(deviceDetails["VendorID"]) and int(ble_device["productId"]) == int(deviceDetails["ProductID"])): chip_device_found = True break else: if (ble_device["name"] == name): chip_device_found = True break return chip_device_found def connect_device_over_ble(devCtrl, discriminator, pinCode, nodeId=None): """ Connect to Matter accessory device over BLE :param devCtrl: device controller instance :param discriminator: CHIP device discriminator :param pinCode: CHIP device pin code :param nodeId: default value of node ID :return: node ID is provisioning successful, otherwise None """ if nodeId == None: nodeId = random.randint(1, 1000000) try: devCtrl.ConnectBLE(int(discriminator), int(pinCode), int(nodeId)) except exceptions.ChipStackException as ex: log.error("Connect device over BLE failed: {}".format(str(ex))) return None return nodeId def close_connection(devCtrl, nodeId): """ Close the BLE connection :param devCtrl: device controller instance :return: true if successful, otherwise false """ try: devCtrl.CloseSession(nodeId) except exceptions.ChipStackException as ex: log.error("Close session failed: {}".format(str(ex))) return False return True def close_ble(devCtrl): """ Close the BLE connection :param devCtrl: device controller instance :return: true if successful, otherwise false """ try: devCtrl.CloseBLEConnection() except exceptions.ChipStackException as ex: log.error("Close BLE connection failed: {}".format(str(ex))) return False return True def commissioning_wifi(devCtrl, ssid, password, nodeId): """ Commissioning a Wi-Fi device :param devCtrl: device controller instance :param ssid: network ssid :param password: network password :param nodeId: value of node ID :return: error code """ # Inject the credentials to the device err, res = send_zcl_command( devCtrl, "NetworkCommissioning AddOrUpdateWiFiNetwork {} 0 0 ssid=str:{} credentials=str:{} breadcrumb=0 timeoutMs=1000".format(nodeId, ssid, password)) if err != 0 and res["Status"] != 0: log.error("Set Wi-Fi credentials failed [{}]".format(err)) return err # Enable the Wi-Fi interface err, res = send_zcl_command( devCtrl, "NetworkCommissioning ConnectNetwork {} 0 0 networkID=str:{} breadcrumb=0 timeoutMs=1000".format(nodeId, ssid)) if err != 0 and res["Status"] != 0: log.error("Enable Wi-Fi failed [{}]".format(err)) return err return err def resolve_device(devCtrl, nodeId): """ Discover IP address and port of the device. :param devCtrl: device controller instance :param nodeId: value of node ID :return: device IP address and port if successful, otherwise None """ ret = None try: err = devCtrl.ResolveNode(int(nodeId)) if err == 0: ret = devCtrl.GetAddressAndPort(int(nodeId)) if ret == None: log.error("Get address and port failed") else: log.error("Resolve node failed [{}]".format(err)) except exceptions.ChipStackException as ex: log.error("Resolve node failed {}".format(str(ex))) return ret
from Child import Child from Node import Node # noqa: I201 STMT_NODES = [ # continue-stmt -> 'continue' label? ';'? Node('ContinueStmt', kind='Stmt', children=[ Child('ContinueKeyword', kind='ContinueToken'), Child('Label', kind='IdentifierToken', is_optional=True), Child('Semicolon', kind='SemicolonToken', is_optional=True), ]), # while-stmt -> label? ':'? 'while' condition-list code-block ';'? Node('WhileStmt', kind='Stmt', children=[ Child('LabelName', kind='IdentifierToken', is_optional=True), Child('LabelColon', kind='ColonToken', is_optional=True), Child('WhileKeyword', kind='WhileToken'), Child('Conditions', kind='ConditionList'), Child('Body', kind='CodeBlock'), Child('Semicolon', kind='SemicolonToken', is_optional=True), ]), # defer-stmt -> 'defer' code-block ';'? Node('DeferStmt', kind='Stmt', children=[ Child('DeferKeyword', kind='DeferToken'), Child('Body', kind='CodeBlock'), Child('Semicolon', kind='SemicolonToken', is_optional=True), ]), # expr-stmt -> expression ';'? Node('ExpressionStmt', kind='Stmt', children=[ Child('Expression', kind='Expr'), Child('Semicolon', kind='SemicolonToken', is_optional=True), ]), # switch-case-list -> switch-case switch-case-list? Node('SwitchCaseList', kind='SyntaxCollection', element='SwitchCase'), # repeat-while-stmt -> label? ':'? 'repeat' code-block 'while' expr ';'? Node('RepeatWhileStmt', kind='Stmt', children=[ Child('LabelName', kind='IdentifierToken', is_optional=True), Child('LabelColon', kind='ColonToken', is_optional=True), Child('RepeatKeyword', kind='RepeatToken'), Child('Body', kind='CodeBlock'), Child('WhileKeyword', kind='WhileToken'), Child('Condition', kind='Expr'), Child('Semicolon', kind='SemicolonToken', is_optional=True), ]), # guard-stmt -> 'guard' condition-list 'else' code-block ';'? Node('GuardStmt', kind='Stmt', children=[ Child('GuardKeyword', kind='GuardToken'), Child('Conditions', kind='ConditionList'), Child('ElseKeyword', kind='ElseToken'), Child('Body', kind='CodeBlock'), Child('Semicolon', kind='SemicolonToken', is_optional=True), ]), Node('ExprList', kind='SyntaxCollection', element='Expr', element_name='Expression'), Node('WhereClause', kind='Syntax', children=[ Child('WhereKeyword', kind='WhereToken'), Child('Expressions', kind='ExprList'), ]), # for-in-stmt -> label? ':'? 'for' 'case'? pattern 'in' expr 'where'? # expr code-block ';'? Node('ForInStmt', kind='Stmt', children=[ Child('LabelName', kind='IdentifierToken', is_optional=True), Child('LabelColon', kind='ColonToken', is_optional=True), Child('For', kind='ForToken'), Child('Case', kind='CaseToken', is_optional=True), Child('ItemPattern', kind='Pattern'), Child('InKeyword', kind='InToken'), Child('CollectionExpr', kind='Expr'), Child('WhereClause', kind='WhereClause', is_optional=True), Child('Body', kind='CodeBlock'), Child('Semicolon', kind='SemicolonToken', is_optional=True), ]), # switch-stmt -> identifier? ':'? 'switch' expr '{' # switch-case-list '}' ';'? Node('SwitchStmt', kind='Stmt', children=[ Child('LabelName', kind='IdentifierToken', is_optional=True), Child('LabelColon', kind='ColonToken', is_optional=True), Child('SwitchKeyword', kind='SwitchToken'), Child('Expression', kind='Expr'), Child('OpenBrace', kind='LeftBraceToken'), Child('Cases', kind='SwitchCaseList'), Child('CloseBrace', kind='RightBraceToken'), Child('Semicolon', kind='SemicolonToken', is_optional=True), ]), # catch-clause-list -> catch-clause catch-clause-list? Node('CatchClauseList', kind='SyntaxCollection', element='CatchClause'), # do-stmt -> identifier? ':'? 'do' code-block catch-clause-list ';'? Node('DoStmt', kind='Stmt', children=[ Child('LabelName', kind='IdentifierToken', is_optional=True), Child('LabelColon', kind='ColonToken', is_optional=True), Child('DoKeyword', kind='DoToken'), Child('Body', kind='CodeBlock'), Child('CatchClauses', kind='CatchClauseList'), Child('Semicolon', kind='SemicolonToken', is_optional=True), ]), # return-stmt -> 'return' expr? ';'? Node('ReturnStmt', kind='Stmt', children=[ Child('ReturnKeyword', kind='ReturnToken'), Child('Expression', kind='Expr', is_optional=True), Child('Semicolon', kind='SemicolonToken', is_optional=True), ]), # fallthrough-stmt -> 'fallthrough' ';'? Node('FallthroughStmt', kind='Stmt', children=[ Child('FallthroughKeyword', kind='FallthroughToken'), Child('Semicolon', kind='SemicolonToken', is_optional=True), ]), # break-stmt -> 'break' identifier? ';'? Node('BreakStmt', kind='Stmt', children=[ Child('BreakKeyword', kind='BreakToken'), Child('Label', kind='IdentifierToken', is_optional=True), Child('Semicolon', kind='SemicolonToken', is_optional=True), ]), # code-block -> '{' stmt-list '}' Node('CodeBlock', kind='Syntax', children=[ Child('OpenBrace', kind='LeftBraceToken'), Child('Statments', kind='StmtList'), Child('CloseBrace', kind='RightBraceToken'), ]), # case-item-list -> case-item case-item-list? Node('CaseItemList', kind='SyntaxCollection', element='CaseItem'), Node('Condition', kind='Syntax', children=[ Child('Condition', kind='Syntax'), Child('TrailingComma', kind='CommaToken', is_optional=True), ]), # condition-list -> condition # | condition ','? condition-list # condition -> expression # | availability-condition # | case-condition # | optional-binding-condition Node('ConditionList', kind='SyntaxCollection', element='Condition'), # A declaration in statement position. # struct Foo {}; Node('DeclarationStmt', kind='Stmt', children=[ Child('Declaration', kind='Decl'), Child('Semicolon', kind='SemicolonToken', is_optional=True), ]), # throw-stmt -> 'throw' expr ';'? Node('ThrowStmt', kind='Stmt', children=[ Child('ThrowKeyword', kind='ThrowToken'), Child('Expression', kind='Expr'), Child('Semicolon', kind='SemicolonToken', is_optional=True), ]), # if-stmt -> identifier? ':'? 'if' condition-list code-block # else-clause ';'? Node('IfStmt', kind='Stmt', children=[ Child('LabelName', kind='IdentifierToken', is_optional=True), Child('LabelColon', kind='ColonToken', is_optional=True), Child('IfKeyword', kind='IfToken'), Child('Conditions', kind='ConditionList'), Child('Body', kind='CodeBlock'), Child('ElseClause', kind='Syntax', is_optional=True), Child('Semicolon', kind='SemicolonToken', is_optional=True), ]), # else-if-continuation -> label? ':'? 'while' condition-list code-block ';' Node('ElseIfContinuation', kind='Syntax', children=[ Child('IfStatement', kind='IfStmt'), ]), # else-clause -> 'else' code-block Node('ElseBlock', kind='Syntax', children=[ Child('ElseKeyword', kind='ElseToken'), Child('Body', kind='CodeBlock'), Child('Semicolon', kind='SemicolonToken', is_optional=True), ]), # stmt-list -> stmt stmt-list? Node('StmtList', kind='SyntaxCollection', element='Stmt'), # switch-case -> switch-case-label stmt-list # | default-label stmt-list Node('SwitchCase', kind='Syntax', children=[ Child('Label', kind='Syntax'), Child('Body', kind='StmtList'), ]), # switch-default-label -> 'default' ':' Node('SwitchDefaultLabel', kind='Syntax', children=[ Child('DefaultKeyword', kind='DefaultToken'), Child('Colon', kind='ColonToken'), ]), # case-item -> pattern where-clause? ','? Node('CaseItem', kind='Syntax', children=[ Child('Pattern', kind='Pattern'), Child('WhereClause', kind='WhereClause', is_optional=True), Child('Comma', kind='CommaToken', is_optional=True), ]), # switch-case-label -> 'case' case-item-list ':' Node('SwitchCaseLabel', kind='Syntax', children=[ Child('CaseKeyword', kind='CaseToken'), Child('CaseItems', kind='CaseItemList'), Child('Colon', kind='ColonToken'), ]), # catch-clause 'catch' pattern? where-clause? code-block Node('CatchClause', kind='Syntax', children=[ Child('CatchKeyword', kind='CatchToken'), Child('Pattern', kind='Pattern', is_optional=True), Child('WhereClause', kind='WhereClause', is_optional=True), Child('Body', kind='CodeBlock'), ]), ]
import os, glob import numpy as np import scipy.linalg as spl import matplotlib.pylab as plt import cv2 import time def load_files(path,extension,colour=False): """ This function loads all the image files with part of their filenames as 'extension' in the directory 'path' in an array. If colour is 'True', then the images will have colour.""" if colour == True: colour_setting = 1 else: colour_setting = 0 os.chdir(path) file_name_list = glob.glob(extension) image_list = [] name_list = [] ###for dubugging only for i in range(len(file_name_list)): image_list.append(cv2.imread(file_name_list[i], colour_setting)) name_list.append(file_name_list[i]) ###for debugging only # print name_list ### print the filenames in the array to make sure all sets of images are in the same order return np.array(image_list) def ball_shape(img, min_radius=30, max_radius=50): """ This function requires images in an array and returns the coordinates of centre and radius of the circle detected. It is used to calculate (Cx,Cy) and radius r of the metal ball used for light calibration. It uses Hough Transform to detect the circle. The shape of metal ball should be easily distinguished (like putting a mobile phone behind the ball, and an estimate of the min and max value of the radius of the circle in units of pixel.""" N = img.shape[0] circles = np.empty(shape=(N,3)) #check to see if the image is already in grayscale, and converts it if it is not for i in range(N): if img[i].shape[-1] == (3 or 4): img[i] = cv2.cvtColor(img[i], cv2.COLOR_BGR2GRAY) img[i] = cv2.medianBlur(img[i],5) # smoothen the image so no false circles are detected circle_info = cv2.HoughCircles(img[i],cv2.HOUGH_GRADIENT,1,20, param1=50,param2=30,minRadius=min_radius,maxRadius=max_radius) if circle_info == None: print i print 'Error, no circles found!' return None elif circle_info.shape[-1] != 3: # for checking print 'Error, more than one circle found!' print i print circle_info return None circles[i,:] = circle_info x = np.mean(circles[:,0]) y = np.mean(circles[:,1]) r = np.mean(circles[:,2]) return (x, y, r) def bright_spot(img, ROI=[150,300,150,250]): # if last is true, it is useful and checked as well """This function locates the brightest spot on the metal ball. The region of interest (ROI) should be provided so that the brightest spot falls within this ROI and no false bright spot is detected.""" N = img.shape[0] top, bottom, left, right = ROI bright_spot_array = np.empty(shape=(N,2)) # threshold the border of the image using the ROI # so that no other brighter light source (e.g. mobile phone) is present img2 = img.copy() img2[:,top:bottom,left:right] = 0 img = img - img2 for i in range(N): if img[i].shape[-1] == (3 or 4): img[i] = cv2.cvtColor(img[i], cv2.COLOR_BGR2GRAY) img[i] = cv2.GaussianBlur(img[i], (5,5), 0) bright_spot_array[i,:] = cv2.minMaxLoc(img[i])[3] return bright_spot_array def masked_img(img,ROI,blur_radius=25,threshold=67): """This function requires a single image (image with all LEDs switched on) and returns an image that shows the regions masked by the object""" if img.shape[-1] == 3: img = img[:,:,-1] top,bottom,left,right = ROI img2 = img.copy() img2[top:bottom,left:right] = 0 img = img-img2 img = cv2.GaussianBlur(img, (blur_radius,blur_radius), 0) > threshold return img def scale_image(img,white_board,background): """This function scales all the images by using the images of white board and background illumination.""" if len(img.shape) == 3: N,height,width = img.shape elif len(img.shape) == 4: N,height,width,useless = img.shape img = img[:,:,:,2] else: print 'error! size of img array is not correct!' return None # check to see if the background img is in single colour channel (red) background_light = np.empty(shape=(N,height,width)) if len(background.shape) == 2: background_light[:] = background elif len(background.shape) == 3: background_light[:] = background[:,:,2] background_light[:] = cv2.GaussianBlur(background_light[:], (3,3), 0) # converts the data type of the array so that division results in decimals if img.dtype == 'uint8': img.astype(float) background.astype(float) white_board.astype(float) # scale the image img = (img-background_light)/(white_board-background_light) # converts all 'nan' resulted from 0/0 or 'inf' to 0 img[img == np.nan] = 0 img[img == float('inf')] = 0 img[img == -float('inf')] = 0 return img def light_direction(ball_array, ball_mask_array, ball_ROI, R, D, far=True): """ This function computes the light direction vector L for each light LED using the img of metal ball. ball_array: array of img of metal ball ball_mask_array: the masked region of the metal ball ball_ROI: the region that includes the metal ball R: radius of the metal ball in cm D: distance from the object to the LEDs in cm far: True implies the distance can be treated as very far and approximations are made""" Xc, Yc, radius = ball_shape(ball_mask_array) bright_spot_array = bright_spot(ball_array, ball_ROI) D = D/(R/radius) # compute the no. of img, height and width of the img array if len(ball_array.shape) == 3: # image already in grayscale N, height, width = ball_array.shape else: # coloured image N, height, width, useless = ball_array.shape bright_spot_normal = np.empty(shape=(N,3)) # for debugging L_array = np.empty(shape=(N, height, width, 3)) if far == False: # for correction of light direction at different points x = np.arange(width) y = np.arange(height) index_map = np.meshgrid(x,y) for i in range(N): xo, yo = bright_spot_array[i] Nx = xo-Xc Ny = -(yo-Yc) Nz = np.sqrt(radius**2 - Nx**2 - Ny**2) n = np.array([Nx,Ny,Nz])/radius # surf normal vector at the bright spot print n L = 2*(n[2])*n - np.array([0,0,1]) bright_spot_normal[i,:] = L # calculate the corrected L vector at different points if it is not 'far' # the method used here may not accurate as it only uses simple vector addition # more 'rigorous' expressions may be needed # all results presented in the project assumes 'far' = True if far == False: L_array[i,:,:,0] = D*(L[0]/L[2])-(index_map[0]-xo) L_array[i,:,:,1] = D*(L[1]/L[2])+(index_map[1]-yo) L_array[i,:,:,2] = D else: L_array[i,:,:,:] = L # normalize the vector L_array[i] = L_array[i] / np.sqrt((L_array[i]**2).sum(axis=-1))[:,:,None] # L and L_array are all defined as the vector pointing from the object to the camera return L_array, bright_spot_normal, D def stacked_lstsq(L, b, rcond=1e-8): """ Solve L x = b, via SVD least squares cutting of small singular values L is an array of shape (..., M, N) and b of shape (..., M). Returns x of shape (..., N) The algorithm is adopted from: http://stackoverflow.com/questions/30442377/how-to-solve-many-overdetermined-systems-of-linear-equations-using-vectorized-co This vectorized code is slightly faster than doing least-square for each pixel one-by-one, especially if L is different for different points """ u, s, v = np.linalg.svd(L, full_matrices=False) s_max = s.max(axis=-1, keepdims=True) s_min = rcond*s_max inv_s = np.zeros_like(s) inv_s[s >= s_min] = 1/s[s>=s_min] x = np.einsum('...ji,...j->...i', v, inv_s * np.einsum('...ji,...j->...i', u, b.conj())) return np.conj(x, x) def surf_normal_test(img_array, img_mask, light_direction, blur=1, shadow=0.5): """this funcion calculates the surf normal of the object. img_array: set of images of the actual object (in grayscale/single colour channel) img_mask: the masked region of the object (a 2D boolean array) light_direction: the array that stores the light direction for different images shadow: the threshold for detecting shadow. Set it to 0 to deactivate it.the L is Nx3 array of light direction. """ N,height,width = img_array.shape total_pix = height*width img_mask.astype(float) img_array.astype(float) # smooth the image and calibrate the intensity if blur>0: img_array[:] = cv2.GaussianBlur(img_array[:], (blur,blur), 0) img_array = img_array*img_mask img_array = img_array.reshape(N,total_pix) L = np.empty(shape=(total_pix,N,3)) b = np.empty(shape=(total_pix,N)) for i in range(N): b[:,i] = img_array[i] light_direction = light_direction.reshape(N,total_pix,3) #checking #light_direction = light_direction.reshape(N,total_pix,3) #checking light_direction = np.rollaxis(light_direction,1) #checking L[:] = light_direction if shadow>0: b_median = np.median(b,axis=1) if N>=5: for pix in range(total_pix): for n in range(N): if b[pix,n] < 0.3*b_median[pix]: b[pix,n] = 0 L[pix,n,:] = 0 elif N==4: b_min = np.argmin(b,axis=1) for pix in range(total_pix): if b[pix,b_min[pix]] < 0.5*b_median[pix]: b[pix,b_min[pix]] = 0 L[pix,b_min[pix],:] = 0 surf_normal_map = stacked_lstsq(L,b).reshape(height,width,3) surf_normal_map = surf_normal_map/np.sqrt((surf_normal_map**2).sum(axis=-1))[:,:,None] #normalize the vector return surf_normal_map def surf_height(surf_normal,penalty,estimate=0): """ this function reconstruct the surface using a regularized least-square method. surface_normal is the heightxwidthx3 array that stores the surface normal at each point penalty is the value of lambda""" def D_matrix(size): D_mat = np.zeros(shape=(size,size)) D_mat[0,0] = -3 D_mat[0,1] = 4 D_mat[0,2] = -1 D_mat[-1,-3] = 1 D_mat[-1,-2] = -4 D_mat[-1,3] = 3 for row in range(1,size-1): D_mat[row,row-1] = -1 D_mat[row,row+1] = 1 D_mat = D_mat/2 return D_mat normal_array[np.isnan(normal_array)]=0 y,x = np.nonzero(surf_normal[:,:,0]) left = np.min(x) right = np.max(x) top = np.min(y) bottom = np.max(y) surf_normal = surf_normal[top:bottom+1,left:right+1,:] #return surf_normal Zx = -surf_normal[:,:,0] Zy = surf_normal[:,:,1] height,width,useless = surf_normal.shape if estimate==0: guess=np.zeros(shape=(height,width)) Dy = D_matrix(height) Dx = D_matrix(width) A = np.dot(Dy.T,Dy) + penalty**2*np.identity(height) B = np.dot(Dx.T,Dx) + penalty**2*np.identity(width) Q = np.dot(Dy.T,Zy )+ np.dot(Zx,Dx)+2*penalty**2*estimate Z = spl.solve_sylvester(A,B,Q) min_height = np.min(Z) Z = Z - min_height Z = Z/masked_image[top:bottom+1,left:right+1] Z[Z==float('inf')] = np.nan Z[Z==(-float('inf'))] = np.nan return Z ### main program starts here ### start_time = time.time() path = "H:/Project/Data/15-6-Mon" # load the images as arrays # the first eight images are those that correspond to different light directions # 9th image is when all lights are on # 10th image is when all lights are off ball_array = load_files(path,'*img_03*') # the image of the metal ball ball_mask_array = load_files(path,'*img_04*') # the image of the metal ball with mobile phone behind obj = load_files(path,'*img_05*',colour=True) # ping-pong ball (object) board = load_files(path,'*img_02*',colour=True)[:-2,:,:,2] # image of the white board board2 = load_files(path,'*img_01*',colour=True)[:-2,:,:,2] # image of the white board (take avg using two data) board_avg = (board.astype(float)+board2.astype(float))/2 # take the avg value of the board R = 5.0/2 # radius of the chrome ball in cm D = 30.0 # distance from object to camera in cm ball_ROI=[210,335,200,310] # region of interest for the ball mask [top,bottom,left,right] far_setting = True # light direction L, bright_spot_normal, d = light_direction(ball_array[0:-2],ball_mask_array,ball_ROI,R,D,far=far_setting) ### white scattering ball as image object_ROI = [170,335,185,350] #[top,bottom,left,right] masked_image = masked_img(obj[-2],object_ROI) background = obj[-1] processed_image = scale_image(obj[0:-2],board_avg,background) normal_array = surf_normal_test(processed_image,masked_image,L,blur=1) height_map = surf_height(normal_array,0.03) # plot the three components of the gradient field (surface normal) top,bottom,left,right = object_ROI component=['x-component','y-component','z-component'] for i in range(3): # turn the background into nan (no colour) normal_array[:,:,i]=normal_array[:,:,i]/masked_image for i in range(3): # plot the intensity graph plt.subplot(2,2,i+1) plt.imshow(normal_array[:,:,i]) plt.xlim(left,right) plt.ylim(bottom,top) plt.axis('Off') plt.colorbar() plt.title(component[i]) plt.show() # plot the height map of the object plt.subplot(2,2,4) plt.title('height map') plt.imshow(height_map) plt.axis('Off') plt.colorbar() plt.show() print time.time()-start_time
from nose.tools import assert_raises from rx import Observer from rx.notification import OnNext, OnError, OnCompleted from rx.internal.exceptions import CompletedException class MyObserver(Observer): def on_next(self, value): self.has_on_next = value def on_error(self, err): self.has_on_error = err def on_completed(self): self.has_on_completed = True def test_to_observer_notification_on_next(): i = 0 def next(n): assert(i == 0) assert(n.kind == 'N') assert(n.value == 42) assert(not hasattr(n, "exception")) assert(n.has_value) Observer.from_notifier(next).on_next(42) def test_to_observer_notification_on_error(): ex = 'ex' i = 0 def next(n): assert(i == 0) assert(n.kind == 'E') assert(n.exception == ex) assert(not n.has_value) Observer.from_notifier(next).on_error(ex) def test_to_observer_notification_on_completed(): i = 0 def next(n): assert(i == 0) assert(n.kind == 'C') assert(not n.has_value) Observer.from_notifier(next).on_completed() def test_to_notifier_forwards(): obsn = MyObserver() obsn.to_notifier()(OnNext(42)) assert(obsn.has_on_next == 42) ex = 'ex' obse = MyObserver() obse.to_notifier()(OnError(ex)) assert(ex == obse.has_on_error) obsc = MyObserver() obsc.to_notifier()(OnCompleted()) assert(obsc.has_on_completed) def test_create_on_next(): next = [False] def on_next(x): assert(42 == x) next[0] = True res = Observer(on_next) res.on_next(42) assert(next[0]) return res.on_completed() def test_create_on_next_has_error(): ex = 'ex' next = [False] _e = None def on_next(x): assert(42 == x) next[0] = True res = Observer(on_next) res.on_next(42) assert(next[0]) try: res.on_error(ex) assert(False) except Exception as e: e_ = e.args[0] assert(ex == e_) def test_create_on_next_on_completed(): next = [False] completed = [False] def on_next(x): assert(42 == x) next[0] = True return next[0] def on_completed(): completed[0] = True return completed[0] res = Observer(on_next, None, on_completed) res.on_next(42) assert(next[0]) assert(not completed[0]) res.on_completed() assert(completed[0]) def test_create_on_next_on_completed_has_error(): e_ = None ex = 'ex' next = [False] completed = [False] def on_next(x): assert(42 == x) next[0] = True def on_completed(): completed[0] = True res = Observer(on_next, None, on_completed) res.on_next(42) assert(next[0]) assert(not completed[0]) try: res.on_error(ex) assert(False) except Exception as e: e_ = e.args[0] assert(ex == e_) assert(not completed[0]) def test_create_on_next_on_error(): ex = 'ex' next = [True] error = [False] def on_next(x): assert(42 == x) next[0] = True def on_error(e): assert(ex == e) error[0] = True res = Observer(on_next, on_error) res.on_next(42) assert(next[0]) assert(not error[0]) res.on_error(ex) assert(error[0]) def test_create_on_next_on_error_hit_completed(): ex = 'ex' next = [True] error = [False] def on_next(x): assert(42 == x) next[0] = True def on_error(e): assert(ex == e) error[0] = True res = Observer(on_next, on_error) res.on_next(42) assert(next[0]) assert(not error[0]) res.on_completed() assert(not error[0]) def test_create_on_next_on_error_on_completed1(): ex = 'ex' next = [True] error = [False] completed = [False] def on_next(x): assert(42 == x) next[0] = True def on_error(e): assert(ex == e) error[0] = True def on_completed(): completed[0] = True res = Observer(on_next, on_error, on_completed) res.on_next(42) assert(next[0]) assert(not error[0]) assert(not completed[0]) res.on_completed() assert(completed[0]) assert(not error[0]) def test_create_on_next_on_error_on_completed2(): ex = 'ex' next = [True] error = [False] completed = [False] def on_next(x): assert(42 == x) next[0] = True def on_error(e): assert(ex == e) error[0] = True def on_completed(): completed[0] = True res = Observer(on_next, on_error, on_completed) res.on_next(42) assert(next[0]) assert(not error[0]) assert(not completed[0]) res.on_error(ex) assert(not completed[0]) assert(error[0]) def test_as_observer_hides(): obs = MyObserver() res = obs.as_observer() assert(res != obs) assert(not isinstance(res, obs.__class__)) assert(not isinstance(obs, res.__class__)) def test_as_observer_forwards(): obsn = MyObserver() obsn.as_observer().on_next(42) assert(obsn.has_on_next == 42) ex = 'ex' obse = MyObserver() obse.as_observer().on_error(ex) assert(obse.has_on_error == ex) obsc = MyObserver() obsc.as_observer().on_completed() assert(obsc.has_on_completed) def test_observer_checked_already_terminated_completed(): m, n = [0], [0] def on_next(x): m[0] += 1 def on_error(x): assert(False) def on_completed(): n[0] += 1 o = Observer(on_next, on_error, on_completed).checked() o.on_next(1) o.on_next(2) o.on_completed() assert_raises(CompletedException, o.on_completed) try: on.on_error(Exception('error')) except Exception: pass assert(2 == m[0]) assert(1 == n[0]) def test_observer_checked_already_terminated_error(): m, n = [0], [0] def on_next(x): m[0] += 1 def on_error(x): n[0] += 1 def on_completed(): assert(False) o = Observer(on_next, on_error, on_completed).checked() o.on_next(1) o.on_next(2) o.on_error(Exception('error')) try: o.on_completed() except Exception: pass try: o.on_error(Exception('error')) except Exception: pass assert(2 == m[0]) assert(1 == n[0]) def test_observer_checked_reentrant_next(): ex = "Re-entrancy detected" n = [0] def on_next(x): n[0] += 1 try: o.on_next(9) except Exception as e: assert str(e) == ex try: o.on_error(Exception('error')) except Exception as e: assert str(e) == ex try: o.on_completed() except Exception as e: assert str(e) == ex def on_error(ex): assert(False) def on_completed(): assert(False) o = Observer(on_next, on_error, on_completed).checked() o.on_next(1) assert(1 == n[0]) def test_observer_checked_reentrant_error(): msg = "Re-entrancy detected" n = [0] def on_next(x): assert(False) def on_error(ex): n[0] += 1 try: o.on_next(9) except Exception as e: assert str(e) == msg try: o.on_error(Exception('error')) except Exception as e: assert str(e) == msg try: o.on_completed() except Exception as e: assert str(e) == msg def on_completed(): assert(False) o = Observer(on_next, on_error, on_completed).checked() o.on_error(Exception('error')) assert(1 == n[0]) def test_observer_checked_reentrant_completed(): msg = "Re-entrancy detected" n = [0] def on_next(x): assert(False) def on_error(ex): assert(False) def on_completed(): n[0] += 1 try: o.on_next(9) except Exception as e: print (str(e)) assert str(e) == msg try: o.on_error(Exception('error')) except Exception as e: assert str(e) == msg try: o.on_completed() except Exception as e: assert str(e) == msg o = Observer(on_next, on_error, on_completed).checked() o.on_completed() assert(1 == n[0]) if __name__ == '__main__': test_to_notifier_forwards()
import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) from subprocess import check_output import io import bson # this is installed with the pymongo package import matplotlib.pyplot as plt from skimage.data import imread # or, whatever image library you prefer import multiprocessing as mp # will come in handy due to the size of the data import os from tqdm import * import struct from collections import defaultdict import cv2 from keras import backend as K import threading from keras.preprocessing.image import load_img, img_to_array import tensorflow as tf from keras.layers import Input, Dense from keras.models import Model from keras.preprocessing.image import Iterator from keras.preprocessing.image import ImageDataGenerator from keras import backend as K from keras.models import Sequential from keras.layers import Dropout, Flatten, Dense from keras.layers.convolutional import Conv2D from keras.layers.pooling import MaxPooling2D, GlobalAveragePooling2D from keras.callbacks import EarlyStopping, ModelCheckpoint from keras.layers.normalization import BatchNormalization from keras.layers.merge import concatenate from skimage.color import rgb2yuv ############################################################################ __GLOBAL_PARAMS__ = { 'MODEL' : "mynet" , 'DEBUG' : True, 'NORMALIZATION' : True, 'YUV' : True , 'MULTI_SCALE' : False } ######## if __GLOBAL_PARAMS__['MULTI_SCALE']: raise Exception("MULTI_SCALE not supported yet!") __MODEL__KEY__ = "" for k in sorted(__GLOBAL_PARAMS__.keys()): if not k.startswith("_"): __MODEL__KEY__ += "__" + str(k) + "_" + str(__GLOBAL_PARAMS__[k]) if (__GLOBAL_PARAMS__['DEBUG']): LOG_FILE = "simple.log" else: LOG_FILE = "log" + __MODEL__KEY__ + ".log" SUB_FILE = "sub" + __MODEL__KEY__ + ".csv.gz" import logging logging.basicConfig(format='%(asctime)s %(message)s', filename=LOG_FILE,level=logging.DEBUG) #logging.debug('This message should go to the log file') if (__GLOBAL_PARAMS__['DEBUG']): logging.info('** DEBUG: '+__MODEL__KEY__+' ****************************************************************') else: logging.info('** PRODUCTION:'+__MODEL__KEY__+' ****************************************************************') #logging.warning('And this, too') ########### -------------> FUNC def preprocess_image(x): if __GLOBAL_PARAMS__['NORMALIZATION']: x = (x - 128.0) / 128.0 if __GLOBAL_PARAMS__['YUV']: x = np.array([rgb2yuv(x.reshape((1,180,180,3)))]) x = x.reshape((180,180,3)) return x class BSONIterator(Iterator): def __init__(self, bson_file, images_df, offsets_df, num_class, image_data_generator, lock, target_size=(180, 180), with_labels=True, batch_size=32, shuffle=False, seed=None): self.file = bson_file self.images_df = images_df self.offsets_df = offsets_df self.with_labels = with_labels self.samples = len(images_df) self.num_class = num_class self.image_data_generator = image_data_generator self.target_size = tuple(target_size) self.image_shape = self.target_size + (3,) print("Found %d images belonging to %d classes." % (self.samples, self.num_class)) super(BSONIterator, self).__init__(self.samples, batch_size, shuffle, seed) self.lock = lock def _get_batches_of_transformed_samples(self, index_array): batch_x = np.zeros((len(index_array),) + self.image_shape, dtype=K.floatx()) if self.with_labels: batch_y = np.zeros((len(batch_x), self.num_class), dtype=K.floatx()) for i, j in enumerate(index_array): # Protect file and dataframe access with a lock. with self.lock: image_row = self.images_df.iloc[j] product_id = image_row["product_id"] offset_row = self.offsets_df.loc[product_id] # Read this product's data from the BSON file. self.file.seek(offset_row["offset"]) item_data = self.file.read(offset_row["length"]) # Grab the image from the product. item = bson.BSON.decode(item_data) img_idx = image_row["img_idx"] bson_img = item["imgs"][img_idx]["picture"] # Load the image. img = load_img(io.BytesIO(bson_img), target_size=self.target_size) # Preprocess the image. x = img_to_array(img) x = preprocess_image(x) #x = self.image_data_generator.random_transform(x) #x = self.image_data_generator.standardize(x) # Add the image and the label to the batch (one-hot encoded). batch_x[i] = x if self.with_labels: batch_y[i, image_row["category_idx"]] = 1 if self.with_labels: return batch_x, batch_y else: return batch_x def next(self): with self.lock: index_array = next(self.index_generator) return self._get_batches_of_transformed_samples(index_array[0]) def make_category_tables(): cat2idx = {} idx2cat = {} for ir in categories_df.itertuples(): category_id = ir[0] category_idx = ir[4] cat2idx[category_id] = category_idx idx2cat[category_idx] = category_id return cat2idx, idx2cat def read_bson(bson_path, num_records, with_categories): rows = {} with open(bson_path, "rb") as f, tqdm(total=num_records) as pbar: offset = 0 while True: item_length_bytes = f.read(4) if len(item_length_bytes) == 0: break length = struct.unpack("<i", item_length_bytes)[0] f.seek(offset) item_data = f.read(length) assert len(item_data) == length item = bson.BSON.decode(item_data) product_id = item["_id"] num_imgs = len(item["imgs"]) row = [num_imgs, offset, length] if with_categories: row += [item["category_id"]] rows[product_id] = row offset += length f.seek(offset) pbar.update() columns = ["num_imgs", "offset", "length"] if with_categories: columns += ["category_id"] df = pd.DataFrame.from_dict(rows, orient="index") df.index.name = "product_id" df.columns = columns df.sort_index(inplace=True) return df def make_val_set(df, split_percentage=0.2, drop_percentage=0.): # Find the product_ids for each category. category_dict = defaultdict(list) for ir in tqdm(df.itertuples()): category_dict[ir[4]].append(ir[0]) train_list = [] val_list = [] with tqdm(total=len(df)) as pbar: for category_id, product_ids in category_dict.items(): category_idx = cat2idx[category_id] # Randomly remove products to make the dataset smaller. keep_size = int(len(product_ids) * (1. - drop_percentage)) if keep_size < len(product_ids): product_ids = np.random.choice(product_ids, keep_size, replace=False) # Randomly choose the products that become part of the validation set. val_size = int(len(product_ids) * split_percentage) if val_size > 0: val_ids = np.random.choice(product_ids, val_size, replace=False) else: val_ids = [] # Create a new row for each image. for product_id in product_ids: row = [product_id, category_idx] for img_idx in range(df.loc[product_id, "num_imgs"]): if product_id in val_ids: val_list.append(row + [img_idx]) else: train_list.append(row + [img_idx]) pbar.update() columns = ["product_id", "category_idx", "img_idx"] train_df = pd.DataFrame(train_list, columns=columns) val_df = pd.DataFrame(val_list, columns=columns) return train_df, val_df ########### -------------> MAIN categories_path = os.path.join("data", "category_names.csv") categories_df = pd.read_csv(categories_path, index_col="category_id") # Maps the category_id to an integer index. This is what we'll use to # one-hot encode the labels. print(">>> Mapping category_id to an integer index ... ") categories_df["category_idx"] = pd.Series(range(len(categories_df)), index=categories_df.index) print(categories_df.head()) cat2idx, idx2cat = make_category_tables() # Test if it works: print(cat2idx[1000012755], idx2cat[4] , len(cat2idx)) print(">>> Train set ... ") data_dir = "data" if (__GLOBAL_PARAMS__['DEBUG']): print(">>> DEBUG mode ... ") train_bson_path = os.path.join(data_dir, "train_example.bson") num_train_products = 82 else: print(">>> PRODUCTION mode ... ") train_bson_path = os.path.join(data_dir, "train.bson") num_train_products = 7069896 test_bson_path = os.path.join(data_dir, "test.bson") num_test_products = 1768182 print(train_bson_path,num_train_products) if (not __GLOBAL_PARAMS__['DEBUG']): if os.path.isfile("train_offsets.csv"): print(">> reading from file train_offsets ... ") train_offsets_df = pd.read_csv("train_offsets.csv") train_offsets_df.set_index( "product_id" , inplace= True) train_offsets_df.sort_index(inplace=True) else: train_offsets_df = read_bson(train_bson_path, num_records=num_train_products, with_categories=True) train_offsets_df.to_csv("train_offsets.csv") print(train_offsets_df.head()) if os.path.isfile("train_images.csv"): print(">> reading from file train_images / val_images ... ") train_images_df = pd.read_csv("train_images.csv") train_images_df = train_images_df[['product_id','category_idx','img_idx']] val_images_df = pd.read_csv("val_images.csv") val_images_df = val_images_df[['product_id', 'category_idx', 'img_idx']] else: train_images_df, val_images_df = make_val_set(train_offsets_df, split_percentage=0.2, drop_percentage=0) train_images_df.to_csv("train_images.csv") val_images_df.to_csv("val_images.csv") print(train_images_df.head()) print(val_images_df.head()) categories_df.to_csv("categories.csv") else: train_offsets_df = read_bson(train_bson_path, num_records=num_train_products, with_categories=True) train_images_df, val_images_df = make_val_set(train_offsets_df, split_percentage=0.2, drop_percentage=0) print(train_images_df.head()) print(val_images_df.head()) ## Generator print(">>> Generator ... ") # Tip: use ImageDataGenerator for data augmentation and preprocessing ?? train_bson_file = open(train_bson_path, "rb") lock = threading.Lock() num_classes = len(cat2idx) num_train_images = len(train_images_df) num_val_images = len(val_images_df) batch_size = 256 train_datagen = ImageDataGenerator() train_gen = BSONIterator(train_bson_file, train_images_df, train_offsets_df, num_classes, train_datagen, lock, batch_size=batch_size, shuffle=True) val_datagen = ImageDataGenerator() val_gen = BSONIterator(train_bson_file, val_images_df, train_offsets_df, num_classes, val_datagen, lock, batch_size=batch_size, shuffle=True) ## Model inputs = Input(shape=(180, 180, 3)) x = Conv2D(32, 5, padding="valid", activation="relu")(inputs) x = BatchNormalization()(x) # hope similar to local response normalization x = MaxPooling2D(pool_size=(3, 3))(x) fl1 = Flatten()(x) x2 = Conv2D(64, 5, padding="valid", activation="relu")(x) x2 = BatchNormalization()(x2) # hope similar to local response normalization x2 = MaxPooling2D(pool_size=(3, 3))(x2) fl2 = Flatten()(x2) merged = concatenate([fl1, fl2]) # multi scale features merged = Dropout(0.5)(merged) merged = BatchNormalization()(merged) merged = Dense(2*num_classes, activation='relu')(merged) merged = Dropout(0.5)(merged) merged = BatchNormalization()(merged) predictions = Dense(num_classes, activation='softmax')(merged) model = Model(inputs=inputs, outputs=predictions) model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"]) model.summary() early_stopping = EarlyStopping(monitor='val_loss', patience=0 ) bst_model_path = "mod" + __MODEL__KEY__ + '.h5' model_checkpoint = ModelCheckpoint(bst_model_path, save_best_only=True, save_weights_only=True) # To train the model: history = model.fit_generator(train_gen, epochs=200, steps_per_epoch = num_train_images // batch_size + 1, validation_data = val_gen, validation_steps = num_val_images // batch_size + 1, callbacks=[early_stopping, model_checkpoint]) print(history.history.keys()) # logging logging.info('N. epochs == '+str(len(history.history['val_acc']))) logging.info('Val accuracy == '+str(max(history.history['val_acc']))) ## Predict on Test-set print(">>> Predicting on test-set ... ") submission_df = pd.read_csv("data/sample_submission.csv") print(submission_df.head()) test_datagen = ImageDataGenerator() data = bson.decode_file_iter(open(test_bson_path, "rb")) with tqdm(total=num_test_products) as pbar: for c, d in enumerate(data): product_id = d["_id"] num_imgs = len(d["imgs"]) batch_x = np.zeros((num_imgs, 180, 180, 3), dtype=K.floatx()) for i in range(num_imgs): bson_img = d["imgs"][i]["picture"] # Load and preprocess the image. img = load_img(io.BytesIO(bson_img), target_size=(180, 180)) x = img_to_array(img) x = preprocess_image(x) # = test_datagen.random_transform(x) # = test_datagen.standardize(x) # Add the image to the batch. batch_x[i] = x prediction = model.predict(batch_x, batch_size=num_imgs) avg_pred = prediction.mean(axis=0) cat_idx = np.argmax(avg_pred) submission_df.iloc[c]["category_id"] = idx2cat[cat_idx] pbar.update() submission_df.to_csv(SUB_FILE, compression="gzip", index=False)
import numpy as np import matplotlib.pyplot as plt import re class tight_binding(): """Returns solutions for a periodic lattice """ def __init__(self): """initialize all variables: """ self.E_s0 = 0 self.E_s1 = 0 self.E_p0 = 7.4 self.E_p1 = 7.4 self.V_ss = -15.2 self.V_s0p = 10.25 self.V_s1p = 10.25 self.V_xx = 3.0 self.V_xy = 8.30 self.kvec = None self.kvecSet = False def gen_kvec(self, start, end, nrows): """generates a k vector for use later k """ direction = end - start norm = 1 / np.linalg.norm(direction) spacing = 1 / (nrows * norm) kvec = np.outer(np.arange(nrows), direction * norm * spacing) + start self.kvec = kvec self.kvecSet = True return kvec def gen_kpath(self, pstr, precision): """ generates a path depending on the string, each letter of the string corresponds to a symmtery point in the brillouin zone. Gamma = g X = x L = l W = w U = u K = k also has the option to follow symmetry lines, however, a mix of the two formats in the string will raise an exception Delta = d Lambda = a Sigma = i S = s Z = z Q = q """ outmat = [] #print(outmat) point = re.compile('^[gxlwuk]+$') path = re.compile('^[daiszq]+$') if point.match(pstr): points = { 'g': np.array([0, 0, 0]), 'x': np.array([0, 0.5, 0.5]), 'l': np.array([0.5, 0.5, 0.5]), 'w': np.array([0.25, 0.75, 0.5]), 'u': np.array([0.25, 0.625, 0.625]), 'k': np.array([0.375, 0.75, 0.375]) } prev = 'p' # we generate a matrix of points from the symmetry points for c in pstr: if not (prev == 'p' or prev == c): #print(self.gen_kvec(points[prev], points[c], precision)) outmat.append(self.gen_kvec( points[prev], points[c], precision)) prev = c elif path.match(pstr): pass # this is actually not as simple as I thought else: print('invalid string') raise Exception pathmat = np.concatenate(outmat, axis=0) self.kvec = pathmat self.kvecSet = True print('K', pathmat) return pathmat def get_geometry(self, kvec=None): gmat = np.zeros((kvec.shape[0], 4,), dtype=np.complex128) ck1 = np.cos(kvec[:, 0] * np.pi * 0.5) ck2 = np.cos(kvec[:, 1] * np.pi * 0.5) ck3 = np.cos(kvec[:, 2] * np.pi * 0.5) sk1 = np.sin(kvec[:, 0] * np.pi * 0.5) sk2 = np.sin(kvec[:, 1] * np.pi * 0.5) sk3 = np.sin(kvec[:, 2] * np.pi * 0.5) gmat[:, 0] = (ck1 * ck2 * ck3) - (1j*(sk1 * sk2 * sk3)) gmat[:, 1] = -(ck1 * sk2 * sk3) + (1j*(sk1 * ck2 * ck3)) gmat[:, 2] = -(sk1 * ck2 * sk3) + (1j*(ck1 * sk2 * ck3)) gmat[:, 3] = -(sk1 * sk2 * ck3) + (1j*(ck1 * ck2 * sk3)) return gmat def ss_interactions(self, g): """Creates a matrix of all ss interactions """ ss_matrix = np.zeros((2, 2,), dtype=np.complex128) ss_matrix[0, 0] = self.E_s0 ss_matrix[0, 1] = g[0] * self.V_ss ss_matrix[1, 0] = g[0].conjugate() * self.V_ss ss_matrix[1, 1] = self.E_s1 return ss_matrix def sp_interactions(self, g): """Creates a matrix of all sp interactions """ sp_matrix = np.zeros((2, 6,), dtype=np.complex128) sp_matrix[0, 3] = g[1] * self.V_s0p sp_matrix[0, 4] = g[2] * self.V_s0p sp_matrix[0, 5] = g[3] * self.V_s0p sp_matrix[1, 0] = -g[1].conjugate() * self.V_s1p sp_matrix[1, 1] = -g[2].conjugate() * self.V_s1p sp_matrix[1, 2] = -g[3].conjugate() * self.V_s1p return sp_matrix def ps_interactions(self, g): """Creates a matrix of all ps interactions """ sp_matrix = np.zeros((6, 2,), dtype=np.complex128) sp_matrix[0, 1] = -g[1] * self.V_s1p sp_matrix[1, 1] = -g[2] * self.V_s1p sp_matrix[2, 1] = -g[3] * self.V_s1p sp_matrix[3, 0] = g[1].conjugate() * self.V_s0p sp_matrix[4, 0] = g[2].conjugate() * self.V_s0p sp_matrix[5, 0] = g[3].conjugate() * self.V_s0p return sp_matrix def pp_interactions(self, g): """Creates a matrix of all ps interactions """ ul = np.diag(np.ones(3,) * self.E_p0) ur = np.zeros((3, 3,), dtype=np.complex128) for i in np.arange(3): for j in np.arange(3): if i == j: ur[i, j] = g[0] * self.V_xx else: if i + j == 1: k = 3 else: k = i + j - 1 ur[i, j] = g[k] * self.V_xy ll = ur.conj() lr = np.diag(np.ones(3,) * self.E_p1) return np.concatenate((np.concatenate((ul, ur), axis=1), np.concatenate((ll, lr), axis=1)), axis=0) def create_tbmatrix(self, g): return np.concatenate((np.concatenate((self.ss_interactions(g), self.sp_interactions(g)), axis=1), np.concatenate((self.ps_interactions(g), self.pp_interactions(g)), axis=1)), axis=0) def solve_eigh(self, in_matrix): evals, evecs = np.linalg.eigh(in_matrix) return (evals, evecs) def get_full_table(self, gmat, n): out_t = np.zeros((gmat.shape[0], n+1)) #print(out_t) for i, g in enumerate(gmat): #print(g) m = self.create_tbmatrix(g) #m = self.ss_interactions(g) print('MATRIX', i, m) x, y = self.solve_eigh(m) #print(x) out_t[i, 0] = i for j in np.arange(n): out_t[i, j+1] = x[j] #print(out_t) return out_t if __name__ == '__main__': tb = tight_binding() kpath = tb.gen_kpath('lgxkg', 30) g = tb.get_geometry(kpath) print('G', g) #print(tb.get_geometry()) data = tb.get_full_table(g, 6) plt.plot(data[:,0], data[:,1]) plt.plot(data[:,0], data[:,2]) plt.plot(data[:,0], data[:,3]) plt.plot(data[:,0], data[:,4]) plt.plot(data[:,0], data[:,5]) plt.plot(data[:,0], data[:,6]) plt.show() #print(tb.create_tbmatrix())
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import warnings from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import grpc_helpers from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.ads.googleads.v9.resources.types import customer_extension_setting from google.ads.googleads.v9.services.types import ( customer_extension_setting_service, ) from .base import CustomerExtensionSettingServiceTransport, DEFAULT_CLIENT_INFO class CustomerExtensionSettingServiceGrpcTransport( CustomerExtensionSettingServiceTransport ): """gRPC backend transport for CustomerExtensionSettingService. Service to manage customer extension settings. This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation and call it. It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ def __init__( self, *, host: str = "googleads.googleapis.com", credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or application default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for grpc channel. It is ignored if ``channel`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ self._ssl_channel_credentials = ssl_channel_credentials if channel: # Sanity check: Ensure that channel and credentials are not both # provided. credentials = False # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None elif api_mtls_endpoint: warnings.warn( "api_mtls_endpoint and client_cert_source are deprecated", DeprecationWarning, ) host = ( api_mtls_endpoint if ":" in api_mtls_endpoint else api_mtls_endpoint + ":443" ) if credentials is None: credentials, _ = google.auth.default( scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id ) # Create SSL credentials with client_cert_source or application # default SSL credentials. if client_cert_source: cert, key = client_cert_source() ssl_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) else: ssl_credentials = SslCredentials().ssl_credentials # create a new channel. The provided one is ignored. self._grpc_channel = type(self).create_channel( host, credentials=credentials, credentials_file=credentials_file, ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) self._ssl_channel_credentials = ssl_credentials else: host = host if ":" in host else host + ":443" if credentials is None: credentials, _ = google.auth.default(scopes=self.AUTH_SCOPES) # create a new channel. The provided one is ignored. self._grpc_channel = type(self).create_channel( host, credentials=credentials, ssl_credentials=ssl_channel_credentials, scopes=self.AUTH_SCOPES, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) self._stubs = {} # type: Dict[str, Callable] # Run the base constructor. super().__init__( host=host, credentials=credentials, client_info=client_info, ) @classmethod def create_channel( cls, host: str = "googleads.googleapis.com", credentials: ga_credentials.Credentials = None, scopes: Optional[Sequence[str]] = None, **kwargs, ) -> grpc.Channel: """Create and return a gRPC channel object. Args: address (Optionsl[str]): The host for the channel to use. credentials (Optional[~.Credentials]): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: grpc.Channel: A gRPC channel object. """ return grpc_helpers.create_channel( host, credentials=credentials, scopes=scopes or cls.AUTH_SCOPES, **kwargs, ) def close(self): self.grpc_channel.close() @property def grpc_channel(self) -> grpc.Channel: """Return the channel designed to connect to this service. """ return self._grpc_channel @property def get_customer_extension_setting( self, ) -> Callable[ [customer_extension_setting_service.GetCustomerExtensionSettingRequest], customer_extension_setting.CustomerExtensionSetting, ]: r"""Return a callable for the get customer extension setting method over gRPC. Returns the requested customer extension setting in full detail. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `HeaderError <>`__ `InternalError <>`__ `QuotaError <>`__ `RequestError <>`__ Returns: Callable[[~.GetCustomerExtensionSettingRequest], ~.CustomerExtensionSetting]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_customer_extension_setting" not in self._stubs: self._stubs[ "get_customer_extension_setting" ] = self.grpc_channel.unary_unary( "/google.ads.googleads.v9.services.CustomerExtensionSettingService/GetCustomerExtensionSetting", request_serializer=customer_extension_setting_service.GetCustomerExtensionSettingRequest.serialize, response_deserializer=customer_extension_setting.CustomerExtensionSetting.deserialize, ) return self._stubs["get_customer_extension_setting"] @property def mutate_customer_extension_settings( self, ) -> Callable[ [ customer_extension_setting_service.MutateCustomerExtensionSettingsRequest ], customer_extension_setting_service.MutateCustomerExtensionSettingsResponse, ]: r"""Return a callable for the mutate customer extension settings method over gRPC. Creates, updates, or removes customer extension settings. Operation statuses are returned. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `CollectionSizeError <>`__ `CriterionError <>`__ `DatabaseError <>`__ `DateError <>`__ `DistinctError <>`__ `ExtensionSettingError <>`__ `FieldError <>`__ `HeaderError <>`__ `IdError <>`__ `InternalError <>`__ `ListOperationError <>`__ `MutateError <>`__ `NewResourceCreationError <>`__ `NotEmptyError <>`__ `NullError <>`__ `OperatorError <>`__ `QuotaError <>`__ `RangeError <>`__ `RequestError <>`__ `SizeLimitError <>`__ `StringFormatError <>`__ `StringLengthError <>`__ `UrlFieldError <>`__ Returns: Callable[[~.MutateCustomerExtensionSettingsRequest], ~.MutateCustomerExtensionSettingsResponse]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "mutate_customer_extension_settings" not in self._stubs: self._stubs[ "mutate_customer_extension_settings" ] = self.grpc_channel.unary_unary( "/google.ads.googleads.v9.services.CustomerExtensionSettingService/MutateCustomerExtensionSettings", request_serializer=customer_extension_setting_service.MutateCustomerExtensionSettingsRequest.serialize, response_deserializer=customer_extension_setting_service.MutateCustomerExtensionSettingsResponse.deserialize, ) return self._stubs["mutate_customer_extension_settings"] __all__ = ("CustomerExtensionSettingServiceGrpcTransport",)
# 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. # ============================================================================== """object_detection_evaluation module. ObjectDetectionEvaluation is a class which manages ground truth information of a object detection dataset, and computes frequently used detection metrics such as Precision, Recall, CorLoc of the provided detection results. It supports the following operations: 1) Add ground truth information of images sequentially. 2) Add detection result of images sequentially. 3) Evaluate detection metrics on already inserted detection results. 4) Write evaluation result into a pickle file for future processing or visualization. Note: This module operates on numpy boxes and box lists. """ from abc import ABCMeta from abc import abstractmethod import collections import logging import unicodedata import numpy as np from object_detection.core import standard_fields from object_detection.utils import label_map_util from object_detection.utils import metrics from object_detection.utils import per_image_evaluation class DetectionEvaluator(object): """Interface for object detection evalution classes. Example usage of the Evaluator: ------------------------------ evaluator = DetectionEvaluator(categories) # Detections and groundtruth for image 1. evaluator.add_single_groundtruth_image_info(...) evaluator.add_single_detected_image_info(...) # Detections and groundtruth for image 2. evaluator.add_single_groundtruth_image_info(...) evaluator.add_single_detected_image_info(...) metrics_dict = evaluator.evaluate() """ __metaclass__ = ABCMeta def __init__(self, categories): """Constructor. Args: categories: A list of dicts, each of which has the following keys - 'id': (required) an integer id uniquely identifying this category. 'name': (required) string representing category name e.g., 'cat', 'dog'. """ self._categories = categories @abstractmethod def add_single_ground_truth_image_info(self, image_id, groundtruth_dict): """Adds groundtruth for a single image to be used for evaluation. Args: image_id: A unique string/integer identifier for the image. groundtruth_dict: A dictionary of groundtruth numpy arrays required for evaluations. """ pass @abstractmethod def add_single_detected_image_info(self, image_id, detections_dict): """Adds detections for a single image to be used for evaluation. Args: image_id: A unique string/integer identifier for the image. detections_dict: A dictionary of detection numpy arrays required for evaluation. """ pass def get_estimator_eval_metric_ops(self, eval_dict): """Returns dict of metrics to use with `tf.estimator.EstimatorSpec`. Note that this must only be implemented if performing evaluation with a `tf.estimator.Estimator`. Args: eval_dict: A dictionary that holds tensors for evaluating an object detection model, returned from eval_util.result_dict_for_single_example(). Returns: A dictionary of metric names to tuple of value_op and update_op that can be used as eval metric ops in `tf.estimator.EstimatorSpec`. """ pass @abstractmethod def evaluate(self): """Evaluates detections and returns a dictionary of metrics.""" pass @abstractmethod def clear(self): """Clears the state to prepare for a fresh evaluation.""" pass class ObjectDetectionEvaluator(DetectionEvaluator): """A class to evaluate detections.""" def __init__(self, categories, matching_iou_threshold=0.5, evaluate_corlocs=False, metric_prefix=None, use_weighted_mean_ap=False, evaluate_masks=False, group_of_weight=0.0): """Constructor. Args: categories: A list of dicts, each of which has the following keys - 'id': (required) an integer id uniquely identifying this category. 'name': (required) string representing category name e.g., 'cat', 'dog'. matching_iou_threshold: IOU threshold to use for matching groundtruth boxes to detection boxes. evaluate_corlocs: (optional) boolean which determines if corloc scores are to be returned or not. metric_prefix: (optional) string prefix for metric name; if None, no prefix is used. use_weighted_mean_ap: (optional) boolean which determines if the mean average precision is computed directly from the scores and tp_fp_labels of all classes. evaluate_masks: If False, evaluation will be performed based on boxes. If True, mask evaluation will be performed instead. group_of_weight: Weight of group-of boxes.If set to 0, detections of the correct class within a group-of box are ignored. If weight is > 0, then if at least one detection falls within a group-of box with matching_iou_threshold, weight group_of_weight is added to true positives. Consequently, if no detection falls within a group-of box, weight group_of_weight is added to false negatives. Raises: ValueError: If the category ids are not 1-indexed. """ super(ObjectDetectionEvaluator, self).__init__(categories) self._num_classes = max([cat['id'] for cat in categories]) if min(cat['id'] for cat in categories) < 1: raise ValueError('Classes should be 1-indexed.') self._matching_iou_threshold = matching_iou_threshold self._use_weighted_mean_ap = use_weighted_mean_ap self._label_id_offset = 1 self._evaluate_masks = evaluate_masks self._group_of_weight = group_of_weight self._evaluation = ObjectDetectionEvaluation( num_groundtruth_classes=self._num_classes, matching_iou_threshold=self._matching_iou_threshold, use_weighted_mean_ap=self._use_weighted_mean_ap, label_id_offset=self._label_id_offset, group_of_weight=self._group_of_weight) self._image_ids = set([]) self._evaluate_corlocs = evaluate_corlocs self._metric_prefix = (metric_prefix + '_') if metric_prefix else '' def add_single_ground_truth_image_info(self, image_id, groundtruth_dict): """Adds groundtruth for a single image to be used for evaluation. Args: image_id: A unique string/integer identifier for the image. groundtruth_dict: A dictionary containing - standard_fields.InputDataFields.groundtruth_boxes: float32 numpy array of shape [num_boxes, 4] containing `num_boxes` groundtruth boxes of the format [ymin, xmin, ymax, xmax] in absolute image coordinates. standard_fields.InputDataFields.groundtruth_classes: integer numpy array of shape [num_boxes] containing 1-indexed groundtruth classes for the boxes. standard_fields.InputDataFields.groundtruth_difficult: Optional length M numpy boolean array denoting whether a ground truth box is a difficult instance or not. This field is optional to support the case that no boxes are difficult. standard_fields.InputDataFields.groundtruth_instance_masks: Optional numpy array of shape [num_boxes, height, width] with values in {0, 1}. Raises: ValueError: On adding groundtruth for an image more than once. Will also raise error if instance masks are not in groundtruth dictionary. """ if image_id in self._image_ids: raise ValueError('Image with id {} already added.'.format(image_id)) groundtruth_classes = ( groundtruth_dict[standard_fields.InputDataFields.groundtruth_classes] - self._label_id_offset) # If the key is not present in the groundtruth_dict or the array is empty # (unless there are no annotations for the groundtruth on this image) # use values from the dictionary or insert None otherwise. if (standard_fields.InputDataFields.groundtruth_difficult in groundtruth_dict.keys() and (groundtruth_dict[standard_fields.InputDataFields.groundtruth_difficult] .size or not groundtruth_classes.size)): groundtruth_difficult = groundtruth_dict[ standard_fields.InputDataFields.groundtruth_difficult] else: groundtruth_difficult = None if not len(self._image_ids) % 1000: logging.warn( 'image %s does not have groundtruth difficult flag specified', image_id) groundtruth_masks = None if self._evaluate_masks: if (standard_fields.InputDataFields.groundtruth_instance_masks not in groundtruth_dict): raise ValueError('Instance masks not in groundtruth dictionary.') groundtruth_masks = groundtruth_dict[ standard_fields.InputDataFields.groundtruth_instance_masks] self._evaluation.add_single_ground_truth_image_info( image_key=image_id, groundtruth_boxes=groundtruth_dict[ standard_fields.InputDataFields.groundtruth_boxes], groundtruth_class_labels=groundtruth_classes, groundtruth_is_difficult_list=groundtruth_difficult, groundtruth_masks=groundtruth_masks) self._image_ids.update([image_id]) def add_single_detected_image_info(self, image_id, detections_dict): """Adds detections for a single image to be used for evaluation. Args: image_id: A unique string/integer identifier for the image. detections_dict: A dictionary containing - standard_fields.DetectionResultFields.detection_boxes: float32 numpy array of shape [num_boxes, 4] containing `num_boxes` detection boxes of the format [ymin, xmin, ymax, xmax] in absolute image coordinates. standard_fields.DetectionResultFields.detection_scores: float32 numpy array of shape [num_boxes] containing detection scores for the boxes. standard_fields.DetectionResultFields.detection_classes: integer numpy array of shape [num_boxes] containing 1-indexed detection classes for the boxes. standard_fields.DetectionResultFields.detection_masks: uint8 numpy array of shape [num_boxes, height, width] containing `num_boxes` masks of values ranging between 0 and 1. Raises: ValueError: If detection masks are not in detections dictionary. """ detection_classes = ( detections_dict[standard_fields.DetectionResultFields.detection_classes] - self._label_id_offset) detection_masks = None if self._evaluate_masks: if (standard_fields.DetectionResultFields.detection_masks not in detections_dict): raise ValueError('Detection masks not in detections dictionary.') detection_masks = detections_dict[ standard_fields.DetectionResultFields.detection_masks] self._evaluation.add_single_detected_image_info( image_key=image_id, detected_boxes=detections_dict[ standard_fields.DetectionResultFields.detection_boxes], detected_scores=detections_dict[ standard_fields.DetectionResultFields.detection_scores], detected_class_labels=detection_classes, detected_masks=detection_masks) def evaluate(self): """Compute evaluation result. Returns: A dictionary of metrics with the following fields - 1. summary_metrics: 'Precision/mAP@<matching_iou_threshold>IOU': mean average precision at the specified IOU threshold. 2. per_category_ap: category specific results with keys of the form 'PerformanceByCategory/mAP@<matching_iou_threshold>IOU/category'. """ (per_class_ap, mean_ap, _, _, per_class_corloc, mean_corloc) = ( self._evaluation.evaluate()) pascal_metrics = { self._metric_prefix + 'Precision/mAP@{}IOU'.format(self._matching_iou_threshold): mean_ap } if self._evaluate_corlocs: pascal_metrics[self._metric_prefix + 'Precision/meanCorLoc@{}IOU'.format( self._matching_iou_threshold)] = mean_corloc category_index = label_map_util.create_category_index(self._categories) for idx in range(per_class_ap.size): if idx + self._label_id_offset in category_index: category_name = category_index[idx + self._label_id_offset]['name'] try: category_name = unicode(category_name, 'utf-8') except TypeError: pass category_name = unicodedata.normalize( 'NFKD', category_name).encode('ascii', 'ignore') display_name = ( self._metric_prefix + 'PerformanceByCategory/AP@{}IOU/{}'.format( self._matching_iou_threshold, category_name)) pascal_metrics[display_name] = per_class_ap[idx] # Optionally add CorLoc metrics.classes if self._evaluate_corlocs: display_name = ( self._metric_prefix + 'PerformanceByCategory/CorLoc@{}IOU/{}' .format(self._matching_iou_threshold, category_name)) pascal_metrics[display_name] = per_class_corloc[idx] return pascal_metrics def clear(self): """Clears the state to prepare for a fresh evaluation.""" self._evaluation = ObjectDetectionEvaluation( num_groundtruth_classes=self._num_classes, matching_iou_threshold=self._matching_iou_threshold, use_weighted_mean_ap=self._use_weighted_mean_ap, label_id_offset=self._label_id_offset) self._image_ids.clear() class PascalDetectionEvaluator(ObjectDetectionEvaluator): """A class to evaluate detections using PASCAL metrics.""" def __init__(self, categories, matching_iou_threshold=0.5): super(PascalDetectionEvaluator, self).__init__( categories, matching_iou_threshold=matching_iou_threshold, evaluate_corlocs=False, metric_prefix='PascalBoxes', use_weighted_mean_ap=False) class WeightedPascalDetectionEvaluator(ObjectDetectionEvaluator): """A class to evaluate detections using weighted PASCAL metrics. Weighted PASCAL metrics computes the mean average precision as the average precision given the scores and tp_fp_labels of all classes. In comparison, PASCAL metrics computes the mean average precision as the mean of the per-class average precisions. This definition is very similar to the mean of the per-class average precisions weighted by class frequency. However, they are typically not the same as the average precision is not a linear function of the scores and tp_fp_labels. """ def __init__(self, categories, matching_iou_threshold=0.5): super(WeightedPascalDetectionEvaluator, self).__init__( categories, matching_iou_threshold=matching_iou_threshold, evaluate_corlocs=False, metric_prefix='WeightedPascalBoxes', use_weighted_mean_ap=True) class PascalInstanceSegmentationEvaluator(ObjectDetectionEvaluator): """A class to evaluate instance masks using PASCAL metrics.""" def __init__(self, categories, matching_iou_threshold=0.5): super(PascalInstanceSegmentationEvaluator, self).__init__( categories, matching_iou_threshold=matching_iou_threshold, evaluate_corlocs=False, metric_prefix='PascalMasks', use_weighted_mean_ap=False, evaluate_masks=True) class WeightedPascalInstanceSegmentationEvaluator(ObjectDetectionEvaluator): """A class to evaluate instance masks using weighted PASCAL metrics. Weighted PASCAL metrics computes the mean average precision as the average precision given the scores and tp_fp_labels of all classes. In comparison, PASCAL metrics computes the mean average precision as the mean of the per-class average precisions. This definition is very similar to the mean of the per-class average precisions weighted by class frequency. However, they are typically not the same as the average precision is not a linear function of the scores and tp_fp_labels. """ def __init__(self, categories, matching_iou_threshold=0.5): super(WeightedPascalInstanceSegmentationEvaluator, self).__init__( categories, matching_iou_threshold=matching_iou_threshold, evaluate_corlocs=False, metric_prefix='WeightedPascalMasks', use_weighted_mean_ap=True, evaluate_masks=True) class OpenImagesDetectionEvaluator(ObjectDetectionEvaluator): """A class to evaluate detections using Open Images V2 metrics. Open Images V2 introduce group_of type of bounding boxes and this metric handles those boxes appropriately. """ def __init__(self, categories, matching_iou_threshold=0.5, evaluate_corlocs=False, metric_prefix='OpenImagesV2', group_of_weight=0.0): """Constructor. Args: categories: A list of dicts, each of which has the following keys - 'id': (required) an integer id uniquely identifying this category. 'name': (required) string representing category name e.g., 'cat', 'dog'. matching_iou_threshold: IOU threshold to use for matching groundtruth boxes to detection boxes. evaluate_corlocs: if True, additionally evaluates and returns CorLoc. metric_prefix: Prefix name of the metric. group_of_weight: Weight of the group-of bounding box. If set to 0 (default for Open Images V2 detection protocol), detections of the correct class within a group-of box are ignored. If weight is > 0, then if at least one detection falls within a group-of box with matching_iou_threshold, weight group_of_weight is added to true positives. Consequently, if no detection falls within a group-of box, weight group_of_weight is added to false negatives. """ super(OpenImagesDetectionEvaluator, self).__init__( categories, matching_iou_threshold, evaluate_corlocs, metric_prefix=metric_prefix, group_of_weight=group_of_weight) def add_single_ground_truth_image_info(self, image_id, groundtruth_dict): """Adds groundtruth for a single image to be used for evaluation. Args: image_id: A unique string/integer identifier for the image. groundtruth_dict: A dictionary containing - standard_fields.InputDataFields.groundtruth_boxes: float32 numpy array of shape [num_boxes, 4] containing `num_boxes` groundtruth boxes of the format [ymin, xmin, ymax, xmax] in absolute image coordinates. standard_fields.InputDataFields.groundtruth_classes: integer numpy array of shape [num_boxes] containing 1-indexed groundtruth classes for the boxes. standard_fields.InputDataFields.groundtruth_group_of: Optional length M numpy boolean array denoting whether a groundtruth box contains a group of instances. Raises: ValueError: On adding groundtruth for an image more than once. """ if image_id in self._image_ids: raise ValueError('Image with id {} already added.'.format(image_id)) groundtruth_classes = ( groundtruth_dict[standard_fields.InputDataFields.groundtruth_classes] - self._label_id_offset) # If the key is not present in the groundtruth_dict or the array is empty # (unless there are no annotations for the groundtruth on this image) # use values from the dictionary or insert None otherwise. if (standard_fields.InputDataFields.groundtruth_group_of in groundtruth_dict.keys() and (groundtruth_dict[standard_fields.InputDataFields.groundtruth_group_of] .size or not groundtruth_classes.size)): groundtruth_group_of = groundtruth_dict[ standard_fields.InputDataFields.groundtruth_group_of] else: groundtruth_group_of = None if not len(self._image_ids) % 1000: logging.warn( 'image %s does not have groundtruth group_of flag specified', image_id) self._evaluation.add_single_ground_truth_image_info( image_id, groundtruth_dict[standard_fields.InputDataFields.groundtruth_boxes], groundtruth_classes, groundtruth_is_difficult_list=None, groundtruth_is_group_of_list=groundtruth_group_of) self._image_ids.update([image_id]) class OpenImagesDetectionChallengeEvaluator(OpenImagesDetectionEvaluator): """A class implements Open Images Challenge Detection metrics. Open Images Challenge Detection metric has two major changes in comparison with Open Images V2 detection metric: - a custom weight might be specified for detecting an object contained in a group-of box. - verified image-level labels should be explicitelly provided for evaluation: in case in image has neither positive nor negative image level label of class c, all detections of this class on this image will be ignored. """ def __init__(self, categories, matching_iou_threshold=0.5, evaluate_corlocs=False, group_of_weight=1.0): """Constructor. Args: categories: A list of dicts, each of which has the following keys - 'id': (required) an integer id uniquely identifying this category. 'name': (required) string representing category name e.g., 'cat', 'dog'. matching_iou_threshold: IOU threshold to use for matching groundtruth boxes to detection boxes. evaluate_corlocs: if True, additionally evaluates and returns CorLoc. group_of_weight: weight of a group-of box. If set to 0, detections of the correct class within a group-of box are ignored. If weight is > 0 (default for Open Images Detection Challenge 2018), then if at least one detection falls within a group-of box with matching_iou_threshold, weight group_of_weight is added to true positives. Consequently, if no detection falls within a group-of box, weight group_of_weight is added to false negatives. """ super(OpenImagesDetectionChallengeEvaluator, self).__init__( categories, matching_iou_threshold, evaluate_corlocs, metric_prefix='OpenImagesChallenge2018', group_of_weight=group_of_weight) self._evaluatable_labels = {} def add_single_ground_truth_image_info(self, image_id, groundtruth_dict): """Adds groundtruth for a single image to be used for evaluation. Args: image_id: A unique string/integer identifier for the image. groundtruth_dict: A dictionary containing - standard_fields.InputDataFields.groundtruth_boxes: float32 numpy array of shape [num_boxes, 4] containing `num_boxes` groundtruth boxes of the format [ymin, xmin, ymax, xmax] in absolute image coordinates. standard_fields.InputDataFields.groundtruth_classes: integer numpy array of shape [num_boxes] containing 1-indexed groundtruth classes for the boxes. standard_fields.InputDataFields.groundtruth_image_classes: integer 1D numpy array containing all classes for which labels are verified. standard_fields.InputDataFields.groundtruth_group_of: Optional length M numpy boolean array denoting whether a groundtruth box contains a group of instances. Raises: ValueError: On adding groundtruth for an image more than once. """ super(OpenImagesDetectionChallengeEvaluator, self).add_single_ground_truth_image_info(image_id, groundtruth_dict) groundtruth_classes = ( groundtruth_dict[standard_fields.InputDataFields.groundtruth_classes] - self._label_id_offset) self._evaluatable_labels[image_id] = np.unique( np.concatenate(((groundtruth_dict.get( standard_fields.InputDataFields.groundtruth_image_classes, np.array([], dtype=int)) - self._label_id_offset), groundtruth_classes))) def add_single_detected_image_info(self, image_id, detections_dict): """Adds detections for a single image to be used for evaluation. Args: image_id: A unique string/integer identifier for the image. detections_dict: A dictionary containing - standard_fields.DetectionResultFields.detection_boxes: float32 numpy array of shape [num_boxes, 4] containing `num_boxes` detection boxes of the format [ymin, xmin, ymax, xmax] in absolute image coordinates. standard_fields.DetectionResultFields.detection_scores: float32 numpy array of shape [num_boxes] containing detection scores for the boxes. standard_fields.DetectionResultFields.detection_classes: integer numpy array of shape [num_boxes] containing 1-indexed detection classes for the boxes. Raises: ValueError: If detection masks are not in detections dictionary. """ if image_id not in self._image_ids: # Since for the correct work of evaluator it is assumed that groundtruth # is inserted first we make sure to break the code if is it not the case. self._image_ids.update([image_id]) self._evaluatable_labels[image_id] = np.array([]) detection_classes = ( detections_dict[standard_fields.DetectionResultFields.detection_classes] - self._label_id_offset) allowed_classes = np.where( np.isin(detection_classes, self._evaluatable_labels[image_id])) detection_classes = detection_classes[allowed_classes] detected_boxes = detections_dict[ standard_fields.DetectionResultFields.detection_boxes][allowed_classes] detected_scores = detections_dict[ standard_fields.DetectionResultFields.detection_scores][allowed_classes] self._evaluation.add_single_detected_image_info( image_key=image_id, detected_boxes=detected_boxes, detected_scores=detected_scores, detected_class_labels=detection_classes) def clear(self): """Clears stored data.""" super(OpenImagesDetectionChallengeEvaluator, self).clear() self._evaluatable_labels.clear() ObjectDetectionEvalMetrics = collections.namedtuple( 'ObjectDetectionEvalMetrics', [ 'average_precisions', 'mean_ap', 'precisions', 'recalls', 'corlocs', 'mean_corloc' ]) class ObjectDetectionEvaluation(object): """Internal implementation of Pascal object detection metrics.""" def __init__(self, num_groundtruth_classes, matching_iou_threshold=0.5, nms_iou_threshold=1.0, nms_max_output_boxes=10000, use_weighted_mean_ap=False, label_id_offset=0, group_of_weight=0.0, per_image_eval_class=per_image_evaluation.PerImageEvaluation): """Constructor. Args: num_groundtruth_classes: Number of ground-truth classes. matching_iou_threshold: IOU threshold used for matching detected boxes to ground-truth boxes. nms_iou_threshold: IOU threshold used for non-maximum suppression. nms_max_output_boxes: Maximum number of boxes returned by non-maximum suppression. use_weighted_mean_ap: (optional) boolean which determines if the mean average precision is computed directly from the scores and tp_fp_labels of all classes. label_id_offset: The label id offset. group_of_weight: Weight of group-of boxes.If set to 0, detections of the correct class within a group-of box are ignored. If weight is > 0, then if at least one detection falls within a group-of box with matching_iou_threshold, weight group_of_weight is added to true positives. Consequently, if no detection falls within a group-of box, weight group_of_weight is added to false negatives. per_image_eval_class: The class that contains functions for computing per image metrics. Raises: ValueError: if num_groundtruth_classes is smaller than 1. """ if num_groundtruth_classes < 1: raise ValueError('Need at least 1 groundtruth class for evaluation.') self.per_image_eval = per_image_eval_class( num_groundtruth_classes=num_groundtruth_classes, matching_iou_threshold=matching_iou_threshold, nms_iou_threshold=nms_iou_threshold, nms_max_output_boxes=nms_max_output_boxes, group_of_weight=group_of_weight) self.group_of_weight = group_of_weight self.num_class = num_groundtruth_classes self.use_weighted_mean_ap = use_weighted_mean_ap self.label_id_offset = label_id_offset self.groundtruth_boxes = {} self.groundtruth_class_labels = {} self.groundtruth_masks = {} self.groundtruth_is_difficult_list = {} self.groundtruth_is_group_of_list = {} self.num_gt_instances_per_class = np.zeros(self.num_class, dtype=float) self.num_gt_imgs_per_class = np.zeros(self.num_class, dtype=int) self._initialize_detections() def _initialize_detections(self): """Initializes internal data structures.""" self.detection_keys = set() self.scores_per_class = [[] for _ in range(self.num_class)] self.tp_fp_labels_per_class = [[] for _ in range(self.num_class)] self.num_images_correctly_detected_per_class = np.zeros(self.num_class) self.average_precision_per_class = np.empty(self.num_class, dtype=float) self.average_precision_per_class.fill(np.nan) self.precisions_per_class = [np.nan] * self.num_class self.recalls_per_class = [np.nan] * self.num_class self.corloc_per_class = np.ones(self.num_class, dtype=float) def clear_detections(self): self._initialize_detections() def add_single_ground_truth_image_info(self, image_key, groundtruth_boxes, groundtruth_class_labels, groundtruth_is_difficult_list=None, groundtruth_is_group_of_list=None, groundtruth_masks=None): """Adds groundtruth for a single image to be used for evaluation. Args: image_key: A unique string/integer identifier for the image. groundtruth_boxes: float32 numpy array of shape [num_boxes, 4] containing `num_boxes` groundtruth boxes of the format [ymin, xmin, ymax, xmax] in absolute image coordinates. groundtruth_class_labels: integer numpy array of shape [num_boxes] containing 0-indexed groundtruth classes for the boxes. groundtruth_is_difficult_list: A length M numpy boolean array denoting whether a ground truth box is a difficult instance or not. To support the case that no boxes are difficult, it is by default set as None. groundtruth_is_group_of_list: A length M numpy boolean array denoting whether a ground truth box is a group-of box or not. To support the case that no boxes are groups-of, it is by default set as None. groundtruth_masks: uint8 numpy array of shape [num_boxes, height, width] containing `num_boxes` groundtruth masks. The mask values range from 0 to 1. """ if image_key in self.groundtruth_boxes: logging.warn( 'image %s has already been added to the ground truth database.', image_key) return self.groundtruth_boxes[image_key] = groundtruth_boxes self.groundtruth_class_labels[image_key] = groundtruth_class_labels self.groundtruth_masks[image_key] = groundtruth_masks if groundtruth_is_difficult_list is None: num_boxes = groundtruth_boxes.shape[0] groundtruth_is_difficult_list = np.zeros(num_boxes, dtype=bool) self.groundtruth_is_difficult_list[ image_key] = groundtruth_is_difficult_list.astype(dtype=bool) if groundtruth_is_group_of_list is None: num_boxes = groundtruth_boxes.shape[0] groundtruth_is_group_of_list = np.zeros(num_boxes, dtype=bool) self.groundtruth_is_group_of_list[ image_key] = groundtruth_is_group_of_list.astype(dtype=bool) self._update_ground_truth_statistics( groundtruth_class_labels, groundtruth_is_difficult_list.astype(dtype=bool), groundtruth_is_group_of_list.astype(dtype=bool)) def add_single_detected_image_info(self, image_key, detected_boxes, detected_scores, detected_class_labels, detected_masks=None): """Adds detections for a single image to be used for evaluation. Args: image_key: A unique string/integer identifier for the image. detected_boxes: float32 numpy array of shape [num_boxes, 4] containing `num_boxes` detection boxes of the format [ymin, xmin, ymax, xmax] in absolute image coordinates. detected_scores: float32 numpy array of shape [num_boxes] containing detection scores for the boxes. detected_class_labels: integer numpy array of shape [num_boxes] containing 0-indexed detection classes for the boxes. detected_masks: np.uint8 numpy array of shape [num_boxes, height, width] containing `num_boxes` detection masks with values ranging between 0 and 1. Raises: ValueError: if the number of boxes, scores and class labels differ in length. """ if (len(detected_boxes) != len(detected_scores) or len(detected_boxes) != len(detected_class_labels)): raise ValueError('detected_boxes, detected_scores and ' 'detected_class_labels should all have same lengths. Got' '[%d, %d, %d]' % len(detected_boxes), len(detected_scores), len(detected_class_labels)) if image_key in self.detection_keys: logging.warn( 'image %s has already been added to the detection result database', image_key) return self.detection_keys.add(image_key) if image_key in self.groundtruth_boxes: groundtruth_boxes = self.groundtruth_boxes[image_key] groundtruth_class_labels = self.groundtruth_class_labels[image_key] # Masks are popped instead of look up. The reason is that we do not want # to keep all masks in memory which can cause memory overflow. groundtruth_masks = self.groundtruth_masks.pop( image_key) groundtruth_is_difficult_list = self.groundtruth_is_difficult_list[ image_key] groundtruth_is_group_of_list = self.groundtruth_is_group_of_list[ image_key] else: groundtruth_boxes = np.empty(shape=[0, 4], dtype=float) groundtruth_class_labels = np.array([], dtype=int) if detected_masks is None: groundtruth_masks = None else: groundtruth_masks = np.empty(shape=[0, 1, 1], dtype=float) groundtruth_is_difficult_list = np.array([], dtype=bool) groundtruth_is_group_of_list = np.array([], dtype=bool) scores, tp_fp_labels, is_class_correctly_detected_in_image = ( self.per_image_eval.compute_object_detection_metrics( detected_boxes=detected_boxes, detected_scores=detected_scores, detected_class_labels=detected_class_labels, groundtruth_boxes=groundtruth_boxes, groundtruth_class_labels=groundtruth_class_labels, groundtruth_is_difficult_list=groundtruth_is_difficult_list, groundtruth_is_group_of_list=groundtruth_is_group_of_list, detected_masks=detected_masks, groundtruth_masks=groundtruth_masks)) for i in range(self.num_class): if scores[i].shape[0] > 0: self.scores_per_class[i].append(scores[i]) self.tp_fp_labels_per_class[i].append(tp_fp_labels[i]) (self.num_images_correctly_detected_per_class ) += is_class_correctly_detected_in_image def _update_ground_truth_statistics(self, groundtruth_class_labels, groundtruth_is_difficult_list, groundtruth_is_group_of_list): """Update grouth truth statitistics. 1. Difficult boxes are ignored when counting the number of ground truth instances as done in Pascal VOC devkit. 2. Difficult boxes are treated as normal boxes when computing CorLoc related statitistics. Args: groundtruth_class_labels: An integer numpy array of length M, representing M class labels of object instances in ground truth groundtruth_is_difficult_list: A boolean numpy array of length M denoting whether a ground truth box is a difficult instance or not groundtruth_is_group_of_list: A boolean numpy array of length M denoting whether a ground truth box is a group-of box or not """ for class_index in range(self.num_class): num_gt_instances = np.sum(groundtruth_class_labels[ ~groundtruth_is_difficult_list & ~groundtruth_is_group_of_list] == class_index) num_groupof_gt_instances = self.group_of_weight * np.sum( groundtruth_class_labels[groundtruth_is_group_of_list] == class_index) self.num_gt_instances_per_class[ class_index] += num_gt_instances + num_groupof_gt_instances if np.any(groundtruth_class_labels == class_index): self.num_gt_imgs_per_class[class_index] += 1 def evaluate(self): """Compute evaluation result. Returns: A named tuple with the following fields - average_precision: float numpy array of average precision for each class. mean_ap: mean average precision of all classes, float scalar precisions: List of precisions, each precision is a float numpy array recalls: List of recalls, each recall is a float numpy array corloc: numpy float array mean_corloc: Mean CorLoc score for each class, float scalar """ if (self.num_gt_instances_per_class == 0).any(): logging.warn( 'The following classes have no ground truth examples: %s', np.squeeze(np.argwhere(self.num_gt_instances_per_class == 0)) + self.label_id_offset) if self.use_weighted_mean_ap: all_scores = np.array([], dtype=float) all_tp_fp_labels = np.array([], dtype=bool) for class_index in range(self.num_class): if self.num_gt_instances_per_class[class_index] == 0: continue if not self.scores_per_class[class_index]: scores = np.array([], dtype=float) tp_fp_labels = np.array([], dtype=float) else: scores = np.concatenate(self.scores_per_class[class_index]) tp_fp_labels = np.concatenate(self.tp_fp_labels_per_class[class_index]) if self.use_weighted_mean_ap: all_scores = np.append(all_scores, scores) all_tp_fp_labels = np.append(all_tp_fp_labels, tp_fp_labels) logging.info('Scores and tpfp per class label: %d', class_index) logging.info(tp_fp_labels) logging.info(scores) precision, recall = metrics.compute_precision_recall( scores, tp_fp_labels, self.num_gt_instances_per_class[class_index]) self.precisions_per_class[class_index] = precision self.recalls_per_class[class_index] = recall average_precision = metrics.compute_average_precision(precision, recall) self.average_precision_per_class[class_index] = average_precision self.corloc_per_class = metrics.compute_cor_loc( self.num_gt_imgs_per_class, self.num_images_correctly_detected_per_class) if self.use_weighted_mean_ap: num_gt_instances = np.sum(self.num_gt_instances_per_class) precision, recall = metrics.compute_precision_recall( all_scores, all_tp_fp_labels, num_gt_instances) mean_ap = metrics.compute_average_precision(precision, recall) else: mean_ap = np.nanmean(self.average_precision_per_class) mean_corloc = np.nanmean(self.corloc_per_class) return ObjectDetectionEvalMetrics( self.average_precision_per_class, mean_ap, self.precisions_per_class, self.recalls_per_class, self.corloc_per_class, mean_corloc)
""" Tests for Spout class """ from __future__ import absolute_import, print_function, unicode_literals import logging import unittest from io import BytesIO try: from unittest.mock import patch except ImportError: from mock import patch from pystorm import ReliableSpout, Spout, Tuple class SpoutTests(unittest.TestCase): def setUp(self): self.tup_dict = { "id": 14, "comp": "some_spout", "stream": "default", "task": "some_spout", "tuple": [1, 2, 3], } self.tup = Tuple( self.tup_dict["id"], self.tup_dict["comp"], self.tup_dict["stream"], self.tup_dict["task"], self.tup_dict["tuple"], ) self.spout = Spout(input_stream=BytesIO(), output_stream=BytesIO()) self.spout.initialize({}, {}) self.spout.logger = logging.getLogger(__name__) @patch.object(Spout, "send_message", autospec=True) def test_emit(self, send_message_mock): # A basic emit self.spout.emit([1, 2, 3], need_task_ids=False) send_message_mock.assert_called_with( self.spout, {"command": "emit", "tuple": [1, 2, 3], "need_task_ids": False} ) # Emit as a direct task self.spout.emit([1, 2, 3], direct_task="other_spout") send_message_mock.assert_called_with( self.spout, { "command": "emit", "tuple": [1, 2, 3], "task": "other_spout", "need_task_ids": False, }, ) # Reliable emit self.spout.emit([1, 2, 3], tup_id="foo", need_task_ids=False) send_message_mock.assert_called_with( self.spout, { "command": "emit", "tuple": [1, 2, 3], "need_task_ids": False, "id": "foo", }, ) # Reliable emit as direct task self.spout.emit([1, 2, 3], tup_id="foo", direct_task="other_spout") send_message_mock.assert_called_with( self.spout, { "command": "emit", "tuple": [1, 2, 3], "task": "other_spout", "id": "foo", "need_task_ids": False, }, ) @patch.object( Spout, "read_command", autospec=True, return_value={"command": "ack", "id": 1234}, ) @patch.object(Spout, "ack", autospec=True) def test_ack(self, ack_mock, read_command_mock): # Make sure ack gets called self.spout._run() read_command_mock.assert_called_with(self.spout) ack_mock.assert_called_with(self.spout, 1234) @patch.object( Spout, "read_command", autospec=True, return_value={"command": "fail", "id": 1234}, ) @patch.object(Spout, "fail", autospec=True) def test_fail(self, fail_mock, read_command_mock): # Make sure fail gets called self.spout._run() read_command_mock.assert_called_with(self.spout) fail_mock.assert_called_with(self.spout, 1234) @patch.object( Spout, "read_command", autospec=True, return_value={"command": "next", "id": 1234}, ) @patch.object(Spout, "next_tuple", autospec=True) def test_next_tuple(self, next_tuple_mock, read_command_mock): self.spout._run() read_command_mock.assert_called_with(self.spout) self.assertEqual(next_tuple_mock.call_count, 1) @patch.object( Spout, "read_command", autospec=True, return_value={"command": "activate", "id": 1234}, ) @patch.object(Spout, "activate", autospec=True) def test_activate(self, activate_mock, read_command_mock): self.spout._run() read_command_mock.assert_called_with(self.spout) self.assertEqual(activate_mock.call_count, 1) @patch.object( Spout, "read_command", autospec=True, return_value={"command": "deactivate", "id": 1234}, ) @patch.object(Spout, "deactivate", autospec=True) def test_deactivate(self, deactivate_mock, read_command_mock): self.spout._run() read_command_mock.assert_called_with(self.spout) self.assertEqual(deactivate_mock.call_count, 1) class ReliableSpoutTests(unittest.TestCase): def setUp(self): self.tup_dict = { "id": 14, "comp": "some_spout", "stream": "default", "task": "some_spout", "tuple": [1, 2, 3], } self.tup = Tuple( self.tup_dict["id"], self.tup_dict["comp"], self.tup_dict["stream"], self.tup_dict["task"], self.tup_dict["tuple"], ) self.spout = ReliableSpout(input_stream=BytesIO(), output_stream=BytesIO()) self.spout.initialize({}, {}) self.spout.logger = logging.getLogger(__name__) @patch.object(ReliableSpout, "send_message", autospec=True) def test_emit_unreliable(self, send_message_mock): # An unreliable emit is not allowed with ReliableSpout with self.assertRaises(ValueError): self.spout.emit([1, 2, 3], need_task_ids=False) @patch.object(ReliableSpout, "send_message", autospec=True) def test_emit_reliable(self, send_message_mock): # Reliable emit self.spout.emit([1, 2, 3], tup_id="foo", need_task_ids=False) send_message_mock.assert_called_with( self.spout, { "command": "emit", "tuple": [1, 2, 3], "need_task_ids": False, "id": "foo", }, ) self.assertEqual( self.spout.unacked_tuples.get("foo"), ([1, 2, 3], None, None, False) ) @patch.object(ReliableSpout, "send_message", autospec=True) def test_emit_reliable_direct(self, send_message_mock): # Reliable emit as direct task self.spout.emit([1, 2, 3], tup_id="foo", direct_task="other_spout") send_message_mock.assert_called_with( self.spout, { "command": "emit", "tuple": [1, 2, 3], "task": "other_spout", "id": "foo", "need_task_ids": False, }, ) self.assertEqual( self.spout.unacked_tuples.get("foo"), ([1, 2, 3], None, "other_spout", False), ) def test_ack(self): self.spout.failed_tuples["foo"] = 2 self.spout.unacked_tuples["foo"] = ([1, 2, 3], None, None, True) # Make sure ack cleans up failed_tuples and unacked_tuples self.spout.ack("foo") self.assertNotIn("foo", self.spout.failed_tuples) self.assertNotIn("foo", self.spout.unacked_tuples) @patch.object(ReliableSpout, "emit", autospec=True) def test_fail_below_limit(self, emit_mock): # Make sure fail increments failed_tuples and calls emit self.spout.max_fails = 3 self.spout.failed_tuples["foo"] = 2 self.spout.unacked_tuples["foo"] = ([1, 2, 3], None, None, True) self.spout.fail("foo") self.assertEqual(self.spout.failed_tuples["foo"], 3) emit_mock.assert_called_with( self.spout, [1, 2, 3], direct_task=None, need_task_ids=True, stream=None, tup_id="foo", ) @patch.object(ReliableSpout, "ack", autospec=True) @patch.object(ReliableSpout, "emit", autospec=True) def test_fail_above_limit(self, emit_mock, ack_mock): # Make sure fail increments failed_tuples self.spout.max_fails = 3 self.spout.failed_tuples["foo"] = 3 emit_args = ([1, 2, 3], None, None, True) self.spout.unacked_tuples["foo"] = emit_args self.spout.fail("foo") self.assertEqual(emit_mock.call_count, 0) ack_mock.assert_called_with(self.spout, "foo") if __name__ == "__main__": unittest.main()
#! /usr/bin/python HOME_PATH = './' CACHE_PATH = '/var/cache/obmc/' FLASH_DOWNLOAD_PATH = "/tmp" GPIO_BASE = 320 SYSTEM_NAME = "Palmetto" ## System states ## state can change to next state in 2 ways: ## - a process emits a GotoSystemState signal with state name to goto ## - objects specified in EXIT_STATE_DEPEND have started SYSTEM_STATES = [ 'BASE_APPS', 'BMC_STARTING', 'BMC_READY', 'HOST_POWERING_ON', 'HOST_POWERED_ON', 'HOST_BOOTING', 'HOST_BOOTED', 'HOST_POWERED_OFF', ] EXIT_STATE_DEPEND = { 'BASE_APPS' : { '/org/openbmc/sensors': 0, }, 'BMC_STARTING' : { '/org/openbmc/control/chassis0': 0, '/org/openbmc/control/power0' : 0, '/org/openbmc/control/led/identify' : 0, '/org/openbmc/control/host0' : 0, '/org/openbmc/control/flash/bios' : 0, } } ## method will be called when state is entered ENTER_STATE_CALLBACK = { 'HOST_POWERED_ON' : { 'boot' : { 'bus_name' : 'org.openbmc.control.Host', 'obj_name' : '/org/openbmc/control/host0', 'interface_name' : 'org.openbmc.control.Host', } }, 'BMC_READY' : { 'setOn' : { 'bus_name' : 'org.openbmc.control.led', 'obj_name' : '/org/openbmc/control/led/identify', 'interface_name' : 'org.openbmc.Led', }, 'init' : { 'bus_name' : 'org.openbmc.control.Flash', 'obj_name' : '/org/openbmc/control/flash/bios', 'interface_name' : 'org.openbmc.Flash', }, } } APPS = { 'startup_hacks' : { 'system_state' : 'BASE_APPS', 'start_process' : True, 'monitor_process' : False, 'process_name' : 'startup_hacks.sh', }, 'inventory' : { 'system_state' : 'BMC_STARTING', 'start_process' : True, 'monitor_process' : True, 'process_name' : 'inventory_items.py', 'args' : [ SYSTEM_NAME ] }, 'pcie_present' : { 'system_state' : 'HOST_POWERED_ON', 'start_process' : False, 'monitor_process' : False, 'process_name' : 'pcie_slot_present.exe', }, 'virtual_sensors' : { 'system_state' : 'BMC_STARTING', 'start_process' : True, 'monitor_process' : True, 'process_name' : 'hwmon.py', 'args' : [ SYSTEM_NAME ] }, 'sensor_manager' : { 'system_state' : 'BASE_APPS', 'start_process' : True, 'monitor_process' : True, 'process_name' : 'sensor_manager2.py', 'args' : [ SYSTEM_NAME ] }, 'host_watchdog' : { 'system_state' : 'BMC_STARTING', 'start_process' : True, 'monitor_process' : True, 'process_name' : 'host_watchdog.exe', }, 'power_control' : { 'system_state' : 'BMC_STARTING', 'start_process' : True, 'monitor_process' : True, 'process_name' : 'power_control.exe', 'args' : [ '3000', '10' ] }, 'power_button' : { 'system_state' : 'BMC_STARTING', 'start_process' : False, 'monitor_process' : False, 'process_name' : 'button_power.exe', }, 'led_control' : { 'system_state' : 'BMC_STARTING', 'start_process' : True, 'monitor_process' : True, 'process_name' : 'led_controller.exe', }, 'flash_control' : { 'system_state' : 'BMC_STARTING', 'start_process' : True, 'monitor_process' : True, 'process_name' : 'flash_bios.exe', }, 'bmc_flash_control' : { 'system_state' : 'BMC_STARTING', 'start_process' : True, 'monitor_process' : True, 'process_name' : 'bmc_update.py', }, 'download_manager' : { 'system_state' : 'BMC_STARTING', 'start_process' : True, 'monitor_process' : True, 'process_name' : 'download_manager.py', 'args' : [ SYSTEM_NAME ] }, 'host_control' : { 'system_state' : 'BMC_STARTING', 'start_process' : True, 'monitor_process' : True, 'process_name' : 'control_host.exe', }, 'chassis_control' : { 'system_state' : 'BMC_STARTING', 'start_process' : True, 'monitor_process' : True, 'process_name' : 'chassis_control.py', }, 'bmc_control' : { 'system_state' : 'BMC_STARTING', 'start_process' : True, 'monitor_process' : True, 'process_name' : 'control_bmc.exe', } } CACHED_INTERFACES = { "org.openbmc.InventoryItem" : True, "org.openbmc.control.Chassis" : True, } INVENTORY_ROOT = '/org/openbmc/inventory' FRU_INSTANCES = { '<inventory_root>/system' : { 'fru_type' : 'SYSTEM','is_fru' : True, }, '<inventory_root>/system/chassis' : { 'fru_type' : 'SYSTEM','is_fru' : True, }, '<inventory_root>/system/chassis/motherboard' : { 'fru_type' : 'MAIN_PLANAR','is_fru' : True, }, '<inventory_root>/system/chassis/fan0' : { 'fru_type' : 'FAN','is_fru' : True, }, '<inventory_root>/system/chassis/fan1' : { 'fru_type' : 'FAN','is_fru' : True, }, '<inventory_root>/system/chassis/fan2' : { 'fru_type' : 'FAN','is_fru' : True, }, '<inventory_root>/system/chassis/fan3' : { 'fru_type' : 'FAN','is_fru' : True, }, '<inventory_root>/system/chassis/fan4' : { 'fru_type' : 'FAN','is_fru' : True, }, '<inventory_root>/system/chassis/motherboard/bmc' : { 'fru_type' : 'BMC','is_fru' : False, 'manufacturer' : 'ASPEED' }, '<inventory_root>/system/chassis/motherboard/cpu0' : { 'fru_type' : 'CPU', 'is_fru' : True, }, '<inventory_root>/system/chassis/motherboard/cpu0/core0' : { 'fru_type' : 'CORE', 'is_fru' : False, }, '<inventory_root>/system/chassis/motherboard/cpu0/core1' : { 'fru_type' : 'CORE', 'is_fru' : False, }, '<inventory_root>/system/chassis/motherboard/cpu0/core2' : { 'fru_type' : 'CORE', 'is_fru' : False, }, '<inventory_root>/system/chassis/motherboard/cpu0/core3' : { 'fru_type' : 'CORE', 'is_fru' : False, }, '<inventory_root>/system/chassis/motherboard/cpu0/core4' : { 'fru_type' : 'CORE', 'is_fru' : False, }, '<inventory_root>/system/chassis/motherboard/cpu0/core5' : { 'fru_type' : 'CORE', 'is_fru' : False, }, '<inventory_root>/system/chassis/motherboard/cpu0/core6' : { 'fru_type' : 'CORE', 'is_fru' : False, }, '<inventory_root>/system/chassis/motherboard/cpu0/core7' : { 'fru_type' : 'CORE', 'is_fru' : False, }, '<inventory_root>/system/chassis/motherboard/cpu0/core8' : { 'fru_type' : 'CORE', 'is_fru' : False, }, '<inventory_root>/system/chassis/motherboard/cpu0/core9' : { 'fru_type' : 'CORE', 'is_fru' : False, }, '<inventory_root>/system/chassis/motherboard/cpu0/core10' : { 'fru_type' : 'CORE', 'is_fru' : False, }, '<inventory_root>/system/chassis/motherboard/cpu0/core11' : { 'fru_type' : 'CORE', 'is_fru' : False, }, '<inventory_root>/system/chassis/motherboard/membuf0' : { 'fru_type' : 'MEMORY_BUFFER', 'is_fru' : False, }, '<inventory_root>/system/chassis/motherboard/dimm0' : { 'fru_type' : 'DIMM', 'is_fru' : True,}, '<inventory_root>/system/chassis/motherboard/dimm1' : { 'fru_type' : 'DIMM', 'is_fru' : True,}, '<inventory_root>/system/chassis/motherboard/dimm2' : { 'fru_type' : 'DIMM', 'is_fru' : True,}, '<inventory_root>/system/chassis/motherboard/dimm3' : { 'fru_type' : 'DIMM', 'is_fru' : True,}, '<inventory_root>/system/chassis/io_board/pcie_slot0' : { 'fru_type' : 'PCIE_CARD', 'is_fru' : True,}, '<inventory_root>/system/chassis/io_board/pcie_slot1' : { 'fru_type' : 'PCIE_CARD', 'is_fru' : True,}, '<inventory_root>/system/systemevent' : { 'fru_type' : 'SYSTEM_EVENT', 'is_fru' : False, }, '<inventory_root>/system/chassis/motherboard/refclock' : { 'fru_type' : 'MAIN_PLANAR', 'is_fru' : False, }, '<inventory_root>/system/chassis/motherboard/pcieclock': { 'fru_type' : 'MAIN_PLANAR', 'is_fru' : False, }, '<inventory_root>/system/chassis/motherboard/todclock' : { 'fru_type' : 'MAIN_PLANAR', 'is_fru' : False, }, '<inventory_root>/system/chassis/motherboard/apss' : { 'fru_type' : 'MAIN_PLANAR', 'is_fru' : False, }, } ID_LOOKUP = { 'FRU' : { 0x0d : '<inventory_root>/system/chassis', 0x34 : '<inventory_root>/system/chassis/motherboard', 0x01 : '<inventory_root>/system/chassis/motherboard/cpu0', 0x02 : '<inventory_root>/system/chassis/motherboard/membuf0', 0x03 : '<inventory_root>/system/chassis/motherboard/dimm0', 0x04 : '<inventory_root>/system/chassis/motherboard/dimm1', 0x05 : '<inventory_root>/system/chassis/motherboard/dimm2', 0x06 : '<inventory_root>/system/chassis/motherboard/dimm3', 0x35 : '<inventory_root>/system', }, 'FRU_STR' : { 'PRODUCT_15' : '<inventory_root>/system', 'CHASSIS_2' : '<inventory_root>/system/chassis', 'BOARD_1' : '<inventory_root>/system/chassis/motherboard/cpu0', 'BOARD_2' : '<inventory_root>/system/chassis/motherboard/membuf0', 'BOARD_14' : '<inventory_root>/system/chassis/motherboard', 'PRODUCT_3' : '<inventory_root>/system/chassis/motherboard/dimm0', 'PRODUCT_4' : '<inventory_root>/system/chassis/motherboard/dimm1', 'PRODUCT_5' : '<inventory_root>/system/chassis/motherboard/dimm2', 'PRODUCT_6' : '<inventory_root>/system/chassis/motherboard/dimm3', }, 'SENSOR' : { 0x34 : '<inventory_root>/system/chassis/motherboard', 0x35 : '<inventory_root>/system/systemevent', 0x37 : '<inventory_root>/system/chassis/motherboard/refclock', 0x38 : '<inventory_root>/system/chassis/motherboard/pcieclock', 0x39 : '<inventory_root>/system/chassis/motherboard/todclock', 0x3A : '<inventory_root>/system/chassis/motherboard/apss', 0x2f : '<inventory_root>/system/chassis/motherboard/cpu0', 0x22 : '<inventory_root>/system/chassis/motherboard/cpu0/core0', 0x23 : '<inventory_root>/system/chassis/motherboard/cpu0/core1', 0x24 : '<inventory_root>/system/chassis/motherboard/cpu0/core2', 0x25 : '<inventory_root>/system/chassis/motherboard/cpu0/core3', 0x26 : '<inventory_root>/system/chassis/motherboard/cpu0/core4', 0x27 : '<inventory_root>/system/chassis/motherboard/cpu0/core5', 0x28 : '<inventory_root>/system/chassis/motherboard/cpu0/core6', 0x29 : '<inventory_root>/system/chassis/motherboard/cpu0/core7', 0x2a : '<inventory_root>/system/chassis/motherboard/cpu0/core8', 0x2b : '<inventory_root>/system/chassis/motherboard/cpu0/core9', 0x2c : '<inventory_root>/system/chassis/motherboard/cpu0/core10', 0x2d : '<inventory_root>/system/chassis/motherboard/cpu0/core11', 0x2e : '<inventory_root>/system/chassis/motherboard/membuf0', 0x1e : '<inventory_root>/system/chassis/motherboard/dimm0', 0x1f : '<inventory_root>/system/chassis/motherboard/dimm1', 0x20 : '<inventory_root>/system/chassis/motherboard/dimm2', 0x21 : '<inventory_root>/system/chassis/motherboard/dimm3', 0x09 : '/org/openbmc/sensors/host/BootCount', 0x05 : '/org/openbmc/sensors/host/BootProgress', 0x08 : '/org/openbmc/sensors/host/cpu0/OccStatus', 0x32 : '/org/openbmc/sensors/host/OperatingSystemStatus', 0x33 : '/org/openbmc/sensors/host/PowerCap', }, 'GPIO_PRESENT' : { 'SLOT0_PRESENT' : '<inventory_root>/system/chassis/io_board/pcie_slot0', 'SLOT1_PRESENT' : '<inventory_root>/system/chassis/io_board/pcie_slot1', } } GPIO_CONFIG = {} GPIO_CONFIG['FSI_CLK'] = { 'gpio_pin': 'A4', 'direction': 'out' } GPIO_CONFIG['FSI_DATA'] = { 'gpio_pin': 'A5', 'direction': 'out' } GPIO_CONFIG['FSI_ENABLE'] = { 'gpio_pin': 'D0', 'direction': 'out' } GPIO_CONFIG['POWER_PIN'] = { 'gpio_pin': 'E1', 'direction': 'out' } GPIO_CONFIG['CRONUS_SEL'] = { 'gpio_pin': 'A6', 'direction': 'out' } GPIO_CONFIG['PGOOD'] = { 'gpio_pin': 'C7', 'direction': 'in' } GPIO_CONFIG['BMC_THROTTLE'] = { 'gpio_pin': 'J3', 'direction': 'out' } GPIO_CONFIG['IDBTN'] = { 'gpio_pin': 'Q7', 'direction': 'out' } GPIO_CONFIG['POWER_BUTTON'] = { 'gpio_pin': 'E0', 'direction': 'both' } GPIO_CONFIG['PCIE_RESET'] = { 'gpio_pin': 'B5', 'direction': 'out' } GPIO_CONFIG['USB_RESET'] = { 'gpio_pin': 'B6', 'direction': 'out' } GPIO_CONFIG['SLOT0_RISER_PRESENT'] = { 'gpio_pin': 'N0', 'direction': 'in' } GPIO_CONFIG['SLOT1_RISER_PRESENT'] = { 'gpio_pin': 'N1', 'direction': 'in' } GPIO_CONFIG['SLOT2_RISER_PRESENT'] = { 'gpio_pin': 'N2', 'direction': 'in' } GPIO_CONFIG['SLOT0_PRESENT'] = { 'gpio_pin': 'N3', 'direction': 'in' } GPIO_CONFIG['SLOT1_PRESENT'] = { 'gpio_pin': 'N4', 'direction': 'in' } GPIO_CONFIG['SLOT2_PRESENT'] = { 'gpio_pin': 'N5', 'direction': 'in' } GPIO_CONFIG['MEZZ0_PRESENT'] = { 'gpio_pin': 'O0', 'direction': 'in' } GPIO_CONFIG['MEZZ1_PRESENT'] = { 'gpio_pin': 'O1', 'direction': 'in' } def convertGpio(name): name = name.upper() c = name[0:1] offset = int(name[1:]) a = ord(c)-65 base = a*8+GPIO_BASE return base+offset HWMON_CONFIG = { '2-004c' : { 'names' : { 'temp1_input' : { 'object_path' : 'temperature/ambient','poll_interval' : 5000,'scale' : 1000,'units' : 'C' }, } }, '3-0050' : { 'names' : { 'caps_curr_powercap' : { 'object_path' : 'powercap/curr_cap','poll_interval' : 10000,'scale' : 1,'units' : 'W' }, 'caps_curr_powerreading' : { 'object_path' : 'powercap/system_power','poll_interval' : 10000,'scale' : 1,'units' : 'W' }, 'caps_max_powercap' : { 'object_path' : 'powercap/max_cap','poll_interval' : 10000,'scale' : 1,'units' : 'W' }, 'caps_min_powercap' : { 'object_path' : 'powercap/min_cap','poll_interval' : 10000,'scale' : 1,'units' : 'W' }, 'caps_norm_powercap' : { 'object_path' : 'powercap/n_cap','poll_interval' : 10000,'scale' : 1,'units' : 'W' }, 'caps_user_powerlimit' : { 'object_path' : 'powercap/user_cap','poll_interval' : 10000,'scale' : 1,'units' : 'W' }, } } } # Miscellaneous non-poll sensor with system specific properties. # The sensor id is the same as those defined in ID_LOOKUP['SENSOR']. MISC_SENSORS = { 0x09 : { 'class' : 'BootCountSensor' }, 0x05 : { 'class' : 'BootProgressSensor' }, 0x08 : { 'class' : 'OccStatusSensor', 'os_path' : '/sys/class/i2c-adapter/i2c-3/3-0050/online' }, 0x32 : { 'class' : 'OperatingSystemStatusSensor' }, 0x33 : { 'class' : 'PowerCap', 'os_path' : '/sys/class/hwmon/hwmon1/user_powercap' }, }
# Based on the python URDF implementation by Antonio El Khoury # Available at https://github.com/laas/robot_model_py import string from naoqi_tools.gazeboUrdf import * from xml.dom.minidom import Document from xml.dom import minidom import sys from numpy import array,pi import re, copy HUBO_JOINT_SUFFIX_MASK=r'([HKASEWF][RPY12345])' class Collision(object): """Collision node stores collision geometry for a link.""" def __init__(self, geometry=None, origin=None): self.geometry = geometry self.origin = origin @staticmethod def parse(node, verbose=True): c = Collision() for child in children(node): if child.localName == 'geometry': c.geometry = Geometry.parse(child, verbose) elif child.localName == 'origin': c.origin = Pose.parse(child) else: print("Unknown collision element '%s'"%child.localName) return c def to_xml(self, doc): xml = doc.createElement("collision") add(doc, xml, self.geometry) add(doc, xml, self.origin) return xml def to_openrave_xml(self, doc): xml = self.geometry.to_openrave_xml(doc) add_openrave(doc,xml, self.origin) return xml def __str__(self): s = "Origin:\n{0}\n".format(reindent(str(self.origin), 1)) s += "Geometry:\n{0}\n".format(reindent(str(self.geometry), 1)) return s class Color(object): """Color node stores color definition for a material or a visual.""" def __init__(self, r=0.0, g=0.0, b=0.0, a=0.0): self.rgba=(r,g,b,a) @staticmethod def parse(node): rgba = node.getAttribute("rgba").split() (r,g,b,a) = [ float(x) for x in rgba ] return Color(r,g,b,a) def to_xml(self, doc): xml = doc.createElement("color") set_attribute(xml, "rgba", self.rgba) return xml def to_openrave_xml(self,doc): return None def __str__(self): return "r: {0}, g: {1}, b: {2}, a: {3},".format( self.rgba[0], self.rgba[1], self.rgba[2], self.rgba[3]) class Dynamics(object): """Dynamics node stores coefficients that define the dynamics of a joint""" def __init__(self, damping=None, friction=None): self.damping = damping self.friction = friction @staticmethod def parse(node): d = Dynamics() if node.hasAttribute('damping'): d.damping = node.getAttribute('damping') if node.hasAttribute('friction'): d.friction = node.getAttribute('friction') return d def to_xml(self, doc): xml = doc.createElement('dynamics') set_attribute(xml, 'damping', self.damping) set_attribute(xml, 'friction', self.friction) return xml def to_openrave_xml(self,doc): return None def __str__(self): return "Damping: {0}\nFriction: {1}\n".format(self.damping, self.friction) class Geometry(object): """Geometry abstract class define the type of geomerical shape for a visual or collision element""" def __init__(self): None @staticmethod def parse(node, verbose=True): shape = children(node)[0] if shape.localName=='box': return Box.parse(shape) elif shape.localName=='cylinder': return Cylinder.parse(shape) elif shape.localName=='sphere': return Sphere.parse(shape) elif shape.localName=='mesh': return Mesh.parse(shape) else: if verbose: print("Unknown shape %s"%shape.localName) def __str__(self): return "Geometry abstract class" class Box(Geometry): """Box node stores the dimensions for a rectangular geometry element""" def __init__(self, dims=None): if dims is None: self.dims = None else: self.dims = (dims[0], dims[1], dims[2]) @staticmethod def parse(node): dims = node.getAttribute('size').split() return Box([float(a) for a in dims]) def to_xml(self, doc): xml = doc.createElement("box") set_attribute(xml, "size", self.dims) geom = doc.createElement('geometry') geom.appendChild(xml) return geom def to_openrave_xml(self, doc): xml = short(doc, "geometry","type","box") xml.appendChild(create_element(xml, "extents", self.dims)) return xml def __str__(self): return "Dimension: {0}".format(self.dims) class Cylinder(Geometry): """Cylinder node stores the dimensions for a z-rotation invariant geometry element""" def __init__(self, radius=0.0, length=0.0): self.radius = radius self.length = length @staticmethod def parse(node): r = node.getAttribute('radius') l = node.getAttribute('length') return Cylinder(float(r), float(l)) def to_xml(self, doc): xml = doc.createElement("cylinder") set_attribute(xml, "radius", self.radius) set_attribute(xml, "length", self.length) geom = doc.createElement('geometry') geom.appendChild(xml) return geom def to_openrave_xml(self, doc): xml = short(doc, "geometry","type","cylinder") xml.appendChild(create_element(doc, "height", self.length)) xml.appendChild(create_element(doc, "radius", self.radius)) return xml def __str__(self): return "Radius: {0}\nLength: {1}".format(self.radius, self.length) class Sphere(Geometry): """Sphere node stores the dimensions for a rotation invariant geometry element""" def __init__(self, radius=0.0): self.radius = radius @staticmethod def parse(node): r = node.getAttribute('radius') return Sphere(float(r)) def to_xml(self, doc): xml = doc.createElement("sphere") set_attribute(xml, "radius", self.radius) geom = doc.createElement('geometry') geom.appendChild(xml) return geom def to_openrave_xml(self, doc): xml = short(doc, "geometry","type","sphere") xml.create_child(xml, "radius", self.radius) return xml def __str__(self): return "Radius: {0}".format(self.radius) class Mesh(Geometry): """Mesh node stores the path of the mesh file to be displayed""" def __init__(self, filename=None, scale=1): self.filename = filename self.scale = scale @staticmethod def parse(node): fn = node.getAttribute('filename') s = node.getAttribute('scale') if s == "": s = 1 else: xyz = node.getAttribute('scale').split() s = map(float, xyz) return Mesh(fn, s) def to_xml(self, doc): xml = doc.createElement("mesh") set_attribute(xml, "filename", self.filename) if self.scale != 1: set_attribute(xml, "scale", self.scale) geom = doc.createElement('geometry') geom.appendChild(xml) return geom def to_openrave_xml(self, doc): xml = short(doc, "geometry","type","trimesh") f='../meshes/'+self.filename.split('/')[-1] fhull=re.sub(r"Body","convhull",f) #xml.appendChild(create_element(doc, "render", [f, self.scale])) xml.appendChild(create_element(doc, "data", [fhull, self.scale])) #set_attribute(xml, "render","true") return xml def __str__(self): return "Filename: {0}\nScale: {1}".format(self.filename, self.scale) class Inertial(object): """Inertial node stores mecanical information of a Link : mass, inertia matrix and origin""" def __init__(self, ixx=0.0, ixy=0.0, ixz=0.0, iyy=0.0, iyz=0.0, izz=0.0, mass=0.0, origin=None): self.matrix = {} self.matrix['ixx'] = ixx self.matrix['ixy'] = ixy self.matrix['ixz'] = ixz self.matrix['iyy'] = iyy self.matrix['iyz'] = iyz self.matrix['izz'] = izz self.mass = mass self.origin = origin @staticmethod def parse(node): inert = Inertial() for child in children(node): if child.localName=='inertia': for v in ['ixx', 'ixy', 'ixz', 'iyy', 'iyz', 'izz']: inert.matrix[v] = float(child.getAttribute(v)) elif child.localName=='mass': inert.mass = float(child.getAttribute('value')) elif child.localName == 'origin': inert.origin = Pose.parse(child) return inert def to_xml(self, doc): xml = doc.createElement("inertial") xml.appendChild(short(doc, "mass", "value", self.mass)) inertia = doc.createElement("inertia") for (n,v) in self.matrix.items(): set_attribute(inertia, n, v) xml.appendChild(inertia) add(doc, xml, self.origin) return xml def to_openrave_xml(self, doc): xml = doc.createElement("mass") set_attribute(xml,"type","custom") xml.appendChild(create_element(doc, "total", self.mass)) text='{ixx} {ixy} {ixz}\n{ixy} {iyy} {iyz}\n{ixz} {iyz} {izz}'.format(**self.matrix) xml.appendChild(create_element(doc,"inertia",text)) add_openrave(doc, xml, self.origin) xml.getElementsByTagName('translation')[0].tagName="com" return xml def __str__(self): s = "Origin:\n{0}\n".format(reindent(str(self.origin), 1)) s += "Mass: {0}\n".format(self.mass) s += "ixx: {0}\n".format(self.matrix['ixx']) s += "ixy: {0}\n".format(self.matrix['ixy']) s += "ixz: {0}\n".format(self.matrix['ixz']) s += "iyy: {0}\n".format(self.matrix['iyy']) s += "iyz: {0}\n".format(self.matrix['iyz']) s += "izz: {0}\n".format(self.matrix['izz']) return s class Joint(object): """Joint node stores articulation information coupling two links""" UNKNOWN = 'unknown' REVOLUTE = 'revolute' CONTINUOUS = 'continuous' PRISMATIC = 'prismatic' FLOATING = 'floating' PLANAR = 'planar' FIXED = 'fixed' def __init__(self, name, parent, child, joint_type, axis=None, origin=None, limits=None, dynamics=None, safety=None, calibration=None, mimic=None): self.name = name self.parent = parent self.child = child self.joint_type = joint_type self.axis = axis self.origin = origin self.limits = limits self.dynamics = dynamics self.safety = safety self.calibration = calibration self.mimic = mimic @staticmethod def parse(node, verbose=True): joint = Joint(node.getAttribute('name'), None, None, node.getAttribute('type')) for child in children(node): if child.localName == 'parent': joint.parent = child.getAttribute('link') elif child.localName == 'child': joint.child = child.getAttribute('link') elif child.localName == 'axis': joint.axis = array([float(x) for x in child.getAttribute('xyz').split(' ')]) elif child.localName == 'origin': joint.origin = Pose.parse(child) elif child.localName == 'limit': joint.limits = JointLimit.parse(child) elif child.localName == 'dynamics': joint.dynamics = Dynamics.parse(child) elif child.localName == 'safety_controller': joint.safety = SafetyController.parse(child) elif child.localName == 'calibration': joint.calibration = JointCalibration.parse(child) elif child.localName == 'mimic': joint.mimic = JointMimic.parse(child) else: if verbose: print("Unknown joint element '%s'"%child.localName) return joint def to_xml(self, doc): xml = doc.createElement("joint") set_attribute(xml, "name", self.name) set_attribute(xml, "type", self.joint_type) xml.appendChild( short(doc, "parent", "link", self.parent) ) xml.appendChild( short(doc, "child" , "link", self.child ) ) add(doc, xml, self.origin) if self.axis is not None: xml.appendChild( short(doc, "axis", "xyz", to_string(self.axis) ) ) add(doc, xml, self.limits) add(doc, xml, self.dynamics) add(doc, xml, self.safety) add(doc, xml, self.calibration) add(doc, xml, self.mimic) return xml def to_openrave_xml(self, doc): xml = doc.createElement("joint") set_attribute(xml, "name", self.name) s="" if self.joint_type == Joint.UNKNOWN: s = "unknown" elif self.joint_type == Joint.REVOLUTE: s = "hinge" elif self.joint_type == Joint.CONTINUOUS: s = "hinge" set_attribute(xml, "circular", "true") elif self.joint_type == Joint.PRISMATIC: s = "slider" elif self.joint_type == Joint.FIXED: s = "hinge" set_attribute(xml, "enable", "false") xml.appendChild( create_element(doc, "limits", "0 0") ) set_attribute(xml, "type", s) if self.mimic is not None: multiplier=self.mimic.multiplier if self.mimic.multiplier is not None else 1.0 offset=self.mimic.offset if self.mimic.offset is not None else 0.0 #1) Follow openrave mimic joint format, disable joint: set_attribute(xml,"enable","false") #2) Create the position equation set_attribute(xml,"mimic_pos","{0} * {1} + {2}".format(self.mimic.joint_name,multiplier,offset)) set_attribute(xml,"mimic_vel","|{0} {1}".format(self.mimic.joint_name,multiplier)) xml.appendChild( create_element(doc, "body", self.parent) ) xml.appendChild( create_element(doc, "body" , self.child ) ) xml.appendChild( create_element(doc, "offsetfrom" , self.parent) ) add_openrave(doc, xml, self.origin) xml.getElementsByTagName('translation')[0].tagName="anchor" if self.axis is not None: xml.appendChild( create_element(doc, "axis", self.axis) ) add_openrave(doc, xml, self.limits) return xml def __str__(self): s = "Name: {0}\n".format(self.name) s += "Child link name: {0}\n".format(self.child) s += "Parent link name: {0}\n".format(self.parent) if self.joint_type == Joint.UNKNOWN: s += "Type: unknown\n" elif self.joint_type == Joint.REVOLUTE: s += "Type: revolute\n" elif self.joint_type == Joint.CONTINUOUS: s += "Type: continuous\n" elif self.joint_type == Joint.PRISMATIC: s += "Type: prismatic\n" elif self.joint_type == Joint.FLOATING: s += "Type: floating\n" elif self.joint_type == Joint.PLANAR: s += "Type: planar\n" elif self.joint_type == Joint.FIXED: s += "Type: fixed\n" else: print("unknown joint type") s += "Axis: {0}\n".format(self.axis) s += "Origin:\n{0}\n".format(reindent(str(self.origin), 1)) s += "Limits:\n" s += reindent(str(self.limits), 1) + "\n" s += "Dynamics:\n" s += reindent(str(self.dynamics), 1) + "\n" s += "Safety:\n" s += reindent(str(self.safety), 1) + "\n" s += "Calibration:\n" s += reindent(str(self.calibration), 1) + "\n" s += "Mimic:\n" s += reindent(str(self.mimic), 1) + "\n" return s #FIXME: we are missing the reference position here. class JointCalibration(object): def __init__(self, rising=None, falling=None): self.rising = rising self.falling = falling @staticmethod def parse(node): jc = JointCalibration() if node.hasAttribute('rising'): jc.rising = float( node.getAttribute('rising') ) if node.hasAttribute('falling'): jc.falling = float( node.getAttribute('falling') ) return jc def to_xml(self, doc): xml = doc.createElement('calibration') set_attribute(xml, 'rising', self.rising) set_attribute(xml, 'falling', self.falling) return xml def to_openrave_xml(self,doc): #No implementation return None def __str__(self): s = "Raising: {0}\n".format(self.rising) s += "Falling: {0}\n".format(self.falling) return s class JointLimit(object): """JointLimit node stores mechanical limits of a given joint""" def __init__(self, effort, velocity, lower=None, upper=None): self.effort = effort self.velocity = velocity self.lower = lower self.upper = upper @staticmethod def parse(node): jl = JointLimit( float( node.getAttribute('effort') ) , float( node.getAttribute('velocity'))) if node.hasAttribute('lower'): jl.lower = float( node.getAttribute('lower') ) if node.hasAttribute('upper'): jl.upper = float( node.getAttribute('upper') ) return jl def get_from_table(self,node): jl = JointLimit( float( node.getAttribute('effort') ) , float( node.getAttribute('velocity'))) if node.hasAttribute('lower'): jl.lower = float( node.getAttribute('lower') ) if node.hasAttribute('upper'): jl.upper = float( node.getAttribute('upper') ) return jl def to_xml(self, doc): xml = doc.createElement('limit') set_attribute(xml, 'effort', self.effort) set_attribute(xml, 'velocity', self.velocity) set_attribute(xml, 'lower', self.lower) set_attribute(xml, 'upper', self.upper) return xml def to_openrave_xml(self,doc): limit = create_element(doc,'limitsdeg',[round(self.lower*180/pi,1),round(self.upper*180/pi,1)]) maxvel = create_element(doc,'maxvel',self.velocity) maxtrq = create_element(doc,'maxtorque',self.effort) return [limit,maxvel,maxtrq] def __str__(self): s = "Effort: {0}\n".format(self.effort) s += "Lower: {0}\n".format(self.lower) s += "Upper: {0}\n".format(self.upper) s += "Velocity: {0}\n".format(self.velocity) return s class JointMimic(object): """JointMimic node stores information coupling an actuated joint to a not controllable joint""" def __init__(self, joint_name, multiplier=None, offset=None): self.joint_name = joint_name self.multiplier = multiplier self.offset = offset @staticmethod def parse(node): mimic = JointMimic( node.getAttribute('joint') ) if node.hasAttribute('multiplier'): mimic.multiplier = float( node.getAttribute('multiplier') ) if node.hasAttribute('offset'): mimic.offset = float( node.getAttribute('offset') ) return mimic def to_xml(self, doc): xml = doc.createElement('mimic') set_attribute(xml, 'joint', self.joint_name) set_attribute(xml, 'multiplier', self.multiplier) set_attribute(xml, 'offset', self.offset) return xml def __str__(self): s = "Joint: {0}\n".format(self.joint_name) s += "Multiplier: {0}\n".format(self.multiplier) s += "Offset: {0}\n".format(self.offset) return s class Link(object): """Link node stores information defining the mechanics and the visualization of a link""" def __init__(self, name, visual=None, inertial=None, collision=None, xacro=None): self.name = name self.visual = visual self.inertial = inertial self.collision = collision self.xacro = xacro @staticmethod def parse(node, verbose=True): link = Link(node.getAttribute('name')) for child in children(node): if child.localName == 'visual': link.visual = Visual.parse(child, verbose) elif child.localName == 'collision': link.collision = Collision.parse(child, verbose) elif child.localName == 'inertial': link.inertial = Inertial.parse(child) elif child.localName.startswith('xacro'): link.xacro = xacro else: if verbose: print("Unknown link element '%s'"%child.localName) return link def to_xml(self, doc): xml = doc.createElement("link") xml.setAttribute("name", self.name) add( doc, xml, self.visual) add( doc, xml, self.collision) add( doc, xml, self.inertial) if self.xacro is not None: text = doc.createElement(self.xacro) xml.appendChild(text) return xml def to_openrave_xml(self, doc): xml = doc.createElement("body") xml.setAttribute("name", self.name) add_openrave( doc, xml, self.collision) add_openrave( doc, xml, self.inertial) return xml def __str__(self): s = "Name: {0}\n".format(self.name) s += "Inertial:\n" s += reindent(str(self.inertial), 1) + "\n" s += "Visual:\n" s += reindent(str(self.visual), 1) + "\n" s += "Collision:\n" s += reindent(str(self.collision), 1) + "\n" s += "Xacro:\n" s += reindent(str(self.xacro),1) + "\n" return s class Material(object): """Material node stores visual information of a mechanical material : color, texture""" def __init__(self, name=None, color=None, texture=None): self.name = name self.color = color self.texture = texture @staticmethod def parse(node, verbose=True): material = Material() if node.hasAttribute('name'): material.name = node.getAttribute('name') for child in children(node): if child.localName == 'color': material.color = Color.parse(child) elif child.localName == 'texture': material.texture = child.getAttribute('filename') else: if verbose: print("Unknown material element '%s'"%child.localName) return material def to_xml(self, doc): xml = doc.createElement("material") set_attribute(xml, "name", self.name) add( doc, xml, self.color ) if self.texture is not None: text = doc.createElement("texture") text.setAttribute('filename', self.texture) xml.appendChild(text) return xml def __str__(self): s = "Name: {0}\n".format(self.name) s += "Color: {0}\n".format(self.color) s += "Texture:\n" s += reindent(str(self.texture), 1) return s class Pose(object): """Pose node stores a cartesian 6-D pose : xyz : array rpy : array """ def __init__(self, position=None, rotation=None): self.position = array(position) self.rotation = array(rotation) @staticmethod def parse(node): pose = Pose() if node.hasAttribute("xyz"): xyz = node.getAttribute('xyz').split() pose.position = array(map(float, xyz)) if node.hasAttribute("rpy"): rpy = node.getAttribute('rpy').split() pose.rotation = array(map(float, rpy)) return pose def to_xml(self, doc): xml = doc.createElement("origin") set_attribute(xml, 'xyz', self.position) set_attribute(xml, 'rpy', self.rotation) return xml def to_openrave_xml(self, doc): xml = doc.createElement("translation") set_content(doc,xml,self.position) elements=[xml] if not self.rotation[0] == 0: rotr = doc.createElement("rotationaxis") set_content(doc,rotr,[1,0,0,self.rotation[0]*180.0/pi]) elements.append(rotr) if not self.rotation[1] == 0: rotp = doc.createElement("rotationaxis") set_content(doc,rotp,[0,1,0,self.rotation[1]*180.0/pi]) elements.append(rotp) if not self.rotation[2] == 0: roty = doc.createElement("rotationaxis") set_content(doc,roty,[0,0,1,self.rotation[2]*180.0/pi]) elements.append(roty) return elements def __str__(self): return "Position: {0}\nRotation: {1}".format(self.position, self.rotation) class SafetyController(object): def __init__(self, velocity, position=None, lower=None, upper=None): self.velocity = velocity self.position = position self.lower = lower self.upper = upper @staticmethod def parse(node): sc = SafetyController( float(node.getAttribute('k_velocity')) ) if node.hasAttribute('soft_lower_limit'): sc.lower = float( node.getAttribute('soft_lower_limit') ) if node.hasAttribute('soft_upper_limit'): sc.upper = float( node.getAttribute('soft_upper_limit') ) if node.hasAttribute('k_position'): sc.position = float( node.getAttribute('k_position') ) return sc def to_xml(self, doc): xml = doc.createElement('safety_controller') set_attribute(xml, 'k_velocity', self.velocity) set_attribute(xml, 'k_position', self.position) set_attribute(xml, 'soft_upper_limit', self.upper) set_attribute(xml, 'soft_lower_limit', self.lower) return xml def __str__(self): s = "Safe lower limit: {0}\n".format(self.lower) s += "Safe upper limit: {0}\n".format(self.upper) s += "K position: {0}\n".format(self.position) s += "K velocity: {0}\n".format(self.velocity) return s class Visual(object): """Visual node stores information defining shape and material of the link to be displayed""" def __init__(self, geometry=None, material=None, origin=None): self.geometry = geometry self.material = material self.origin = origin @staticmethod def parse(node, verbose=True): v = Visual() for child in children(node): if child.localName == 'geometry': v.geometry = Geometry.parse(child, verbose) elif child.localName == 'origin': v.origin = Pose.parse(child) elif child.localName == 'material': v.material = Material.parse(child, verbose) else: if verbose: print("Unknown visual element '%s'"%child.localName) return v def to_xml(self, doc): xml = doc.createElement("visual") add( doc, xml, self.geometry ) add( doc, xml, self.origin ) add( doc, xml, self.material ) return xml def __str__(self): s = "Origin:\n{0}\n".format(reindent(str(self.origin), 1)) s += "Geometry:\n" s += reindent(str(self.geometry), 1) + "\n" s += "Material:\n" s += reindent(str(self.material), 1) + "\n" return s class Actuator(object): """Actuator node stores information about how a motor controls a joint : used in transmission tags""" def __init__(self,name=None,hardwareInterface=None,mechanicalReduction=1): self.name = name self.hardwareInterface = hardwareInterface self.mechanicalReduction = mechanicalReduction @staticmethod def parse(node, verbose=True): actuator = Actuator() if node.hasAttribute('name'): actuator.name = node.getAttribute('name') for child in children(node): if child.localName == 'hardwareInterface': actuator.hardwareInterface = str(child.childNodes[0].nodeValue) if child.localName == 'mechanicalReduction': actuator.mechanicalReduction = str(child.childNodes[0].nodeValue) else: print'Unknown actuator element ' + str(child.localName) return actuator def to_xml(self, doc): xml = doc.createElement('actuator') set_attribute(xml, 'name', self.name) xml.appendChild(create_element(doc, 'hardwareInterface', self.hardwareInterface)) xml.appendChild(create_element(doc,"mechanicalReduction",str(self.mechanicalReduction))) return xml def __str__(self): s = "Name: {0}\n".format(self.name) s += "HardwareInterface : {0}\n".format(self.hardwareInterface) s += "Mechanical Reduction: {0}\n".format(self.mechanicalReduction) return s class Transmission(object): """Transmission node stores information linking a joint to an actuator""" def __init__(self,name=None,type=None,joint=None,actuator=None): self.name = name self.joint = joint self.actuator = actuator self.type = type @staticmethod def parse(node, verbose=True): trans = Transmission() if node.hasAttribute('name'): trans.name = node.getAttribute('name') for child in children(node): if child.localName == 'joint': trans.joint = child.getAttribute('name') if child.localName == 'actuator': trans.actuator = Actuator.parse(child,verbose) if child.localName == 'type': trans.type = str(child.childNodes[0].nodeValue)#str(child.getAttribute('type')) return trans def to_xml(self, doc): xml = doc.createElement('transmission') set_attribute(xml, 'name', self.name) xml.appendChild( short(doc, "joint", "name", self.joint) ) xml.appendChild(create_element(doc, 'type', self.type)) add(doc, xml, self.actuator) return xml def __str__(self): s = "Name: {0}\n".format(self.name) s += "Type: {0}\n".format(self.type) s += "Joint: {0}\n".format(self.joint) s += "Actuator:\n" s += reindent(str(self.actuator), 1) + "\n" return s ######################################## ######### URDF Global Class ############ ######################################## class URDF(object): """URDF node stores every information about a robot's model""" ZERO_THRESHOLD=0.000000001 def __init__(self, name=""): self.name = name self.elements = [] self.gazebos = {} self.links = {} self.joints = {} self.materials = {} self.parent_map = {} self.child_map = {} @staticmethod def parse_xml_string(xml_string, verbose=True): """Parse a string to create a URDF robot structure.""" urdf = URDF() base = minidom.parseString(xml_string) robot = children(base)[0] urdf.name = robot.getAttribute('name') for node in children(robot): if node.nodeType is node.TEXT_NODE: continue if node.localName == 'joint': urdf.add_joint( Joint.parse(node, verbose) ) elif node.localName == 'link': urdf.add_link( Link.parse(node, verbose) ) elif node.localName == 'material': urdf.add_material(Material.parse(node,verbose)) elif node.localName == 'gazebo': urdf.add_gazebo(Gazebo.parse(node,verbose)) elif node.localName == 'transmission': urdf.elements.append( Transmission.parse(node,verbose) ) else: if verbose: print("Unknown robot element '%s'"%node.localName) return urdf @staticmethod def load_xml_file(filename, verbose=True): """Parse a file to create a URDF robot structure.""" f = open(filename, 'r') return URDF.parse_xml_string(f.read(), verbose) @staticmethod def load_from_parameter_server(key = 'robot_description', verbose=True): """ Retrieve the robot model on the parameter server and parse it to create a URDF robot structure. Warning: this requires roscore to be running. """ import rospy return URDF.parse_xml_string(rospy.get_param(key), verbose) def add_link(self, link): self.elements.append(link) self.links[link.name] = link def add_joint(self, joint): self.elements.append(joint) self.joints[joint.name] = joint self.parent_map[ joint.child ] = (joint.name, joint.parent) if joint.parent in self.child_map: self.child_map[joint.parent].append( (joint.name, joint.child) ) else: self.child_map[joint.parent] = [ (joint.name, joint.child) ] def add_material(self, material): """ Add a material to the URDF.elements list """ self.elements.append(material) self.materials[material.name] = material def add_gazebo(self, gazebo): """ Add gazebo data to the URDF.elements list """ self.elements.append(gazebo) self.gazebos[gazebo.reference] = gazebo def get_chain(self, root, tip, joints=True, links=True, fixed=True): """Based on given link names root and tip, return either a joint or link chain as a list of names.""" chain = [] if links: chain.append(tip) link = tip while link != root: (joint, parent) = self.parent_map[link] if joints: if fixed or self.joints[joint].joint_type != 'fixed': chain.append(joint) if links: chain.append(parent) link = parent chain.reverse() return chain def get_root(self): root = None for link in self.links: if link not in self.parent_map: assert root is None, "Multiple roots detected, invalid URDF." root = link assert root is not None, "No roots detected, invalid URDF." return root def to_xml(self,orderbytree=False,orderbytype=False): doc = Document() root = doc.createElement("robot") doc.appendChild(root) root.setAttribute("name", self.name) baselink=self.parent_map if orderbytree: #Walk child map sequentially and export pass if orderbytype: pass for element in self.elements: root.appendChild(element.to_xml(doc)) return doc.toprettyxml() def write_xml(self,outfile=None): if outfile is None: outfile=self.name+'.urdf' self.write_reformatted(self.to_xml(),outfile) def make_openrave_kinbody(self,doc): kinbody = doc.createElement("kinbody") doc.appendChild(kinbody) kinbody.setAttribute("name", self.name) for element in self.elements: kinbody.appendChild(element.to_openrave_xml(doc)) #Post-processing to add offsetfrom statements for j in self.joints.keys(): for l in kinbody.getElementsByTagName('body'): if l.getAttribute('name')== self.joints[j].child: #Add offsetfrom declarration and joint anchor as transform l.appendChild( create_element(doc, "offsetfrom" , self.joints[j].parent) ) add_openrave(doc,l,self.joints[j].origin) break #Add adjacencies for j in self.joints.values(): kinbody.appendChild(create_element(doc,"adjacent",[j.parent, j.child])) #Add known extra adjacencies badjoints={'LAR':'LKP','LWR':'LWY','LSY':'LSP','LHY':'LHP', 'RAR':'RKP','RWR':'RWY','RSY':'RSP','RHY':'RHP', 'NK1':'Torso'} for k,v in badjoints.items(): #TODO: search all bodies for above pairs and add extra adjacency tags b1=None b2=None for b in kinbody.getElementsByTagName('body'): if re.search(k,b.getAttribute('name')): b1=b.getAttribute('name') if re.search(v,b.getAttribute('name')): b2=b.getAttribute('name') if b1 and b2: kinbody.appendChild(create_element(doc,"adjacent",[b1, b2])) return kinbody def to_openrave_xml(self): doc = Document() root = doc.createElement("robot") doc.appendChild(root) root.setAttribute("name", self.name) root.appendChild(self.make_openrave_kinbody(doc)) return doc.toprettyxml() def write_reformatted(self,data,name): if name is None: name=self.name outdata=re.sub(r'\t',' ',data) with open(name,'w+') as f: f.write(outdata) def write_openrave_files(self,outname=None,writerobot=False): if outname is None: outname=self.name kinfile=outname+'.kinbody.xml' if writerobot: robotfile=outname+'.robot.xml' doc = Document() root = doc.createElement("robot") doc.appendChild(root) root.setAttribute("name", outname) kinbody = doc.createElement("kinbody") root.appendChild(kinbody) kinbody.setAttribute("name", outname) kinbody.setAttribute("file", kinfile) self.write_reformatted(doc.toprettyxml(),robotfile) doc2 = Document() doc2.appendChild(self.make_openrave_kinbody(doc2)) self.write_reformatted(doc2.toprettyxml(),kinfile) def __str__(self): s = "Name: {0}\n".format(self.name) s += "\n" s += "Links:\n" if len(self.links) == 0: s += "None\n" else: for k, v in self.links.iteritems(): s += "- Link '{0}':\n{1}\n".format(k, reindent(str(v), 1)) s += "\n" s += "Joints:\n" if len(self.joints) == 0: s += "None\n" else: for k, v in self.joints.iteritems(): s += "- Joint '{0}':\n{1}\n".format(k, reindent(str(v), 1)) s += "\n" s += "Materials:\n" if len(self.materials) == 0: s += "None\n" else: for k, v in self.materials.iteritems(): s += "- Material '{0}':\n{1}\n".format(k, reindent(str(v), 1)) return s def walk_chain(self,link,branchorder=None): """Walk along the first branch of urdf tree to find last link. Optionally specify which fork to take globally).""" child=link if branchorder is None: branchorder=0 while self.child_map.has_key(child): children=self.child_map[link] l=len(children) child=children[min(branchorder,l-1)][1] return child def rename_link(self,link,newlink): """Rename a link, updating all internal references to the name, and removing the old name from the links dict.""" self.links[link].name=newlink self.links[newlink]=self.links[link] self.links.pop(link) for k,v in self.parent_map.items(): if k==link: self.parent_map[newlink]=v self.parent_map.pop(k) k=newlink if v[0]==link: new0=newlink v=(new0,v[1]) if v[1]==link: new1=newlink v=(v[0],new1) self.parent_map[k]=v for k,v in self.child_map.items(): if k==link: self.child_map[newlink]=v self.child_map.pop(k) k=newlink vnew=[] for el in v: if el[1]==link: el=(el[0],newlink) vnew.append(el) # print vnew self.child_map[k]=vnew for n,j in self.joints.items(): if j.parent==link: j.parent=newlink if j.child==link: j.child=newlink #print self.child_map def rename_joint(self,joint,newjoint): """Find a joint and rename it to newjoint, updating all internal structures and mimic joints with the new name. Removes the old joint reference from the joints list.""" self.joints[joint].name=newjoint self.joints[newjoint]=self.joints[joint] self.joints.pop(joint) for k,v in self.child_map.items(): vnew=[] for el in v: if el[0]==joint: el=(newjoint,el[1]) print el vnew.append(el) self.child_map[k]=vnew for k,v in self.parent_map.items(): if v[0]==joint: v=(newjoint,v[1]) print el self.parent_map[k]=v for n,j in self.joints.items(): if j.mimic is not None: j.mimic.joint_name=newjoint if j.mimic.joint_name==joint else j.mimic.joint_name def copy_joint(self,joint,f,r): """Copy and rename a joint and it's parent/child by the f / r strings. Assumes links exist. Note that it renames the parent and child, so use this with copy_link""" newjoint=copy.deepcopy(self.joints[joint]) newjoint.name=re.sub(f,r,newjoint.name) newjoint.parent=re.sub(f,r,newjoint.parent) newjoint.child=re.sub(f,r,newjoint.child) self.add_joint(newjoint) return newjoint def move_chain_with_rottrans(self,root,tip,rpy,xyz,f,r): """Find and rename a kinematic chain based on the given root and top names. Renames all links and joints according to find and replace terms. """ linkchain=self.get_chain(root,tip,links=True,joints=False) jointchain=self.get_chain(root,tip,joints=True,links=False) print linkchain print jointchain for l in linkchain[1:]: newlink=re.sub(f,r,l) self.rename_link(l,newlink) for j in jointchain: newname=re.sub(f,r,j) self.rename_joint(j,newname) self.joints[newname].origin.position+=array(xyz) self.joints[newname].origin.rotation+=array(rpy) if self.joints[newname].mimic is not None: self.joints[newname].mimic.joint_name=re.sub(f,r,self.joints[newname].mimic.joint_name) def copy_chain_with_rottrans(self,root,tip,rpy,xyz,f,r,mir_ax=None): """Copy a kinematic chain, renaming joints and links according to a regular expression. Note that this is designed to work with the Hubo joint / body convention, which has an easy pattern for joint and body names. If your model has joints and links that are not systematically named, this function won't be much use. """ linkchain=self.get_chain(root,tip,links=True,joints=False) jointchain=self.get_chain(root,tip,joints=True,links=False) print linkchain print jointchain newjoints=[] newlinks=[] for l in linkchain[1:]: newlink=copy.deepcopy(self.links[l]) newlink.name=re.sub(f,r,newlink.name) if newlink.collision is not None: newlink.collision.geometry.filename=re.sub(f,r,newlink.collision.geometry.filename) newlink.visual.geometry.filename=re.sub(f,r,newlink.visual.geometry.filename) self.add_link(newlink) newlinks.append(newlink) if mir_ax == 'x': newlink.inertial.matrix['ixy']*=-1. newlink.inertial.matrix['ixz']*=-1. newlink.inertial.origin.position[0]*=-1. if mir_ax == 'y': newlink.inertial.matrix['ixy']*=-1. newlink.inertial.matrix['iyz']*=-1. newlink.inertial.origin.position[1]*=-1. if mir_ax == 'z': newlink.inertial.matrix['ixz']*=-1. newlink.inertial.matrix['iyz']*=-1. newlink.inertial.origin.position[2]*=-1. #Hack to rotate just first joint for j in jointchain: newjoints.append(self.copy_joint(j,f,r)) if mir_ax == 'x': newjoints[-1].origin.position[0]*=-1.0 newjoints[-1].origin.rotation[1]*=-1.0 newjoints[-1].origin.rotation[2]*=-1.0 if mir_ax == 'y': newjoints[-1].origin.position[1]*=-1.0 newjoints[-1].origin.rotation[0]*=-1.0 newjoints[-1].origin.rotation[2]*=-1.0 if mir_ax == 'z': newjoints[-1].origin.position[2]*=-1.0 newjoints[-1].origin.rotation[0]*=-1.0 newjoints[-1].origin.rotation[1]*=-1.0 if mir_ax =='rotx': newjoints[0].origin.position[1]*=-1.0 for j in newjoints: if j.mimic is not None: j.mimic.joint_name=re.sub(f,r,j.mimic.joint_name) newjoints[0].origin.position+=array(xyz) newjoints[0].origin.rotation+=array(rpy) def fix_mesh_case(self): for l in self.links: fname=l.collision.geometry.filename l.collision.geometry.filename=re.sub(r'\.[Ss][Tt][Ll]','.stl',fname) #TODO: merge function to tie two chains together from disparate models def update_mesh_paths(self,package_name): """Search and replace package paths in urdf with chosen package name""" for n,l in self.links.items(): #TODO: check if mesh for g in [l.collision.geometry,l.visual.geometry]: #save STL file name only meshfile=g.filename.split('/')[-1] newpath=[package_name,'meshes',meshfile] cleanpath=re.sub('/+','/','/'.join(newpath)) g.filename='package://'+cleanpath l.collision.geometry.filename=re.sub('Body','convhull',l.collision.geometry.filename) def apply_default_limits(self,effort,vel,lower,upper,mask=None): """Apply default limits to all joints and convert continous joints to revolute. Ignores fixed and other joint types.""" for n,j in self.joints.items(): if mask is None or re.search(mask,n): if j.joint_type==Joint.CONTINUOUS or j.joint_type==Joint.REVOLUTE: j.limits=JointLimit(effort,vel,lower,upper) j.joint_type=Joint.REVOLUTE if __name__ == '__main__': #try: #from openhubo import startup #except ImportError: #pass try: filename=sys.argv[1] except IndexError: print "Please supply a URDF filename to convert!" try: outname=sys.argv[2] except IndexError: outname=None model=URDF.load_xml_file(filename) model.write_openrave_files(outname)
# -*- coding: utf-8 -*- import os from collections import deque import uuid from lockfile import LockFile, AlreadyLocked, NotLocked, NotMyLock from django.core.cache import get_cache from django.core.cache.backends.memcached import MemcachedCache from django.core.cache.backends.dummy import DummyCache from django.core.exceptions import ImproperlyConfigured from django.conf import settings class CacheKeyRegistry(object): """ Manages a *unique* cache key registry in cache. Note that this *is not* thread-safe, so it should run within a thread-safe environment to be considered so. """ def __init__(self, registry_key, client, timeout=None): self.registry_key = registry_key self.client = client self.timeout = timeout or self.client.default_timeout def all(self): """ Returns current keys in registry. """ # keys could have timed out return self.client.get(self.registry_key, deque([])) def add(self, key): """ Adds new key to registry. """ keys = self.all() keys.append(key) self.client.set(self.registry_key, keys, self.timeout) def pop(self): """ Pops first key from registry. """ keys = self.all() try: key = keys.popleft() self.client.set(self.registry_key, keys, self.timeout) return key except IndexError: # no keys in registry return None def remove(self, key): """ Removes key from registry. """ keys = self.all() try: # attempt to remove key. note that this # method assumes all keys are unique. keys.remove(key) self.client.set(self.registry_key, keys, self.timeout) except ValueError: # key was not in registry pass def reset(self): """ Resets all keys from registry. Be careful when using this, as you could affect other programs using the registry. """ self.client.set(self.registry_key, deque([]), self.timeout) class BaseCacheQueue(object): """ This object creates a non-blocking thread-safe FIFO queue using django's cache api. Note that only some backends support atomic operations, so the .lock() and .release() methods should be defined in subclasses, depending on the cache backend in use. """ def __init__(self, name, client=None): """ General setup. """ # setup _cqsettings = getattr(settings, 'CACHEQ', {}) self.lockfile = _cqsettings.get('LOCKFILE', '/var/tmp/cacheq.lock') # create lockfile if it doesn't exist with open(self.lockfile, 'w+') as f: pass self.client = client or get_cache(_cqsettings.get('CACHE', 'default')) self.name = name # lock and key registry need to last indefinately # so we set timeout accordingly self.lock_key = 'CacheQueue:%s:lock' % self.name self.timeout = max(self.client.default_timeout, 60*60*24*365*2) # check compatibility & ping cache self.check_compatibility() self.ping_cache() # add a key registry. this registry is what really manages the queue. # it is not thread-safe, so we need to run it from within CacheQueue. self.registry = CacheKeyRegistry( registry_key='CacheQueue:%s:registry' % self.name, client=self.client, timeout=self.timeout) # Overload these methods ######################## def check_compatibility(self): """ Checks compatibility with provided client. """ raise NotImplementedError("Please overload this method.") def lock(self): """ Acquire a lock for thread safe operation. """ raise NotImplementedError("Please overload this method.") def release(self): """ Release acquired lock. """ raise NotImplementedError("Please overload this method.") # Base methods ############### def ping_cache(self): """ Pings cache to check if it's running. Returns True if it is, False if not. """ key = getattr(self, 'ping_key', None) if key is None: self.ping_key = 'CacheQueue:%s:ping' % self.name self.client.set(self.ping_key, True) if not self.client.get(self.ping_key, False): raise ImproperlyConfigured("Cache not responding, please verify it's running.") def random_message_key(self): """ Builds a random message key using uuid. """ return 'CacheQueue:%s:message:%s' % (self.name, str(uuid.uuid4())) def add_message(self, message): """ Attempts a lock. If successful, sets a message and releases. """ if not self.lock(): return # generate a unique random key message_key = self.random_message_key() # try to set message try: self.client.set(message_key, message, timeout=self.timeout) self.registry.add(message_key) except: # TODO: log # if there was an error, we must cleanup self.client.delete(message_key) # note that registry.remove assumes all keys are unique self.registry.remove(message_key) finally: # relase lock self.release() def pop_message(self): """ Attempts a lock. If successful, attempts to pop message by FIFO and releases. """ if not self.lock(): # If there was a lock, we return False, which should be # interpreted as lock being on, not queue being empty return False # Get message key message_key = self.registry.pop() # if no message_key was returned, we return none. this should # be interpreted as an empty queue. if not message_key: # release lock self.release() return None try: # else we fetch message message = self.client.get(message_key) # remove message self.client.delete(message_key) finally: # release lock self.release() return message def reset(self): """ Resets queue, release lock and deletes all messages. Be careful with this, as you could affect other programs using the queue. """ self.client.delete_many(self.registry.all()) self.registry.reset() self.release() class MemcachedCacheQueue(BaseCacheQueue): """ Implements a thread safe cache queue using django's MemcachedCache cache backend. This queue is compatible only with memcached backend, and works completely in memory. """ def check_compatibility(self): """ Checks that backend is MemcachedCache. """ if type(self.client) is not MemcachedCache: raise ImproperlyConfigured("This queue only supports MemcachedCache backend or a memcache client.") def lock(self): """ Method used by MemcachedCache to acquire a lock. Returns True if lock is acquired, else False. """ locked = self.client.add(self.lock_key, 1, timeout=self.timeout) # if cache is down, we will get 0 if locked == 0: self.ping_cache() # if we acquired a lock, we'll get True # if we could not acquire lock, but cache # is running, we'll get False return locked def release(self): """ Method used by MemcachedCache to release a lock. """ # This will always return None, even if cache is down self.client.delete(self.lock_key) class RedisCacheQueue(MemcachedCacheQueue): """ Works exactly the same way as memcached, for now. """ def check_compatibility(self): """ Checks that backend is MemcachedCache. """ if type(self.client).__name__ != 'RedisCache': raise ImproperlyConfigured("This queue only supports RedisCache backends.") class LockFileCacheQueue(BaseCacheQueue): """ Implements a thread safe cache queue using python's lockfile module. This queue is compatible with all cache backends, except DummyCache. """ def check_compatibility(self): """ Checks that backend is supported. DummyCache: not compatible Memcached: not compatible Other backends: compatible Valid self.lockfile: required """ if type(self.client) in [MemcachedCache, DummyCache]: raise ImproperlyConfigured("This queue does not support MemcachedCache nor DummyCache.") if not os.path.exists(self.lockfile): msg = "%s backend requires the use of a lockfile to work with this queue." raise ImproperlyConfigured(msg % type(self.client)) def lock(self): """ Method used for acquiring a lock using the lockfile module. """ lock = LockFile(self.lockfile) # check if it's locked if lock.is_locked(): # Note that lock.i_am_locking() could be True, so # this apporach is not really efficient from a threading # point of view. However, we must be consistent with # MemcachedCacheQueue's behavior. return False # else we can attempt to acquire a lock # we don't want this to fail silently # so we set timeout=0 lock.acquire(timeout=0) return True def release(self): """ Method used to release a lock using the lockfile module. """ lock = LockFile(self.lockfile) if lock.i_am_locking(): lock.release() def get_cache_queue(name, using=''): """ Returns an instance of the best alternative of cache queue, given the cache cache to use. """ if not using: _cqsettings = getattr(settings, 'CACHEQ', {}) using = _cqsettings.get('CACHE', 'default') cache = get_cache(using) if type(cache) is MemcachedCache: return MemcachedCacheQueue(name=name, client=cache) if type(cache).__name__ == 'RedisCache': return RedisCacheQueue(name=name, client=cache) # else default to lock file based queue return LockFileCacheQueue(name=name, client=cache)
# Copyright [2015] Hewlett-Packard Development Company, L.P. # Copyright 2016 Tesora 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 novaclient import exceptions as nova_exceptions from oslo_log import log as logging from trove.cluster import models as cluster_models from trove.cluster.tasks import ClusterTasks from trove.cluster.views import ClusterView from trove.common import cfg from trove.common import exception from trove.common import remote from trove.common.strategies.cluster import base as cluster_base from trove.extensions.mgmt.clusters.views import MgmtClusterView from trove.instance.models import DBInstance from trove.instance.models import Instance from trove.quota.quota import check_quotas from trove.taskmanager import api as task_api LOG = logging.getLogger(__name__) CONF = cfg.CONF class GaleraCommonAPIStrategy(cluster_base.BaseAPIStrategy): @property def cluster_class(self): return GaleraCommonCluster @property def cluster_view_class(self): return GaleraCommonClusterView @property def mgmt_cluster_view_class(self): return GaleraCommonMgmtClusterView class GaleraCommonCluster(cluster_models.Cluster): @staticmethod def _validate_cluster_instances(context, instances, datastore, datastore_version): """Validate the flavor and volume""" ds_conf = CONF.get(datastore_version.manager) num_instances = len(instances) # Check number of instances is at least min_cluster_member_count if num_instances < ds_conf.min_cluster_member_count: raise exception.ClusterNumInstancesNotLargeEnough( num_instances=ds_conf.min_cluster_member_count) # Checking flavors and get delta for quota check flavor_ids = [instance['flavor_id'] for instance in instances] if len(set(flavor_ids)) != 1: raise exception.ClusterFlavorsNotEqual() flavor_id = flavor_ids[0] nova_client = remote.create_nova_client(context) try: flavor = nova_client.flavors.get(flavor_id) except nova_exceptions.NotFound: raise exception.FlavorNotFound(uuid=flavor_id) deltas = {'instances': num_instances} # Checking volumes and get delta for quota check volume_sizes = [instance['volume_size'] for instance in instances if instance.get('volume_size', None)] volume_size = None if ds_conf.volume_support: if len(volume_sizes) != num_instances: raise exception.ClusterVolumeSizeRequired() if len(set(volume_sizes)) != 1: raise exception.ClusterVolumeSizesNotEqual() volume_size = volume_sizes[0] cluster_models.validate_volume_size(volume_size) deltas['volumes'] = volume_size * num_instances else: if len(volume_sizes) > 0: raise exception.VolumeNotSupported() ephemeral_support = ds_conf.device_path if ephemeral_support and flavor.ephemeral == 0: raise exception.LocalStorageNotSpecified(flavor=flavor_id) # quota check check_quotas(context.tenant, deltas) # Checking networks are same for the cluster instance_nics = [instance.get('nics', None) for instance in instances] if len(set(instance_nics)) != 1: raise exception.ClusterNetworksNotEqual() instance_nic = instance_nics[0] if instance_nic is None: return try: nova_client.networks.get(instance_nic) except nova_exceptions.NotFound: raise exception.NetworkNotFound(uuid=instance_nic) @staticmethod def _create_instances(context, db_info, datastore, datastore_version, instances): member_config = {"id": db_info.id, "instance_type": "member"} name_index = 1 for instance in instances: if not instance.get("name"): instance['name'] = "%s-member-%s" % (db_info.name, str(name_index)) name_index += 1 return map(lambda instance: Instance.create(context, instance['name'], instance['flavor_id'], datastore_version.image_id, [], [], datastore, datastore_version, instance.get('volume_size', None), None, availability_zone=instance.get( 'availability_zone', None), nics=instance.get('nics', None), configuration_id=None, cluster_config=member_config ), instances) @classmethod def create(cls, context, name, datastore, datastore_version, instances, extended_properties): LOG.debug("Initiating Galera cluster creation.") cls._validate_cluster_instances(context, instances, datastore, datastore_version) # Updating Cluster Task db_info = cluster_models.DBCluster.create( name=name, tenant_id=context.tenant, datastore_version_id=datastore_version.id, task_status=ClusterTasks.BUILDING_INITIAL) cls._create_instances(context, db_info, datastore, datastore_version, instances) # Calling taskmanager to further proceed for cluster-configuration task_api.load(context, datastore_version.manager).create_cluster( db_info.id) return cls(context, db_info, datastore, datastore_version) def _get_cluster_network_interfaces(self): nova_client = remote.create_nova_client(self.context) nova_instance_id = self.db_instances[0].compute_instance_id interfaces = nova_client.virtual_interfaces.list(nova_instance_id) ret = [{"net-id": getattr(interface, 'net_id')} for interface in interfaces] return ret def grow(self, instances): LOG.debug("Growing cluster %s." % self.id) self.validate_cluster_available() context = self.context db_info = self.db_info datastore = self.ds datastore_version = self.ds_version db_info.update(task_status=ClusterTasks.GROWING_CLUSTER) try: # Get the network of the existing cluster instances. interface_ids = self._get_cluster_network_interfaces() for instance in instances: instance["nics"] = interface_ids new_instances = self._create_instances( context, db_info, datastore, datastore_version, instances) task_api.load(context, datastore_version.manager).grow_cluster( db_info.id, [instance.id for instance in new_instances]) except Exception: db_info.update(task_status=ClusterTasks.NONE) return self.__class__(context, db_info, datastore, datastore_version) def shrink(self, instances): """Removes instances from a cluster.""" LOG.debug("Shrinking cluster %s." % self.id) self.validate_cluster_available() removal_instances = [Instance.load(self.context, inst_id) for inst_id in instances] db_instances = DBInstance.find_all(cluster_id=self.db_info.id).all() if len(db_instances) - len(removal_instances) < 1: raise exception.ClusterShrinkMustNotLeaveClusterEmpty() self.db_info.update(task_status=ClusterTasks.SHRINKING_CLUSTER) try: task_api.load(self.context, self.ds_version.manager ).shrink_cluster(self.db_info.id, [instance.id for instance in removal_instances]) except Exception: self.db_info.update(task_status=ClusterTasks.NONE) return self.__class__(self.context, self.db_info, self.ds, self.ds_version) class GaleraCommonClusterView(ClusterView): def build_instances(self): return self._build_instances(['member'], ['member']) class GaleraCommonMgmtClusterView(MgmtClusterView): def build_instances(self): return self._build_instances(['member'], ['member'])
"""A collection of functions to summarize object information. This module provides several function which will help you to analyze object information which was gathered. Often it is sufficient to work with aggregated data instead of handling the entire set of existing objects. For example can a memory leak identified simple based on the number and size of existing objects. A summary contains information about objects in a table-like manner. Technically, it is a list of lists. Each of these lists represents a row, whereas the first column reflects the object type, the second column the number of objects, and the third column the size of all these objects. This allows a simple table-like output like the following: ============= ============ ============= types # objects total size ============= ============ ============= <type 'dict'> 2 560 <type 'str'> 3 126 <type 'int'> 4 96 <type 'long'> 2 66 <type 'list'> 1 40 ============= ============ ============= Another advantage of summaries is that they influence the system you analyze only to a minimum. Working with references to existing objects will keep these objects alive. Most of the times this is no desired behavior (as it will have an impact on the observations). Using summaries reduces this effect greatly. output representation --------------------- The output representation of types is defined in summary.representations. Every type defined in this dictionary will be represented as specified. Each definition has a list of different representations. The later a representation appears in this list, the higher its verbosity level. From types which are not defined in summary.representations the default str() representation will be used. Per default, summaries will use the verbosity level 1 for any encountered type. The reason is that several computations are done with summaries and rows have to remain comparable. Therefore information which reflect an objects state, e.g. the current line number of a frame, should not be included. You may add more detailed information at higher verbosity levels than 1. """ import re import sys import types from pympler.util import stringutils # default to asizeof if sys.getsizeof is not available (prior to Python 2.6) try: from sys import getsizeof as _getsizeof except ImportError: from pympler.asizeof import flatsize _getsizeof = flatsize representations = {} def _init_representations(): global representations if sys.hexversion < 0x2040000: classobj = [ lambda c: "classobj(%s)" % repr(c), ] representations[types.ClassType] = classobj instance = [ lambda f: "instance(%s)" % repr(f.__class__), ] representations[types.InstanceType] = instance instancemethod = [ lambda i: "instancemethod (%s)" % (repr(i.im_func)), lambda i: "instancemethod (%s, %s)" % (repr(i.im_class), repr(i.im_func)), ] representations[types.MethodType] = instancemethod frame = [ lambda f: "frame (codename: %s)" % (f.f_code.co_name), lambda f: "frame (codename: %s, codeline: %s)" % (f.f_code.co_name, f.f_code.co_firstlineno), lambda f: "frame (codename: %s, filename: %s, codeline: %s)" % (f.f_code.co_name, f.f_code.co_filename, f.f_code.co_firstlineno) ] representations[types.FrameType] = frame _dict = [ lambda d: str(type(d)), lambda d: "dict, len=%s" % len(d), ] representations[dict] = _dict function = [ lambda f: "function (%s)" % f.__name__, lambda f: "function (%s.%s)" % (f.__module, f.__name__), ] representations[types.FunctionType] = function _list = [ lambda l: str(type(l)), lambda l: "list, len=%s" % len(l) ] representations[list] = _list module = [lambda m: "module(%s)" % m.__name__] representations[types.ModuleType] = module _set = [ lambda s: str(type(s)), lambda s: "set, len=%s" % len(s) ] representations[set] = _set _init_representations() def summarize(objects): """Summarize an objects list. Return a list of lists, whereas each row consists of:: [str(type), number of objects of this type, total size of these objects]. No guarantee regarding the order is given. """ count = {} total_size = {} for o in objects: otype = _repr(o) if otype in count: count[otype] += 1 total_size[otype] += _getsizeof(o) else: count[otype] = 1 total_size[otype] = _getsizeof(o) rows = [] for otype in count: rows.append([otype, count[otype], total_size[otype]]) return rows def get_diff(left, right): """Get the difference of two summaries. Subtracts the values of the right summary from the values of the left summary. If similar rows appear on both sides, the are included in the summary with 0 for number of elements and total size. If the number of elements of a row of the diff is 0, but the total size is not, it means that objects likely have changed, but not there number, thus resulting in a changed size. """ res = [] for row_r in right: found = False for row_l in left: if row_r[0] == row_l[0]: res.append([row_r[0], row_r[1] - row_l[1], row_r[2] - row_l[2]]) found = True if not found: res.append(row_r) for row_l in left: found = False for row_r in right: if row_l[0] == row_r[0]: found = True if not found: res.append([row_l[0], -row_l[1], -row_l[2]]) return res def format_(rows, limit=15, sort='size', order='descending'): """Format the rows as a summary. Keyword arguments: limit -- the maximum number of elements to be listed sort -- sort elements by 'size', 'type', or '#' order -- sort 'ascending' or 'descending' """ localrows = [] for row in rows: localrows.append(list(row)) # input validation sortby = ['type', '#', 'size'] if sort not in sortby: raise ValueError("invalid sort, should be one of" + str(sortby)) orders = ['ascending', 'descending'] if order not in orders: raise ValueError("invalid order, should be one of" + str(orders)) # sort rows if sortby.index(sort) == 0: if order == "ascending": localrows.sort(key=lambda x: _repr(x[0])) elif order == "descending": localrows.sort(key=lambda x: _repr(x[0]), reverse=True) else: if order == "ascending": localrows.sort(key=lambda x: x[sortby.index(sort)]) elif order == "descending": localrows.sort(key=lambda x: x[sortby.index(sort)], reverse=True) # limit rows localrows = localrows[0:limit] for row in localrows: row[2] = stringutils.pp(row[2]) # print rows localrows.insert(0, ["types", "# objects", "total size"]) return _format_table(localrows) def _format_table(rows, header=True): """Format a list of lists as a pretty table. Keyword arguments: header -- if True the first row is treated as a table header inspired by http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662 """ border = "=" # vertical delimiter vdelim = " | " # padding nr. of spaces are left around the longest element in the # column padding = 1 # may be left,center,right justify = 'right' justify = {'left': str.ljust, 'center': str.center, 'right': str.rjust}[justify.lower()] # calculate column widths (longest item in each col # plus "padding" nr of spaces on both sides) cols = zip(*rows) colWidths = [max([len(str(item)) + 2 * padding for item in col]) for col in cols] borderline = vdelim.join([w * border for w in colWidths]) for row in rows: yield vdelim.join([justify(str(item), width) for (item, width) in zip(row, colWidths)]) if header: yield borderline header = False def print_(rows, limit=15, sort='size', order='descending'): """Print the rows as a summary. Keyword arguments: limit -- the maximum number of elements to be listed sort -- sort elements by 'size', 'type', or '#' order -- sort 'ascending' or 'descending' """ for line in format_(rows, limit=limit, sort=sort, order=order): print(line) # regular expressions used by _repr to replace default type representations type_prefix = re.compile(r"^<type '") address = re.compile(r' at 0x[0-9a-f]+') type_suffix = re.compile(r"'>$") def _repr(o, verbosity=1): """Get meaning object representation. This function should be used when the simple str(o) output would result in too general data. E.g. "<type 'instance'" is less meaningful than "instance: Foo". Keyword arguments: verbosity -- if True the first row is treated as a table header """ res = "" t = type(o) if (verbosity == 0) or (t not in representations): res = str(t) else: verbosity -= 1 if len(representations[t]) < verbosity: verbosity = len(representations[t]) - 1 res = representations[t][verbosity](o) res = address.sub('', res) res = type_prefix.sub('', res) res = type_suffix.sub('', res) return res def _traverse(summary, function, *args): """Traverse all objects of a summary and call function with each as a parameter. Using this function, the following objects will be traversed: - the summary - each row - each item of a row """ function(summary, *args) for row in summary: function(row, *args) for item in row: function(item, *args) def _subtract(summary, o): """Remove object o from the summary by subtracting it's size.""" found = False row = [_repr(o), 1, _getsizeof(o)] for r in summary: if r[0] == row[0]: (r[1], r[2]) = (r[1] - row[1], r[2] - row[2]) found = True if not found: summary.append([row[0], -row[1], -row[2]]) return summary def _sweep(summary): """Remove all rows in which the total size and the total number of objects is zero. """ return [row for row in summary if ((row[2] != 0) or (row[1] != 0))]
# =============================================================================== # Copyright 2016 Jake Ross # # 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. # =============================================================================== # ============= enthought library imports ======================= import os import time from operator import attrgetter import yaml from pyface.constant import OK from pyface.file_dialog import FileDialog from traits.api import Str, Button, List from traitsui.api import View, UItem, VGroup from traitsui.editors import TabularEditor from traitsui.tabular_adapter import TabularAdapter from pychron.core.helpers.filetools import unique_path2, add_extension from pychron.core.progress import progress_iterator, open_progress from pychron.envisage.browser.record_views import RepositoryRecordView from pychron.loggable import Loggable from pychron.paths import paths def database_path(): return os.path.join(paths.offline_db_dir, 'index.sqlite3') def switch_to_offline_database(preferences): prefid = 'pychron.dvc.connection' kind = '{}.kind'.format(prefid) path = '{}.path'.format(prefid) preferences.set(kind, 'sqlite') preferences.set(path, database_path()) preferences.save() class RepositoryTabularAdapter(TabularAdapter): columns = [('Name', 'name'), ('Create Date', 'created_at'), ('Last Change', 'pushed_at')] class WorkOffline(Loggable): """ 1. Select set of repositories 2. clone repositories 3. update the meta repo 4. copy the central db to a sqlite db 5. set DVC db preferences to sqlite """ work_offline_user = Str work_offline_password = Str repositories = List selected_repositories = List work_offline_button = Button('Work Offline') def initialize(self): """ check internet connection. a. check database b. check github """ if self._check_database_connection(): if self._check_githost_connection(): repos = self.dvc.remote_repositories() repos = [RepositoryRecordView(name=r['name'], created_at=r['created_at'], pushed_at=r['pushed_at']) for r in repos] metaname = os.path.basename(paths.meta_root) repos = sorted([ri for ri in repos if ri.name != metaname], key=attrgetter('name')) self.repositories = repos return True # private def _check_database_connection(self): return self.dvc.connect() def _check_githost_connection(self): return self.dvc.check_githost_connection() def _work_offline(self): self.debug('work offline') # clone repositories if not self._clone_repositories(): return # update meta self.dvc.open_meta_repo() self.dvc.meta_pull() # clone central db repos = [ri.name for ri in self.selected_repositories] path = self._clone_central_db(repos) if not path: return apath = None # create dvc archive if self.confirmation_dialog('Create shareable archive'): dialog = FileDialog(action='save as', default_directory=paths.data_dir) if dialog.open() == OK: apath = dialog.path if apath: apath = add_extension(apath, '.pz') with open(apath, 'wb') as wfile: with open(path, 'rb') as dbfile: ctx = {'meta_repo_name': self.dvc.meta_repo_name, 'meta_repo_dirname': self.dvc.meta_repo_dirname, 'organization': self.dvc.organization, 'database': dbfile.read()} yaml.dump(ctx, wfile, encoding='utf-8') # msg = 'Would you like to switch to the offline database?' # if self.confirmation_dialog(msg): # # update DVC preferences # self._update_preferences() def _clone_repositories(self): self.debug('clone repositories') # check for selected repositories if not self.selected_repositories: return # clone the repositories def func(x, prog, i, n): if prog is not None: prog.change_message('Cloning {}'.format(x.name)) self.dvc.clone_repository(x.name) progress_iterator(self.selected_repositories, func, threshold=0) return True def _get_new_path(self): return unique_path2(paths.dvc_dir, 'index', extension='.sqlite3')[0] def _clone_central_db(self, repositories, analyses=None, principal_investigators=None, projects=None): self.info('--------- Clone DB -----------') # create an a sqlite database from pychron.dvc.dvc_orm import Base metadata = Base.metadata from pychron.dvc.dvc_database import DVCDatabase path = database_path() if os.path.isfile(path): if not self.confirmation_dialog('The database "{}" already exists. ' 'Do you want to overwrite it'.format(os.path.basename(path))): path = self._get_new_path() else: os.remove(path) if path: progress = open_progress(n=20) self.debug('--------- Starting db clone to {}'.format(path)) src = self.dvc db = DVCDatabase(path=path, kind='sqlite') db.connect() with db.session_ctx(use_parent_session=False) as sess: metadata.create_all(sess.bind) tables = ['MassSpectrometerTbl', 'ExtractDeviceTbl', 'VersionTbl', 'UserTbl'] for table in tables: mod = __import__('pychron.dvc.dvc_orm', fromlist=[table]) progress.change_message('Cloning {}'.format(table)) self._copy_table(db, getattr(mod, table)) with src.session_ctx(use_parent_session=False): from pychron.dvc.dvc_orm import RepositoryTbl from pychron.dvc.dvc_orm import AnalysisTbl from pychron.dvc.dvc_orm import AnalysisChangeTbl from pychron.dvc.dvc_orm import RepositoryAssociationTbl from pychron.dvc.dvc_orm import AnalysisGroupTbl from pychron.dvc.dvc_orm import AnalysisGroupSetTbl from pychron.dvc.dvc_orm import MaterialTbl from pychron.dvc.dvc_orm import SampleTbl from pychron.dvc.dvc_orm import IrradiationTbl from pychron.dvc.dvc_orm import LevelTbl from pychron.dvc.dvc_orm import IrradiationPositionTbl from pychron.dvc.dvc_orm import PrincipalInvestigatorTbl repos = [src.db.get_repository(reponame) for reponame in repositories] progress.change_message('Assembling Analyses 0/5') st = time.time() if analyses: ans = analyses ras = [rai for ai in ans for rai in ai.repository_associations] else: # at = time.time() ras = [ra for repo in repos for ra in repo.repository_associations] # self.debug('association time={}'.format(time.time()-at)) progress.change_message('Assembling Analyses 1/5') # at = time.time() ans = [ri.analysis for ri in ras] # self.debug('analysis time={}'.format(time.time()-at)) progress.change_message('Assembling Analyses 2/5') # at = time.time() ans_c = [ai.change for ai in ans] # self.debug('change time={}'.format(time.time()-at)) progress.change_message('Assembling Analyses 3/5') # at = time.time() agss = [gi for ai in ans for gi in ai.group_sets] # self.debug('agss time={}'.format(time.time()-at)) progress.change_message('Assembling Analyses 4/5') # at = time.time() ags = {gi.group for gi in agss} # self.debug('ags time={}'.format(time.time()-at)) progress.change_message('Assembling Analyses 5/5') self.debug('total analysis assembly time={}'.format(time.time()-st)) self._copy_records(progress, db, RepositoryTbl, repos) self._copy_records(progress, db, RepositoryAssociationTbl, ras) self._copy_records(progress, db, AnalysisTbl, ans) self._copy_records(progress, db, AnalysisChangeTbl, ans_c) self._copy_records(progress, db, AnalysisGroupTbl, ags) self._copy_records(progress, db, AnalysisGroupSetTbl, agss) if principal_investigators: pis = [src.get_principal_investigator(pp.name) for pp in principal_investigators] else: pis = {repo.principal_investigator for repo in repos} self._copy_records(progress, db, PrincipalInvestigatorTbl, pis) from pychron.dvc.dvc_orm import ProjectTbl if projects: prjs = [src.get_project(pp) for pp in projects] else: prjs = {ai.irradiation_position.sample.project for ai in ans} self._copy_records(progress, db, ProjectTbl, prjs) ips = {ai.irradiation_position for ai in ans} sams = {ip.sample for ip in ips} mats = {si.material for si in sams} self._copy_records(progress, db, MaterialTbl, mats) self._copy_records(progress, db, SampleTbl, sams) ls = {ip.level for ip in ips} irs = {l.irradiation for l in ls} self._copy_records(progress, db, IrradiationTbl, irs) self._copy_records(progress, db, LevelTbl, ls) self._copy_records(progress, db, IrradiationPositionTbl, ips) self.debug('--------- db clone finished') progress.close() self.information_dialog('Database saved to "{}"'.format(path)) return path def _copy_records(self, progress, dest, table, records): st = time.time() msg = 'Copying records from {}. n={}'.format(table.__tablename__, len(records)) self.debug(msg) progress.change_message(msg) with dest.session_ctx(use_parent_session=False) as dest_sess: keys = list(table.__table__.columns.keys()) mappings = ({k: getattr(row, k) for k in keys} for row in records) dest_sess.bulk_insert_mappings(table, mappings) dest_sess.commit() self.debug('copy finished et={:0.5f}'.format(time.time()-st)) def _copy_table(self, dest, table, filter_criterion=None): src = self.dvc with src.session_ctx(use_parent_session=False) as src_sess: query = src_sess.query(table) if filter_criterion: query = query.filter(filter_criterion) with dest.session_ctx(use_parent_session=False) as dest_sess: keys = list(table.__table__.columns.keys()) mappings = [{k: getattr(row, k) for k in keys} for row in query] dest_sess.bulk_insert_mappings(table, mappings) dest_sess.commit() def _update_preferences(self): self.debug('update dvc preferences') switch_to_offline_database(self.application.preferences) # handlers def _work_offline_button_fired(self): self.debug('work offline fired') self._work_offline() def traits_view(self): v = View(VGroup(UItem('repositories', editor=TabularEditor(adapter=RepositoryTabularAdapter(), selected='selected_repositories', multi_select=True)), UItem('work_offline_button', enabled_when='selected_repositories')), title='Work Offline', resizable=True, width=500, height=500) return v # ============= EOF =============================================
# encoding: 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 'UserInfo.enable_timeline_posts' db.add_column('canvas_userinfo', 'enable_timeline_posts', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False) def backwards(self, orm): # Deleting field 'UserInfo.enable_timeline_posts' db.delete_column('canvas_userinfo', 'enable_timeline_posts') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '254', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'canvas.apiapp': { 'Meta': {'object_name': 'APIApp'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}) }, 'canvas.apiauthtoken': { 'Meta': {'unique_together': "(('user', 'app'),)", 'object_name': 'APIAuthToken'}, 'app': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.APIApp']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'token': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '40'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'canvas.bestof': { 'Meta': {'object_name': 'BestOf'}, 'category': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'best_of'", 'null': 'True', 'blank': 'True', 'to': "orm['canvas.Category']"}), 'chosen_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'comment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'best_of'", 'to': "orm['canvas.Comment']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}) }, 'canvas.category': { 'Meta': {'object_name': 'Category'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '140'}), 'founded': ('django.db.models.fields.FloatField', [], {'default': '1298956320'}), 'founder': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'founded_groups'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'moderators': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'moderated_categories'", 'symmetrical': 'False', 'to': "orm['auth.User']"}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20'}), 'visibility': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'canvas.comment': { 'Meta': {'object_name': 'Comment'}, 'anonymous': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'author': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'comments'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}), 'category': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'comments'", 'null': 'True', 'blank': 'True', 'to': "orm['canvas.Category']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ip': ('django.db.models.fields.IPAddressField', [], {'default': "'0.0.0.0'", 'max_length': '15'}), 'judged': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'ot_hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'parent_comment': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'replies'", 'null': 'True', 'blank': 'True', 'to': "orm['canvas.Comment']"}), 'parent_content': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'comments'", 'null': 'True', 'to': "orm['canvas.Content']"}), 'replied_comment': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['canvas.Comment']", 'null': 'True', 'blank': 'True'}), 'reply_content': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'used_in_comments'", 'null': 'True', 'to': "orm['canvas.Content']"}), 'reply_text': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'blank': 'True'}), 'score': ('django.db.models.fields.FloatField', [], {'default': '0', 'db_index': 'True'}), 'timestamp': ('canvas.util.UnixTimestampField', [], {'default': '0'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '140', 'blank': 'True'}), 'visibility': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'canvas.commentflag': { 'Meta': {'object_name': 'CommentFlag'}, 'comment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'flags'", 'to': "orm['canvas.Comment']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ip': ('django.db.models.fields.IPAddressField', [], {'max_length': '15'}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}), 'type_id': ('django.db.models.fields.IntegerField', [], {}), 'undone': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'flags'", 'to': "orm['auth.User']"}) }, 'canvas.commentmoderationlog': { 'Meta': {'object_name': 'CommentModerationLog'}, 'comment': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.Comment']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'moderator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}), 'note': ('django.db.models.fields.TextField', [], {}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'moderated_comments_log'", 'to': "orm['auth.User']"}), 'visibility': ('django.db.models.fields.IntegerField', [], {}) }, 'canvas.commentpin': { 'Meta': {'object_name': 'CommentPin'}, 'auto': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'comment': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.Comment']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'canvas.commentsticker': { 'Meta': {'object_name': 'CommentSticker'}, 'comment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'stickers'", 'to': "orm['canvas.Comment']"}), 'epic_message': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '140', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ip': ('django.db.models.fields.IPAddressField', [], {'max_length': '15'}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}), 'type_id': ('django.db.models.fields.IntegerField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}) }, 'canvas.content': { 'Meta': {'object_name': 'Content'}, 'alpha': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'animated': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.CharField', [], {'max_length': '40', 'primary_key': 'True'}), 'ip': ('django.db.models.fields.IPAddressField', [], {'default': "'0.0.0.0'", 'max_length': '15'}), 'remix_of': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'remixes'", 'null': 'True', 'to': "orm['canvas.Content']"}), 'remix_text': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1000', 'blank': 'True'}), 'source_url': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '4000', 'blank': 'True'}), 'stamps_used': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'used_as_stamp'", 'blank': 'True', 'to': "orm['canvas.Content']"}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}), 'url_mapping': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.ContentUrlMapping']", 'null': 'True', 'blank': 'True'}), 'visibility': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'canvas.contenturlmapping': { 'Meta': {'object_name': 'ContentUrlMapping'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'canvas.emailunsubscribe': { 'Meta': {'object_name': 'EmailUnsubscribe'}, 'email': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'canvas.externalcontent': { 'Meta': {'object_name': 'ExternalContent'}, '_data': ('django.db.models.fields.TextField', [], {'default': "'{}'"}), 'content_type': ('django.db.models.fields.CharField', [], {'max_length': '2'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'parent_comment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'external_content'", 'to': "orm['canvas.Comment']"}), 'source_url': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '4000', 'null': 'True', 'blank': 'True'}) }, 'canvas.facebookinvite': { 'Meta': {'object_name': 'FacebookInvite'}, 'fb_message_id': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'invited_fbid': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'invitee': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'facebook_invited_from'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}), 'inviter': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'facebook_sent_invites'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}) }, 'canvas.facebookuser': { 'Meta': {'object_name': 'FacebookUser'}, 'email': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'fb_uid': ('django.db.models.fields.BigIntegerField', [], {'unique': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'gender': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_invited': ('canvas.util.UnixTimestampField', [], {'default': '0'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'null': 'True', 'blank': 'True'}) }, 'canvas.followcategory': { 'Meta': {'unique_together': "(('user', 'category'),)", 'object_name': 'FollowCategory'}, 'category': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'followers'", 'to': "orm['canvas.Category']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'following'", 'to': "orm['auth.User']"}) }, 'canvas.invitecode': { 'Meta': {'object_name': 'InviteCode'}, 'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'invitee': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'invited_from'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}), 'inviter': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'sent_invites'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}) }, 'canvas.remixplugin': { 'Meta': {'object_name': 'RemixPlugin'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 's3md5': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'timestamp': ('canvas.util.UnixTimestampField', [], {'default': '0'}) }, 'canvas.stashcontent': { 'Meta': {'object_name': 'StashContent'}, 'content': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.Content']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'canvas.userinfo': { 'Meta': {'object_name': 'UserInfo'}, 'bio_text': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'blank': 'True'}), 'enable_timeline': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'enable_timeline_posts': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'facebook_id': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'free_invites': ('django.db.models.fields.IntegerField', [], {'default': '10'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'invite_bypass': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}), 'is_qa': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'post_anonymously': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'profile_image': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.Comment']", 'null': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'canvas.usermoderationlog': { 'Meta': {'object_name': 'UserModerationLog'}, 'action': ('django.db.models.fields.IntegerField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'moderator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}), 'note': ('django.db.models.fields.TextField', [], {}), 'timestamp': ('canvas.util.UnixTimestampField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'moderation_log'", 'to': "orm['auth.User']"}) }, 'canvas.userwarning': { 'Meta': {'object_name': 'UserWarning'}, 'comment': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['canvas.Comment']", 'null': 'True', 'blank': 'True'}), 'confirmed': ('canvas.util.UnixTimestampField', [], {'default': '0'}), 'custom_message': ('django.db.models.fields.TextField', [], {}), 'disable_user': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'issued': ('canvas.util.UnixTimestampField', [], {}), 'stock_message': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user_warnings'", 'to': "orm['auth.User']"}), 'viewed': ('canvas.util.UnixTimestampField', [], {'default': '0'}) }, 'canvas.welcomeemailrecipient': { 'Meta': {'object_name': 'WelcomeEmailRecipient'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'recipient': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'canvas_auth.user': { 'Meta': {'object_name': 'User', 'db_table': "'auth_user'", '_ormbases': ['auth.User'], 'proxy': 'True'} }, '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'}) } } complete_apps = ['canvas']
# 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 json import logging from django.utils.translation import ugettext_lazy as _ from django.views.decorators.debug import sensitive_variables # noqa from oslo_utils import strutils import six from horizon import exceptions from horizon import forms from horizon import messages from openstack_dashboard import api LOG = logging.getLogger(__name__) def create_upload_form_attributes(prefix, input_type, name): """Creates attribute dicts for the switchable upload form :type prefix: str :param prefix: prefix (environment, template) of field :type input_type: str :param input_type: field type (file, raw, url) :type name: str :param name: translated text label to display to user :rtype: dict :return: an attribute set to pass to form build """ attributes = {'class': 'switched', 'data-switch-on': prefix + 'source'} attributes['data-' + prefix + 'source-' + input_type] = name return attributes class TemplateForm(forms.SelfHandlingForm): class Meta: name = _('Select Template') help_text = _('Select a template to launch a stack.') # TODO(jomara) - update URL choice for template & environment files # w/ client side download when applicable base_choices = [('file', _('File')), ('raw', _('Direct Input'))] url_choice = [('url', _('URL'))] attributes = {'class': 'switchable', 'data-slug': 'templatesource'} template_source = forms.ChoiceField(label=_('Template Source'), choices=base_choices + url_choice, widget=forms.Select(attrs=attributes)) attributes = create_upload_form_attributes( 'template', 'file', _('Template File')) template_upload = forms.FileField( label=_('Template File'), help_text=_('A local template to upload.'), widget=forms.FileInput(attrs=attributes), required=False) attributes = create_upload_form_attributes( 'template', 'url', _('Template URL')) template_url = forms.URLField( label=_('Template URL'), help_text=_('An external (HTTP) URL to load the template from.'), widget=forms.TextInput(attrs=attributes), required=False) attributes = create_upload_form_attributes( 'template', 'raw', _('Template Data')) template_data = forms.CharField( label=_('Template Data'), help_text=_('The raw contents of the template.'), widget=forms.widgets.Textarea(attrs=attributes), required=False) attributes = {'data-slug': 'envsource', 'class': 'switchable'} environment_source = forms.ChoiceField( label=_('Environment Source'), choices=base_choices, widget=forms.Select(attrs=attributes), required=False) attributes = create_upload_form_attributes( 'env', 'file', _('Environment File')) environment_upload = forms.FileField( label=_('Environment File'), help_text=_('A local environment to upload.'), widget=forms.FileInput(attrs=attributes), required=False) attributes = create_upload_form_attributes( 'env', 'raw', _('Environment Data')) environment_data = forms.CharField( label=_('Environment Data'), help_text=_('The raw contents of the environment file.'), widget=forms.widgets.Textarea(attrs=attributes), required=False) def __init__(self, *args, **kwargs): self.next_view = kwargs.pop('next_view') super(TemplateForm, self).__init__(*args, **kwargs) def clean(self): cleaned = super(TemplateForm, self).clean() files = self.request.FILES self.clean_uploaded_files('template', _('template'), cleaned, files) self.clean_uploaded_files('environment', _('environment'), cleaned, files) # Validate the template and get back the params. kwargs = {} if cleaned['template_data']: kwargs['template'] = cleaned['template_data'] else: kwargs['template_url'] = cleaned['template_url'] if cleaned['environment_data']: kwargs['environment'] = cleaned['environment_data'] try: validated = api.heat.template_validate(self.request, **kwargs) cleaned['template_validate'] = validated except Exception as e: raise forms.ValidationError(unicode(e)) return cleaned def clean_uploaded_files(self, prefix, field_label, cleaned, files): """Cleans Template & Environment data from form upload. Does some of the crunchy bits for processing uploads vs raw data depending on what the user specified. Identical process for environment data & template data. :type prefix: str :param prefix: prefix (environment, template) of field :type field_label: str :param field_label: translated prefix str for messages :type input_type: dict :param prefix: existing cleaned fields from form :rtype: dict :return: cleaned dict including environment & template data """ upload_str = prefix + "_upload" data_str = prefix + "_data" url = cleaned.get(prefix + '_url') data = cleaned.get(prefix + '_data') has_upload = upload_str in files # Uploaded file handler if has_upload and not url: log_template_name = files[upload_str].name LOG.info('got upload %s' % log_template_name) tpl = files[upload_str].read() if tpl.startswith('{'): try: json.loads(tpl) except Exception as e: msg = _('There was a problem parsing the' ' %(prefix)s: %(error)s') msg = msg % {'prefix': prefix, 'error': e} raise forms.ValidationError(msg) cleaned[data_str] = tpl # URL handler elif url and (has_upload or data): msg = _('Please specify a %s using only one source method.') msg = msg % field_label raise forms.ValidationError(msg) elif prefix == 'template': # Check for raw template input - blank environment allowed if not url and not data: msg = _('You must specify a template via one of the ' 'available sources.') raise forms.ValidationError(msg) def create_kwargs(self, data): kwargs = {'parameters': data['template_validate'], 'environment_data': data['environment_data'], 'template_data': data['template_data'], 'template_url': data['template_url']} if data.get('stack_id'): kwargs['stack_id'] = data['stack_id'] return kwargs def handle(self, request, data): kwargs = self.create_kwargs(data) # NOTE (gabriel): This is a bit of a hack, essentially rewriting this # request so that we can chain it as an input to the next view... # but hey, it totally works. request.method = 'GET' return self.next_view.as_view()(request, **kwargs) class ChangeTemplateForm(TemplateForm): class Meta: name = _('Edit Template') help_text = _('Select a new template to re-launch a stack.') stack_id = forms.CharField( label=_('Stack ID'), widget=forms.widgets.HiddenInput) stack_name = forms.CharField( label=_('Stack Name'), widget=forms.TextInput(attrs={'readonly': 'readonly'})) class CreateStackForm(forms.SelfHandlingForm): param_prefix = '__param_' class Meta: name = _('Create Stack') template_data = forms.CharField( widget=forms.widgets.HiddenInput, required=False) template_url = forms.CharField( widget=forms.widgets.HiddenInput, required=False) environment_data = forms.CharField( widget=forms.widgets.HiddenInput, required=False) parameters = forms.CharField( widget=forms.widgets.HiddenInput) stack_name = forms.RegexField( max_length=255, label=_('Stack Name'), help_text=_('Name of the stack to create.'), regex=r"^[a-zA-Z][a-zA-Z0-9_.-]*$", error_messages={'invalid': _('Name must start with a letter and may ' 'only contain letters, numbers, underscores, ' 'periods and hyphens.')}) timeout_mins = forms.IntegerField( initial=60, label=_('Creation Timeout (minutes)'), help_text=_('Stack creation timeout in minutes.')) enable_rollback = forms.BooleanField( label=_('Rollback On Failure'), help_text=_('Enable rollback on create/update failure.'), required=False) def __init__(self, *args, **kwargs): parameters = kwargs.pop('parameters') # special case: load template data from API, not passed in params if(kwargs.get('validate_me')): parameters = kwargs.pop('validate_me') super(CreateStackForm, self).__init__(*args, **kwargs) self._build_parameter_fields(parameters) def _build_parameter_fields(self, template_validate): self.fields['password'] = forms.CharField( label=_('Password for user "%s"') % self.request.user.username, help_text=_('This is required for operations to be performed ' 'throughout the lifecycle of the stack'), widget=forms.PasswordInput()) self.help_text = template_validate['Description'] params = template_validate.get('Parameters', {}) if template_validate.get('ParameterGroups'): params_in_order = [] for group in template_validate['ParameterGroups']: for param in group.get('parameters', []): if param in params: params_in_order.append((param, params[param])) else: # no parameter groups, so no way to determine order params_in_order = params.items() for param_key, param in params_in_order: field = None field_key = self.param_prefix + param_key field_args = { 'initial': param.get('Default', None), 'label': param.get('Label', param_key), 'help_text': param.get('Description', ''), 'required': param.get('Default', None) is None } param_type = param.get('Type', None) hidden = strutils.bool_from_string(param.get('NoEcho', 'false')) if 'AllowedValues' in param: choices = map(lambda x: (x, x), param['AllowedValues']) field_args['choices'] = choices field = forms.ChoiceField(**field_args) elif param_type in ('CommaDelimitedList', 'String', 'Json'): if 'MinLength' in param: field_args['min_length'] = int(param['MinLength']) field_args['required'] = param.get('MinLength', 0) > 0 if 'MaxLength' in param: field_args['max_length'] = int(param['MaxLength']) if hidden: field_args['widget'] = forms.PasswordInput() field = forms.CharField(**field_args) elif param_type == 'Number': if 'MinValue' in param: field_args['min_value'] = int(param['MinValue']) if 'MaxValue' in param: field_args['max_value'] = int(param['MaxValue']) field = forms.IntegerField(**field_args) # heat-api currently returns the boolean type in lowercase # (see https://bugs.launchpad.net/heat/+bug/1361448) # so for better compatibility both are checked here elif param_type in ('Boolean', 'boolean'): field = forms.BooleanField(**field_args) if field: self.fields[field_key] = field @sensitive_variables('password') def handle(self, request, data): prefix_length = len(self.param_prefix) params_list = [(k[prefix_length:], v) for (k, v) in six.iteritems(data) if k.startswith(self.param_prefix)] fields = { 'stack_name': data.get('stack_name'), 'timeout_mins': data.get('timeout_mins'), 'disable_rollback': not(data.get('enable_rollback')), 'parameters': dict(params_list), 'password': data.get('password') } if data.get('template_data'): fields['template'] = data.get('template_data') else: fields['template_url'] = data.get('template_url') if data.get('environment_data'): fields['environment'] = data.get('environment_data') try: api.heat.stack_create(self.request, **fields) messages.success(request, _("Stack creation started.")) return True except Exception: exceptions.handle(request) class EditStackForm(CreateStackForm): class Meta: name = _('Update Stack Parameters') stack_id = forms.CharField( label=_('Stack ID'), widget=forms.widgets.HiddenInput) stack_name = forms.CharField( label=_('Stack Name'), widget=forms.TextInput(attrs={'readonly': 'readonly'})) @sensitive_variables('password') def handle(self, request, data): prefix_length = len(self.param_prefix) params_list = [(k[prefix_length:], v) for (k, v) in six.iteritems(data) if k.startswith(self.param_prefix)] stack_id = data.get('stack_id') fields = { 'stack_name': data.get('stack_name'), 'timeout_mins': data.get('timeout_mins'), 'disable_rollback': not(data.get('enable_rollback')), 'parameters': dict(params_list), 'password': data.get('password') } # if the user went directly to this form, resubmit the existing # template data. otherwise, submit what they had from the first form if data.get('template_data'): fields['template'] = data.get('template_data') elif data.get('template_url'): fields['template_url'] = data.get('template_url') elif data.get('parameters'): fields['template'] = data.get('parameters') try: api.heat.stack_update(self.request, stack_id=stack_id, **fields) messages.success(request, _("Stack update started.")) return True except Exception: exceptions.handle(request)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2012 OpenStack LLC # Copyright 2012 Canonical Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from keystone import catalog from keystone.catalog import core from keystone.common import sql from keystone.common.sql import migration from keystone import config from keystone import exception CONF = config.CONF class Service(sql.ModelBase, sql.DictBase): __tablename__ = 'service' attributes = ['id', 'type'] id = sql.Column(sql.String(64), primary_key=True) type = sql.Column(sql.String(255)) extra = sql.Column(sql.JsonBlob()) class Endpoint(sql.ModelBase, sql.DictBase): __tablename__ = 'endpoint' attributes = ['id', 'interface', 'region', 'service_id', 'url', 'legacy_endpoint_id'] id = sql.Column(sql.String(64), primary_key=True) legacy_endpoint_id = sql.Column(sql.String(64)) interface = sql.Column(sql.String(8), primary_key=True) region = sql.Column('region', sql.String(255)) service_id = sql.Column(sql.String(64), sql.ForeignKey('service.id'), nullable=False) url = sql.Column(sql.Text()) extra = sql.Column(sql.JsonBlob()) class Catalog(sql.Base, catalog.Driver): def db_sync(self): migration.db_sync() # Services def list_services(self): session = self.get_session() services = session.query(Service).all() return [s.to_dict() for s in list(services)] def _get_service(self, session, service_id): try: return session.query(Service).filter_by(id=service_id).one() except sql.NotFound: raise exception.ServiceNotFound(service_id=service_id) def get_service(self, service_id): session = self.get_session() return self._get_service(session, service_id).to_dict() def delete_service(self, service_id): session = self.get_session() with session.begin(): ref = self._get_service(session, service_id) session.query(Endpoint).filter_by(service_id=service_id).delete() session.delete(ref) session.flush() def create_service(self, service_id, service_ref): session = self.get_session() with session.begin(): service = Service.from_dict(service_ref) session.add(service) session.flush() return service.to_dict() def update_service(self, service_id, service_ref): session = self.get_session() with session.begin(): ref = self._get_service(session, service_id) old_dict = ref.to_dict() old_dict.update(service_ref) new_service = Service.from_dict(old_dict) for attr in Service.attributes: if attr != 'id': setattr(ref, attr, getattr(new_service, attr)) ref.extra = new_service.extra session.flush() return ref.to_dict() # Endpoints def create_endpoint(self, endpoint_id, endpoint_ref): session = self.get_session() self.get_service(endpoint_ref['service_id']) new_endpoint = Endpoint.from_dict(endpoint_ref) with session.begin(): session.add(new_endpoint) session.flush() return new_endpoint.to_dict() def delete_endpoint(self, endpoint_id): session = self.get_session() with session.begin(): if not session.query(Endpoint).filter_by(id=endpoint_id).delete(): raise exception.EndpointNotFound(endpoint_id=endpoint_id) session.flush() def _get_endpoint(self, session, endpoint_id): try: return session.query(Endpoint).filter_by(id=endpoint_id).one() except sql.NotFound: raise exception.EndpointNotFound(endpoint_id=endpoint_id) def get_endpoint(self, endpoint_id): session = self.get_session() return self._get_endpoint(session, endpoint_id).to_dict() def list_endpoints(self): session = self.get_session() endpoints = session.query(Endpoint) return [e.to_dict() for e in list(endpoints)] def update_endpoint(self, endpoint_id, endpoint_ref): session = self.get_session() with session.begin(): ref = self._get_endpoint(session, endpoint_id) old_dict = ref.to_dict() old_dict.update(endpoint_ref) new_endpoint = Endpoint.from_dict(old_dict) for attr in Endpoint.attributes: if attr != 'id': setattr(ref, attr, getattr(new_endpoint, attr)) ref.extra = new_endpoint.extra session.flush() return ref.to_dict() def get_catalog(self, user_id, tenant_id, metadata=None): d = dict(CONF.iteritems()) d.update({'tenant_id': tenant_id, 'user_id': user_id}) catalog = {} services = {} for endpoint in self.list_endpoints(): # look up the service services.setdefault( endpoint['service_id'], self.get_service(endpoint['service_id'])) service = services[endpoint['service_id']] # add the endpoint to the catalog if it's not already there catalog.setdefault(endpoint['region'], {}) catalog[endpoint['region']].setdefault( service['type'], { 'id': endpoint['id'], 'name': service['name'], 'publicURL': '', # this may be overridden, but must exist }) # add the interface's url url = core.format_url(endpoint.get('url'), d) interface_url = '%sURL' % endpoint['interface'] catalog[endpoint['region']][service['type']][interface_url] = url return catalog def get_v3_catalog(self, user_id, tenant_id, metadata=None): d = dict(CONF.iteritems()) d.update({'tenant_id': tenant_id, 'user_id': user_id}) services = {} for endpoint in self.list_endpoints(): # look up the service service_id = endpoint['service_id'] services.setdefault( service_id, self.get_service(service_id)) service = services[service_id] del endpoint['service_id'] endpoint['url'] = core.format_url(endpoint['url'], d) if 'endpoints' in services[service_id]: services[service_id]['endpoints'].append(endpoint) else: services[service_id]['endpoints'] = [endpoint] catalog = [] for service_id, service in services.iteritems(): formatted_service = {} formatted_service['id'] = service['id'] formatted_service['type'] = service['type'] formatted_service['endpoints'] = service['endpoints'] catalog.append(formatted_service) return catalog
# Copyright 2022 The Magenta 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. """Autoencoder config. All configs should have encode() and decode(). """ from magenta.models.nsynth import utils import tensorflow.compat.v1 as tf config_hparams = dict( num_latent=1984, batch_size=8, mag_only=True, n_fft=1024, fw_loss_coeff=10.0, fw_loss_cutoff=4000,) def encode(x, hparams, is_training=True, reuse=False): """Autoencoder encoder network. Args: x: Tensor. The observed variables. hparams: HParams. Hyperparameters. is_training: bool. Whether batch normalization should be computed in training mode. Defaults to True. reuse: bool. Whether the variable scope should be reused. Defaults to False. Returns: The output of the encoder, i.e. a synthetic z computed from x. """ with tf.variable_scope("encoder", reuse=reuse): h = utils.conv2d( x, [5, 5], [2, 2], 128, is_training, activation_fn=utils.leaky_relu(), batch_norm=True, scope="0") h = utils.conv2d( h, [4, 4], [2, 2], 128, is_training, activation_fn=utils.leaky_relu(), batch_norm=True, scope="1") h = utils.conv2d( h, [4, 4], [2, 2], 128, is_training, activation_fn=utils.leaky_relu(), batch_norm=True, scope="2") h = utils.conv2d( h, [4, 4], [2, 2], 256, is_training, activation_fn=utils.leaky_relu(), batch_norm=True, scope="3") h = utils.conv2d( h, [4, 4], [2, 2], 256, is_training, activation_fn=utils.leaky_relu(), batch_norm=True, scope="4") h = utils.conv2d( h, [4, 4], [2, 2], 256, is_training, activation_fn=utils.leaky_relu(), batch_norm=True, scope="5") h = utils.conv2d( h, [4, 4], [2, 2], 512, is_training, activation_fn=utils.leaky_relu(), batch_norm=True, scope="6") h = utils.conv2d( h, [4, 4], [2, 2], 512, is_training, activation_fn=utils.leaky_relu(), batch_norm=True, scope="7") h = utils.conv2d( h, [4, 4], [2, 1], 512, is_training, activation_fn=utils.leaky_relu(), batch_norm=True, scope="7_1") h = utils.conv2d( h, [1, 1], [1, 1], 1024, is_training, activation_fn=utils.leaky_relu(), batch_norm=True, scope="8") z = utils.conv2d( h, [1, 1], [1, 1], hparams.num_latent, is_training, activation_fn=None, batch_norm=True, scope="z") return z def decode(z, batch, hparams, is_training=True, reuse=False): """Autoencoder decoder network. Args: z: Tensor. The latent variables. batch: NSynthReader batch for pitch information. hparams: HParams. Hyperparameters (unused). is_training: bool. Whether batch normalization should be computed in training mode. Defaults to True. reuse: bool. Whether the variable scope should be reused. Defaults to False. Returns: The output of the decoder, i.e. a synthetic x computed from z. """ del hparams with tf.variable_scope("decoder", reuse=reuse): z_pitch = utils.pitch_embeddings(batch, reuse=reuse) z = tf.concat([z, z_pitch], 3) h = utils.conv2d( z, [1, 1], [1, 1], 1024, is_training, activation_fn=utils.leaky_relu(), transpose=True, batch_norm=True, scope="0") h = utils.conv2d( h, [4, 4], [2, 2], 512, is_training, activation_fn=utils.leaky_relu(), transpose=True, batch_norm=True, scope="1") h = utils.conv2d( h, [4, 4], [2, 2], 512, is_training, activation_fn=utils.leaky_relu(), transpose=True, batch_norm=True, scope="2") h = utils.conv2d( h, [4, 4], [2, 2], 256, is_training, activation_fn=utils.leaky_relu(), transpose=True, batch_norm=True, scope="3") h = utils.conv2d( h, [4, 4], [2, 2], 256, is_training, activation_fn=utils.leaky_relu(), transpose=True, batch_norm=True, scope="4") h = utils.conv2d( h, [4, 4], [2, 2], 256, is_training, activation_fn=utils.leaky_relu(), transpose=True, batch_norm=True, scope="5") h = utils.conv2d( h, [4, 4], [2, 2], 128, is_training, activation_fn=utils.leaky_relu(), transpose=True, batch_norm=True, scope="6") h = utils.conv2d( h, [4, 4], [2, 2], 128, is_training, activation_fn=utils.leaky_relu(), transpose=True, batch_norm=True, scope="7") h = utils.conv2d( h, [5, 5], [2, 2], 128, is_training, activation_fn=utils.leaky_relu(), transpose=True, batch_norm=True, scope="8") h = utils.conv2d( h, [5, 5], [2, 1], 128, is_training, activation_fn=utils.leaky_relu(), transpose=True, batch_norm=True, scope="8_1") xhat = utils.conv2d( h, [1, 1], [1, 1], 1, is_training, activation_fn=tf.nn.sigmoid, batch_norm=False, scope="mag") return xhat
# Copyright (C) 2015-2021 Regents of the University of California # # 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 importlib import os import subprocess import sys import tempfile from contextlib import contextmanager from inspect import getsource from io import BytesIO from textwrap import dedent from zipfile import ZipFile from mock import MagicMock, patch from toil import inVirtualEnv from toil.resource import ModuleDescriptor, Resource, ResourceException from toil.test import ToilTest, travis_test from toil.version import exactPython @contextmanager def tempFileContaining(content, suffix=''): """ Write a file with the given contents, and keep it on disk as long as the context is active. :param str content: The contents of the file. :param str suffix: The extension to use for the temporary file. """ fd, path = tempfile.mkstemp(suffix=suffix) try: encoded = content.encode('utf-8') assert os.write(fd, encoded) == len(encoded) except: os.close(fd) raise else: os.close(fd) yield path finally: os.unlink(path) class ResourceTest(ToilTest): """ Test module descriptors and resources derived from them. """ @travis_test def testStandAlone(self): self._testExternal(moduleName='userScript', pyFiles=('userScript.py', 'helper.py')) @travis_test def testPackage(self): self._testExternal(moduleName='foo.userScript', pyFiles=('foo/__init__.py', 'foo/userScript.py', 'foo/bar/__init__.py', 'foo/bar/helper.py')) @travis_test def testVirtualEnv(self): self._testExternal(moduleName='foo.userScript', virtualenv=True, pyFiles=('foo/__init__.py', 'foo/userScript.py', 'foo/bar/__init__.py', 'foo/bar/helper.py', 'de/pen/dency.py', 'de/__init__.py', 'de/pen/__init__.py')) @travis_test def testStandAloneInPackage(self): self.assertRaises(ResourceException, self._testExternal, moduleName='userScript', pyFiles=('__init__.py', 'userScript.py', 'helper.py')) def _testExternal(self, moduleName, pyFiles, virtualenv=False): dirPath = self._createTempDir() if virtualenv: self.assertTrue(inVirtualEnv()) # --never-download prevents silent upgrades to pip, wheel and setuptools subprocess.check_call(['virtualenv', '--never-download', '--python', exactPython, dirPath]) sitePackages = os.path.join(dirPath, 'lib', exactPython, 'site-packages') # tuple assignment is necessary to make this line immediately precede the try: oldPrefix, sys.prefix, dirPath = sys.prefix, dirPath, sitePackages else: oldPrefix = None try: for relPath in pyFiles: path = os.path.join(dirPath, relPath) os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, 'w') as f: f.write('pass\n') sys.path.append(dirPath) try: userScript = importlib.import_module(moduleName) try: self._test(userScript.__name__, expectedContents=pyFiles, allowExtraContents=True) finally: del userScript while moduleName: del sys.modules[moduleName] self.assertFalse(moduleName in sys.modules) moduleName = '.'.join(moduleName.split('.')[:-1]) finally: sys.path.remove(dirPath) finally: if oldPrefix: sys.prefix = oldPrefix @travis_test def testBuiltIn(self): # Create a ModuleDescriptor for the module containing ModuleDescriptor, i.e. toil.resource module_name = ModuleDescriptor.__module__ self.assertEqual(module_name, 'toil.resource') self._test(module_name, shouldBelongToToil=True) def _test(self, module_name, shouldBelongToToil=False, expectedContents=None, allowExtraContents=True): module = ModuleDescriptor.forModule(module_name) # Assert basic attributes and properties self.assertEqual(module.belongsToToil, shouldBelongToToil) self.assertEqual(module.name, module_name) if shouldBelongToToil: self.assertTrue(module.dirPath.endswith('/src')) # Before the module is saved as a resource, localize() and globalize() are identity # methods. This should log.warnings. self.assertIs(module.localize(), module) self.assertIs(module.globalize(), module) # Create a mock job store ... jobStore = MagicMock() # ... to generate a fake URL for the resource ... url = 'file://foo.zip' jobStore.getSharedPublicUrl.return_value = url # ... and save the resource to it. resource = module.saveAsResourceTo(jobStore) # Ensure that the URL generation method is actually called, ... jobStore.getSharedPublicUrl.assert_called_once_with(sharedFileName=resource.pathHash) # ... and that ensure that writeSharedFileStream is called. jobStore.writeSharedFileStream.assert_called_once_with(sharedFileName=resource.pathHash, isProtected=False) # Now it gets a bit complicated: Ensure that the context manager returned by the # jobStore's writeSharedFileStream() method is entered and that the file handle yielded # by the context manager is written to once with the zipped source tree from which # 'toil.resource' was orginally imported. Keep the zipped tree around such that we can # mock the download later. file_handle = jobStore.writeSharedFileStream.return_value.__enter__.return_value # The first 0 index selects the first call of write(), the second 0 selects positional # instead of keyword arguments, and the third 0 selects the first positional, i.e. the # contents. This is a bit brittle since it assumes that all the data is written in a # single call to write(). If more calls are made we can easily concatenate them. zipFile = file_handle.write.call_args_list[0][0][0] self.assertTrue(zipFile.startswith(b'PK')) # the magic header for ZIP files # Check contents if requested if expectedContents is not None: with ZipFile(BytesIO(zipFile)) as _zipFile: actualContents = set(_zipFile.namelist()) if allowExtraContents: self.assertTrue(actualContents.issuperset(expectedContents)) else: self.assertEqual(actualContents, expectedContents) self.assertEqual(resource.url, url) # Now we're on the worker. Prepare the storage for localized resources Resource.prepareSystem() try: # Register the resource for subsequent lookup. resource.register() # Lookup the resource and ensure that the result is equal to but not the same as the # original resource. Lookup will also be used when we localize the module that was # originally used to create the resource. localResource = Resource.lookup(module._resourcePath) self.assertEqual(resource, localResource) self.assertIsNot(resource, localResource) # Now show that we can localize the module using the registered resource. Set up a mock # urlopen() that yields the zipped tree ... mock_urlopen = MagicMock() mock_urlopen.return_value.read.return_value = zipFile with patch('toil.resource.urlopen', mock_urlopen): # ... and use it to download and unpack the resource localModule = module.localize() # The name should be equal between original and localized resource ... self.assertEqual(module.name, localModule.name) # ... but the directory should be different. self.assertNotEqual(module.dirPath, localModule.dirPath) # Show that we can 'undo' localization. This is necessary when the user script's jobs # are invoked on the worker where they generate more child jobs. self.assertEqual(localModule.globalize(), module) finally: Resource.cleanSystem() @travis_test def testNonPyStandAlone(self): """ Asserts that Toil enforces the user script to have a .py or .pyc extension because that's the only way auto-deployment can re-import the module on a worker. See https://github.com/BD2KGenomics/toil/issues/631 and https://github.com/BD2KGenomics/toil/issues/858 """ def script(): import argparse from toil.common import Toil from toil.job import Job def fn(): pass if __name__ == '__main__': parser = argparse.ArgumentParser() Job.Runner.addToilOptions(parser) options = parser.parse_args() job = Job.wrapFn(fn, memory='10M', cores=0.1, disk='10M') with Toil(options) as toil: toil.start(job) scriptBody = dedent('\n'.join(getsource(script).split('\n')[1:])) shebang = '#! %s\n' % sys.executable with tempFileContaining(shebang + scriptBody) as scriptPath: self.assertFalse(scriptPath.endswith(('.py', '.pyc'))) os.chmod(scriptPath, 0o755) jobStorePath = scriptPath + '.jobStore' process = subprocess.Popen([scriptPath, jobStorePath], stderr=subprocess.PIPE) stdout, stderr = process.communicate() self.assertTrue('The name of a user script/module must end in .py or .pyc.' in stderr.decode('utf-8')) self.assertNotEqual(0, process.returncode) self.assertFalse(os.path.exists(jobStorePath))
import os import pytest from datetime import datetime, timedelta, time from ogn_lib import exceptions, parser, constants def get_messages(n_messages=float('inf')): test_dir = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(test_dir, 'messages.txt'), 'r') as f: lines = f.readlines() messages = [] for i, l in enumerate(lines): if i >= n_messages: break messages.append(l.strip()) return messages class TestParserBase: def test_new_no_id(self): class Callsign(parser.Parser): pass assert 'Callsign' in parser.ParserBase.parsers def test_new_single_id(self): class Callsign(parser.Parser): __destto__ = 'CALL1234' assert 'CALL1234' in parser.ParserBase.parsers def test_new_multi_id(self): class Callsign(parser.Parser): __destto__ = ['CALL234', 'CALL4321'] assert 'CALL234' in parser.ParserBase.parsers assert 'CALL4321' in parser.ParserBase.parsers def test_no_destto(self): old = parser.ParserBase.parsers class Anon(parser.Parser): __destto__ = None assert parser.ParserBase.parsers == old assert 'Anon' not in parser.ParserBase.parsers def test_new_wrong_id(self): with pytest.raises(TypeError): class Callsign(parser.Parser): __destto__ = 12345678 def test_set_default(self): class Callsign(parser.Parser): __default__ = True assert parser.ParserBase.default is Callsign def test_call(self, mocker): class Callsign(parser.Parser): __destto__ = 'CALLSIGN' parse_message = mocker.Mock() msg = ('FLRDD83BC>CALLSIGN,qAS,EDLF:/163148h5124.56N/00634.42E\'' '276/075/A=001551') parser.ParserBase.__call__(msg) Callsign.parse_message.assert_called_once_with(msg) def test_call_server(self, mocker): with mocker.patch('ogn_lib.parser.ServerParser.parse_message'): msg = ('LKHS>APRS,TCPIP*,qAC,GLIDERN2:/211635h4902.45NI01429.51E&' '000/000/A=001689') parser.ParserBase.__call__(msg) parser.ServerParser.parse_message.assert_called_once_with(msg) def test_call_no_parser(self): with pytest.raises(exceptions.ParserNotFoundError): parser.ParserBase.default = None parser.ParserBase.__call__( 'FLRDD83BC>APRS-1,qAS,EDLF:/163148h5124.56N/00634.42E\'' '276/075/A=001551') def test_call_default(self, mocker): class Callsign(parser.Parser): __default__ = True parse_message = mocker.Mock() msg = ('FLRDD83BC>Unknown,qAS,EDLF:/163148h5124.56N/00634.42E\'' '276/075/A=001551') parser.ParserBase.__call__(msg) Callsign.parse_message.assert_called_once_with(msg) def test_call_failed(self, mocker): with mocker.patch('ogn_lib.parser.Parser.parse_message', side_effect=ValueError): with pytest.raises(exceptions.ParseError): parser.ParserBase.__call__('FLR123456>APRS,') class TestParser: messages = get_messages() message = ("FLRDDA5BA>APRS,qAS,LFMX:/165829h4415.41N/00600.03E'342/049/A=" "005524 id0ADDA5BA -454fpm -1.1rot 8.8dB 0e+51.2kHz gps4x5") expected_matches = { 'source': 'FLRDDA5BA', 'destination': 'APRS', 'digipeaters': 'qAS,LFMX', 'time': '165829h', 'latitude': '4415.41N', 'longitude': '00600.03E', 'altitude': '005524', 'speed': '049', 'heading': '342' } def _test_matches_all(self, pattern): for msg in self.messages: match = pattern.search(msg) if not match: raise Exception('Message not matched: {}'.format(msg)) def _test_pattern_field(self, pattern, field): match = pattern.search(self.message) assert match.group(field) == self.expected_matches[field] def test_pattern_header(self): for field in ['source', 'destination', 'digipeaters']: self._test_pattern_field(parser.Parser.PATTERN_HEADER, field) match = parser.Parser.PATTERN_HEADER.match(self.message) assert match.group('data') def test_pattern_header_matches_all(self): self._test_matches_all(parser.Parser.PATTERN_HEADER) def test_pattern_location(self): for field in ['time', 'latitude', 'longitude']: self._test_pattern_field(parser.Parser.PATTERN_LOCATION, field) def test_pattern_location_matches_all(self): self._test_matches_all(parser.Parser.PATTERN_LOCATION) def test_pattern_comment_common(self): for field in ['heading', 'speed', 'altitude']: self._test_pattern_field(parser.Parser.PATTERN_COMMENT_COMON, field) def test_pattern_comment_common_matches_all(self): self._test_matches_all(parser.Parser.PATTERN_COMMENT_COMON) def test_pattern_all(self): for k in self.expected_matches.keys(): self._test_pattern_field(parser.Parser.PATTERN_ALL, k) def test_pattern_all_matches_all(self): self._test_matches_all(parser.Parser.PATTERN_ALL) def test_parse_msg_no_match(self): with pytest.raises(exceptions.ParseError): parser.Parser.parse_message('invalid message') def test_parse_msg_calls(self, mocker): mocker.spy(parser.Parser, '_parse_timestamp') mocker.spy(parser.Parser, '_parse_location') mocker.spy(parser.Parser, '_parse_altitude') mocker.spy(parser.Parser, '_parse_digipeaters') mocker.spy(parser.Parser, '_parse_heading_speed') mocker.spy(parser.Parser, '_parse_protocol_specific') mocker.spy(parser.Parser, '_preprocess_message') msg = ('FLRDD83BC>APRS,qAS,EDLF:/163148h5124.56N/00634.42E\'' '276/075/A=001551') parser.Parser.parse_message(msg) parser.Parser._preprocess_message.assert_called_once_with(msg) parser.Parser._parse_timestamp.assert_called_once_with('163148h') assert parser.Parser._parse_location.call_count == 2 parser.Parser._parse_altitude.assert_called_once_with('001551') parser.Parser._parse_digipeaters.assert_called_once_with('qAS,EDLF') parser.Parser._parse_heading_speed.assert_called_once_with('276', '075') parser.Parser._parse_protocol_specific.assert_not_called() def test_parse_msg(self, mocker): data = parser.Parser.parse_message( 'FLRDD83BC>APRS,qAS,EDLF:/163148h5124.56N/00634.42E\'' '276/075/A=001551') assert data['from'] == 'FLRDD83BC' assert data['destto'] == 'APRS' def test_parse_msg_full(self, mocker): msg = ('NAV07220E>OGNAVI,qAS,NAVITER:/125447h4557.77N/01220.19E\'258/' '056/A=006562 !W76! id1C4007220E +180fpm +0.0rot') mocker.spy(parser.Parser, '_parse_protocol_specific') data = parser.Parser.parse_message(msg) parser.Parser._parse_protocol_specific.assert_called_once_with( '!W76! id1C4007220E +180fpm +0.0rot') assert data['raw'] == msg def test_parse_msg_delete_update(self, mocker): msg = ('NAV07220E>OGNAVI,qAS,NAVITER:/125447h4557.77N/01220.19E\'258/' '056/A=006562 !W76! id1C4007220E +180fpm +0.0rot') data = {'_update': [{'target': 'key', 'function': lambda x: x}]} mocker.patch('ogn_lib.parser.Parser._parse_protocol_specific', return_value=data) mocker.patch('ogn_lib.parser.Parser._update_data') parser.Parser.parse_message(msg) assert parser.Parser._update_data.call_count == 1 def test_parse_msg_comment(self, mocker): mocker.patch('ogn_lib.parser.Parser._parse_protocol_specific', return_value={'comment': True}) data = parser.Parser.parse_message( 'FLRDD83BC>APRS,qAS,EDLF:/163148h5124.56N/00634.42E\'' '276/075/A=001551 [comment]') parser.Parser._parse_protocol_specific.assert_called_once_with('[comment]') assert data['comment'] def test_preprocess_message(self): msg = 'asdf' assert parser.Parser._preprocess_message(msg) == msg def test_parse_digipeaters(self): data = parser.Parser._parse_digipeaters('qAS,RECEIVER') assert data == { 'relayer': None, 'receiver': 'RECEIVER' } def test_parse_digipeaters_relayed(self): data = parser.Parser._parse_digipeaters('RELAYER*,qAS,RECEIVER') assert data == { 'relayer': 'RELAYER', 'receiver': 'RECEIVER' } def test_parse_digipeaters_unknown_format(self): with pytest.raises(ValueError): parser.Parser._parse_digipeaters('qAS') def test_parse_heading_speed(self): data = parser.Parser._parse_heading_speed('100', '050') assert data['heading'] == 100 assert abs(data['ground_speed'] - 25.72) < 0.1 def test_parse_heading_speed_both_missing(self): data = parser.Parser._parse_heading_speed('000', '000') assert data['heading'] is None assert data['ground_speed'] is None def test_parse_heading_speed_null_input(self): assert not parser.Parser._parse_heading_speed(None, '000') assert not parser.Parser._parse_heading_speed('000', None) assert not parser.Parser._parse_heading_speed(None, None) def test_parse_altitude(self): assert abs(parser.Parser._parse_altitude('005000') - 1524) < 1 def test_parse_altitude_missing(self): assert parser.Parser._parse_altitude(None) is None def test_parse_attrs(self): pass def test_parse_timestamp_h(self, mocker): with mocker.patch('ogn_lib.parser.Parser._parse_time'): parser.Parser._parse_timestamp('010203h') parser.Parser._parse_time.assert_called_once_with('010203') def test_parse_timestamp_z(self, mocker): with mocker.patch('ogn_lib.parser.Parser._parse_datetime'): parser.Parser._parse_timestamp('010203z') parser.Parser._parse_datetime.assert_called_once_with('010203') def test_parse_time_past(self): for i in range(24): now = datetime.utcnow() other = now - timedelta(hours=i) parsed = parser.Parser._parse_time(other.strftime('%H%M%S')) delta = (now - parsed).total_seconds() assert 0 <= delta <= 86400 def test_parse_time_future(self): for i in range(5): now = datetime.utcnow() other = now + timedelta(minutes=i) parsed = parser.Parser._parse_time(other.strftime('%H%M%S')) delta = (parsed - now).total_seconds() assert (i - 1) * 60 <= delta <= i * 60 def test_parse_datetime(self): now = datetime.utcnow() parsed = parser.Parser._parse_datetime(now.strftime('%d%H%M')) assert (parsed - now).total_seconds() < 60 def test_parse_location_sign(self): assert parser.Parser._parse_location('0100.00N') >= 0 assert parser.Parser._parse_location('00100.00E') >= 0 assert parser.Parser._parse_location('0100.00S') < 0 assert parser.Parser._parse_location('00100.00W') < 0 def test_parse_location_value(self): val = parser.Parser._parse_location('0130.50N') assert abs(val - 1.5083333) < 0.0001 val = parser.Parser._parse_location('01125.01W') assert abs(val - -11.416833) < 0.0001 def test_parse_protocol_specific(self): assert parser.Parser._parse_protocol_specific("1 2 3 4") == {} def test_conv_fpm_to_ms(self): assert abs(parser.Parser._convert_fpm_to_ms('+123fpm') - 0.624) < 0.01 assert abs(abs(parser.Parser._convert_fpm_to_ms('-123fpm')) - 0.624) < 0.01 def test_conv_fpm_to_ms_sign(self): assert parser.Parser._convert_fpm_to_ms('+123fpm') > 0 assert parser.Parser._convert_fpm_to_ms('-123fpm') < 0 def test_get_location_update_func(self): fn = parser.Parser._get_location_update_func(0) assert 1 == fn(1) def test_update_location_decimal_same(self): existing = 1 new = parser.Parser._update_location_decimal(existing, 0) assert new == existing def test_update_location_decimal_positive(self): existing = 1 new = parser.Parser._update_location_decimal(existing, 3) assert new > existing def test_update_location_decimal_negative(self): existing = -1 new = parser.Parser._update_location_decimal(existing, 3) assert new < existing def test_call(self, mocker): msg = 'FLR123456>APRS,reminder_of_message' with mocker.patch('ogn_lib.parser.APRS.parse_message'): parser.Parser(msg) parser.APRS.parse_message.assert_called_once_with(msg) def test_update_data(self): updates = [ {'target': 'key1', 'function': lambda x: 0}, {'target': 'key2', 'function': lambda x: x - 1} ] data = { 'key1': 1, 'key2': 2 } assert parser.Parser._update_data(data, updates) == { 'key1': 0, 'key2': 1 } def test_update_data_missing(self): # following should pass: parser.Parser._update_data({}, [{'target': 'key', 'function': lambda x: x}]) class TestAPRS: def test_parse_protocol_specific(self): msg = ('!W12! id06DF0A52 +020fpm +0.0rot FL000.00 55.2dB 0e -6.2kHz' ' gps4x6 s6.01 h03 rDDACC4 +5.0dBm hearD7EA hearDA95') data = parser.APRS._parse_protocol_specific(msg) assert len(data['_update']) == 2 assert (set(map(lambda x: x['target'], data['_update'])) == {'latitude', 'longitude'}) del data['_update'] assert abs(data['vertical_speed'] - 0.1016) < 0.01 del data['vertical_speed'] assert data == { 'address_type': constants.AddressType.flarm, 'aircraft_type': constants.AirplaneType.glider, 'do_not_track': False, 'error_count': 0, 'flarm_hardware': 3, 'flarm_id': 'DDACC4', 'flarm_software': '6.01', 'flight_level': 0.0, 'frequency_offset': -6.2, 'gps_quality': {'horizontal': 4, 'vertical': 6}, 'other_devices': ['D7EA', 'DA95'], 'power_ratio': 5.0, 'signal_to_noise_ratio': 55.2, 'stealth': False, 'turn_rate': 0.0, 'uid': '06DF0A52', } def test_parse_id_string(self): uid = '06DF0A52' data = parser.APRS._parse_id_string(uid) assert data['uid'] == uid assert not data['stealth'] assert not data['do_not_track'] assert data['aircraft_type'] is constants.AirplaneType.glider assert data['address_type'] is constants.AddressType.flarm def test_registered(self, mocker): mocker.spy(parser.APRS, '_parse_protocol_specific') parser.Parser("FLRDDA5BA>APRS,qAS,LFMX:/165829h4415.41N/00600.03E'342/" "049/A=005524 id0ADDA5BA -454fpm -1.1rot 8.8dB 0e " "+51.2kHz gps4x5") parser.APRS._parse_protocol_specific.assert_called_once_with( 'id0ADDA5BA -454fpm -1.1rot 8.8dB 0e +51.2kHz gps4x5') class TestNaviter: def test_parse_protocol_specific(self): msg = '!W76! id1C4007220E +180fpm +0.0rot' data = parser.Naviter._parse_protocol_specific(msg) assert len(data['_update']) == 2 assert (set(map(lambda x: x['target'], data['_update'])) == {'latitude', 'longitude'}) del data['_update'] assert abs(data['vertical_speed'] - 0.9144) < 0.01 del data['vertical_speed'] assert data == { 'address_type': constants.AddressType.naviter, 'aircraft_type': constants.AirplaneType.paraglider, 'do_not_track': False, 'stealth': False, 'turn_rate': 0.0, 'uid': '1C4007220E', } def test_parse_id_string(self): uid = '1C4007220E' data = parser.Naviter._parse_id_string(uid) assert data['uid'] == uid assert not data['stealth'] assert not data['do_not_track'] assert data['aircraft_type'] is constants.AirplaneType.paraglider assert data['address_type'] is constants.AddressType.naviter def test_registered(self, mocker): mocker.spy(parser.Naviter, '_parse_protocol_specific') parser.Parser("NAV04220E>OGNAVI,qAS,NAVITER:/140748h4552.27N/01155.61E" "'090/012/A=006562 !W81! id044004220E +060fpm +1.2rot") parser.Naviter._parse_protocol_specific.assert_called_once_with( '!W81! id044004220E +060fpm +1.2rot') class TestSpot: def test_parse_protocol_specific(self): data = parser.Spot._parse_protocol_specific('id0-2860357 SPOT3 GOOD') assert data['id'] == 'id0-2860357' assert data['model'] == 'SPOT3' assert data['status'] == 'GOOD' def test_parse_protocol_specific_fail(self): with pytest.raises(exceptions.ParseError): parser.Spot._parse_protocol_specific('id0-2860357 SPOT3') def test_registered(self, mocker): mocker.spy(parser.Spot, '_parse_protocol_specific') parser.Parser("ICA3E7540>OGSPOT,qAS,SPOT:/161427h1448.35S/04610.86W'" "000/000/A=008677 id0-2860357 SPOT3 GOOD") parser.Spot._parse_protocol_specific.assert_called_once_with( 'id0-2860357 SPOT3 GOOD') class TestSpider: def test_parse_protocol_specific(self): data = parser.Spider._parse_protocol_specific('id300234010617040 +19dB' ' LWE 3D') assert data['id'] == 'id300234010617040' assert data['signal_strength'] == '+19dB' assert data['spider_id'] == 'LWE' assert data['gps_status'] == '3D' def test_parse_protocol_specific_fail(self): with pytest.raises(exceptions.ParseError): parser.Spider._parse_protocol_specific('id300234010617040 +19dB') def test_registered(self, mocker): mocker.spy(parser.Spider, '_parse_protocol_specific') parser.Parser("FLRDDF944>OGSPID,qAS,SPIDER:/190930h3322.78S/07034.60W'" "000/000/A=002263 id300234010617040 +19dB LWE 3D") parser.Spider._parse_protocol_specific.assert_called_once_with( 'id300234010617040 +19dB LWE 3D') class TestSkylines: def test_parse_protocol_specific(self): data = parser.Skylines._parse_protocol_specific('id2816 +000fpm') assert data['id'] == 'id2816' assert data['vertical_speed'] == 0 data = parser.Skylines._parse_protocol_specific('id2816 +159fpm') assert data['id'] == 'id2816' assert abs(data['vertical_speed'] - 0.807) < 0.1 def test_parse_protocol_specific_fail(self): with pytest.raises(exceptions.ParseError): parser.Skylines._parse_protocol_specific('id1111') def test_registered(self, mocker): mocker.spy(parser.Skylines, '_parse_protocol_specific') parser.Parser("FLRDDDD78>OGSKYL,qAS,SKYLINES:/134403h4225.90N/00144.8" "3E'000/000/A=008438 id2816 +000fpm") parser.Skylines._parse_protocol_specific.assert_called_once_with( 'id2816 +000fpm') class TestLT24: def test_parse_protocol_specific(self): data = parser.LiveTrack24._parse_protocol_specific('id25387 +000fpm GPS') assert data['id'] == 'id25387' assert data['vertical_speed'] == 0 assert data['source'] == 'GPS' data = parser.LiveTrack24._parse_protocol_specific('id25387 +159fpm GPS') assert data['id'] == 'id25387' assert abs(data['vertical_speed'] - 0.807) < 0.1 assert data['source'] == 'GPS' def test_parse_protocol_specific_fail(self): with pytest.raises(exceptions.ParseError): parser.LiveTrack24._parse_protocol_specific('id11111 GPS') def test_registered(self, mocker): mocker.spy(parser.LiveTrack24, '_parse_protocol_specific') parser.Parser("FLRDDE48A>OGLT24,qAS,LT24:/102606h4030.47N/00338.38W'" "000/018/A=002267 id25387 +000fpm GPS") parser.LiveTrack24._parse_protocol_specific.assert_called_once_with( 'id25387 +000fpm GPS') class TestCapturs: def test_process(self): parser.Capturs.parse_message( "FLRDDEEF1>OGCAPT,qAS,CAPTURS:/065144h4837.56N/00233.80E'000/000/") def test_preprocess(self): msg_original = ("FLRDDEEF1>OGCAPT,qAS,CAPTURS:/065144h4837.56N/" "00233.80E'000/000/") msg = parser.Capturs._preprocess_message(msg_original) assert msg == msg_original[:-1] def test_registered(self, mocker): mocker.spy(parser.Capturs, '_preprocess_message') msg = ("FLRDDEEF1>OGCAPT,qAS,CAPTURS:/065144h4837.56N/00233.80E'000/000/") parser.Parser(msg) parser.Capturs._preprocess_message.assert_called_once_with(msg) class TestFanet: def test_parse_protocol_specific(self): data = parser.Fanet._parse_protocol_specific('!W30! id1E1103CE 180fpm') assert data['id'] == 'id1E1103CE' assert abs(data['vertical_speed'] - 0.9144) < 0.01 assert (list(map(lambda x: x['target'], data['_update'])) == ['latitude', 'longitude']) def test_parse_protocol_specific_fail(self): with pytest.raises(exceptions.ParseError): parser.Fanet._parse_protocol_specific('id1E1103CE') with pytest.raises(exceptions.ParseError): parser.Fanet._parse_protocol_specific( '!W30! id1E1103CE -02fpm x') def test_registered(self, mocker): mocker.spy(parser.Fanet, '_parse_protocol_specific') parser.Parser('FNT1103CE>OGNFNT,qAS,FNB1103CE:/183734h5057.94N/' '00801.00Eg354/001/A=001042 !W30! id1E1103CE -10fpm') parser.Fanet._parse_protocol_specific.assert_called_once_with( '!W30! id1E1103CE -10fpm') class TestServerParser: def test_parse_message_beacon(self, mocker): msg = ('LKHS>APRS,TCPIP*,qAC,GLIDERN2:/211635h4902.45NI01429.51E&' '000/000/A=001689') data = parser.ServerParser.parse_message(msg) assert data['from'] == 'LKHS' assert data['destto'] == 'APRS' assert data['timestamp'].time() == time(21, 16, 35) assert data['latitude'] == 49.04083333333333 assert data['longitude'] == 14.491833333333334 assert not data['heading'] assert not data['ground_speed'] assert abs(data['altitude'] - 514.8) < 1 assert data['raw'] == msg assert data['beacon_type'] == constants.BeaconType.server_beacon assert 'comment' not in data def test_parse_message_status(self, mocker): msg = ( 'LKHS>APRS,TCPIP*,qAC,GLIDERN2:/211635h v0.2.6.ARM CPU:0.2 ' 'RAM:777.7/972.2MB NTP:3.1ms/-3.8ppm 4.902V 0.583A +33.6C 14/' '16Acfts[1h] RF:+62-0.8ppm/+33.66dB/+19.4dB@10km[112619]/+25.0' 'dB@10km[8/15]') data = parser.ServerParser.parse_message(msg) assert data['from'] == 'LKHS' assert data['destto'] == 'APRS' assert data['timestamp'].time() == time(21, 16, 35) assert not data['latitude'] assert not data['longitude'] assert 'heading' not in data assert 'ground_speed' not in data assert not data['altitude'] assert data['raw'] == msg assert data['beacon_type'] == constants.BeaconType.server_status assert data['raw'] assert data['comment'].startswith('v0.2.6') def test_parse_beacon_comment(self, mocker): msg = ('LKHS>APRS,TCPIP*,qAC,GLIDERN2:/211635h4902.45NI01429.51E&' '000/000/A=001689 comment') data = parser.ServerParser.parse_message(msg) assert data['comment'] == 'comment'
import base64 import json import logging from . import credentials from . import errors from .utils import config INDEX_NAME = 'docker.io' INDEX_URL = f'https://index.{INDEX_NAME}/v1/' TOKEN_USERNAME = '<token>' log = logging.getLogger(__name__) def resolve_repository_name(repo_name): if '://' in repo_name: raise errors.InvalidRepository( f'Repository name cannot contain a scheme ({repo_name})' ) index_name, remote_name = split_repo_name(repo_name) if index_name[0] == '-' or index_name[-1] == '-': raise errors.InvalidRepository( 'Invalid index name ({}). Cannot begin or end with a' ' hyphen.'.format(index_name) ) return resolve_index_name(index_name), remote_name def resolve_index_name(index_name): index_name = convert_to_hostname(index_name) if index_name == 'index.' + INDEX_NAME: index_name = INDEX_NAME return index_name def get_config_header(client, registry): log.debug('Looking for auth config') if not client._auth_configs or client._auth_configs.is_empty: log.debug( "No auth config in memory - loading from filesystem" ) client._auth_configs = load_config(credstore_env=client.credstore_env) authcfg = resolve_authconfig( client._auth_configs, registry, credstore_env=client.credstore_env ) # Do not fail here if no authentication exists for this # specific registry as we can have a readonly pull. Just # put the header if we can. if authcfg: log.debug('Found auth config') # auth_config needs to be a dict in the format used by # auth.py username , password, serveraddress, email return encode_header(authcfg) log.debug('No auth config found') return None def split_repo_name(repo_name): parts = repo_name.split('/', 1) if len(parts) == 1 or ( '.' not in parts[0] and ':' not in parts[0] and parts[0] != 'localhost' ): # This is a docker index repo (ex: username/foobar or ubuntu) return INDEX_NAME, repo_name return tuple(parts) def get_credential_store(authconfig, registry): if not isinstance(authconfig, AuthConfig): authconfig = AuthConfig(authconfig) return authconfig.get_credential_store(registry) class AuthConfig(dict): def __init__(self, dct, credstore_env=None): if 'auths' not in dct: dct['auths'] = {} self.update(dct) self._credstore_env = credstore_env self._stores = {} @classmethod def parse_auth(cls, entries, raise_on_error=False): """ Parses authentication entries Args: entries: Dict of authentication entries. raise_on_error: If set to true, an invalid format will raise InvalidConfigFile Returns: Authentication registry. """ conf = {} for registry, entry in entries.items(): if not isinstance(entry, dict): log.debug( 'Config entry for key {} is not auth config'.format( registry ) ) # We sometimes fall back to parsing the whole config as if it # was the auth config by itself, for legacy purposes. In that # case, we fail silently and return an empty conf if any of the # keys is not formatted properly. if raise_on_error: raise errors.InvalidConfigFile( 'Invalid configuration for registry {}'.format( registry ) ) return {} if 'identitytoken' in entry: log.debug( 'Found an IdentityToken entry for registry {}'.format( registry ) ) conf[registry] = { 'IdentityToken': entry['identitytoken'] } continue # Other values are irrelevant if we have a token if 'auth' not in entry: # Starting with engine v1.11 (API 1.23), an empty dictionary is # a valid value in the auths config. # https://github.com/docker/compose/issues/3265 log.debug( 'Auth data for {} is absent. Client might be using a ' 'credentials store instead.'.format(registry) ) conf[registry] = {} continue username, password = decode_auth(entry['auth']) log.debug( 'Found entry (registry={}, username={})' .format(repr(registry), repr(username)) ) conf[registry] = { 'username': username, 'password': password, 'email': entry.get('email'), 'serveraddress': registry, } return conf @classmethod def load_config(cls, config_path, config_dict, credstore_env=None): """ Loads authentication data from a Docker configuration file in the given root directory or if config_path is passed use given path. Lookup priority: explicit config_path parameter > DOCKER_CONFIG environment variable > ~/.docker/config.json > ~/.dockercfg """ if not config_dict: config_file = config.find_config_file(config_path) if not config_file: return cls({}, credstore_env) try: with open(config_file) as f: config_dict = json.load(f) except (OSError, KeyError, ValueError) as e: # Likely missing new Docker config file or it's in an # unknown format, continue to attempt to read old location # and format. log.debug(e) return cls(_load_legacy_config(config_file), credstore_env) res = {} if config_dict.get('auths'): log.debug("Found 'auths' section") res.update({ 'auths': cls.parse_auth( config_dict.pop('auths'), raise_on_error=True ) }) if config_dict.get('credsStore'): log.debug("Found 'credsStore' section") res.update({'credsStore': config_dict.pop('credsStore')}) if config_dict.get('credHelpers'): log.debug("Found 'credHelpers' section") res.update({'credHelpers': config_dict.pop('credHelpers')}) if res: return cls(res, credstore_env) log.debug( "Couldn't find auth-related section ; attempting to interpret " "as auth-only file" ) return cls({'auths': cls.parse_auth(config_dict)}, credstore_env) @property def auths(self): return self.get('auths', {}) @property def creds_store(self): return self.get('credsStore', None) @property def cred_helpers(self): return self.get('credHelpers', {}) @property def is_empty(self): return ( not self.auths and not self.creds_store and not self.cred_helpers ) def resolve_authconfig(self, registry=None): """ Returns the authentication data from the given auth configuration for a specific registry. As with the Docker client, legacy entries in the config with full URLs are stripped down to hostnames before checking for a match. Returns None if no match was found. """ if self.creds_store or self.cred_helpers: store_name = self.get_credential_store(registry) if store_name is not None: log.debug( f'Using credentials store "{store_name}"' ) cfg = self._resolve_authconfig_credstore(registry, store_name) if cfg is not None: return cfg log.debug('No entry in credstore - fetching from auth dict') # Default to the public index server registry = resolve_index_name(registry) if registry else INDEX_NAME log.debug(f"Looking for auth entry for {repr(registry)}") if registry in self.auths: log.debug(f"Found {repr(registry)}") return self.auths[registry] for key, conf in self.auths.items(): if resolve_index_name(key) == registry: log.debug(f"Found {repr(key)}") return conf log.debug("No entry found") return None def _resolve_authconfig_credstore(self, registry, credstore_name): if not registry or registry == INDEX_NAME: # The ecosystem is a little schizophrenic with index.docker.io VS # docker.io - in that case, it seems the full URL is necessary. registry = INDEX_URL log.debug(f"Looking for auth entry for {repr(registry)}") store = self._get_store_instance(credstore_name) try: data = store.get(registry) res = { 'ServerAddress': registry, } if data['Username'] == TOKEN_USERNAME: res['IdentityToken'] = data['Secret'] else: res.update({ 'Username': data['Username'], 'Password': data['Secret'], }) return res except credentials.CredentialsNotFound: log.debug('No entry found') return None except credentials.StoreError as e: raise errors.DockerException( f'Credentials store error: {repr(e)}' ) def _get_store_instance(self, name): if name not in self._stores: self._stores[name] = credentials.Store( name, environment=self._credstore_env ) return self._stores[name] def get_credential_store(self, registry): if not registry or registry == INDEX_NAME: registry = INDEX_URL return self.cred_helpers.get(registry) or self.creds_store def get_all_credentials(self): auth_data = self.auths.copy() if self.creds_store: # Retrieve all credentials from the default store store = self._get_store_instance(self.creds_store) for k in store.list().keys(): auth_data[k] = self._resolve_authconfig_credstore( k, self.creds_store ) auth_data[convert_to_hostname(k)] = auth_data[k] # credHelpers entries take priority over all others for reg, store_name in self.cred_helpers.items(): auth_data[reg] = self._resolve_authconfig_credstore( reg, store_name ) auth_data[convert_to_hostname(reg)] = auth_data[reg] return auth_data def add_auth(self, reg, data): self['auths'][reg] = data def resolve_authconfig(authconfig, registry=None, credstore_env=None): if not isinstance(authconfig, AuthConfig): authconfig = AuthConfig(authconfig, credstore_env) return authconfig.resolve_authconfig(registry) def convert_to_hostname(url): return url.replace('http://', '').replace('https://', '').split('/', 1)[0] def decode_auth(auth): if isinstance(auth, str): auth = auth.encode('ascii') s = base64.b64decode(auth) login, pwd = s.split(b':', 1) return login.decode('utf8'), pwd.decode('utf8') def encode_header(auth): auth_json = json.dumps(auth).encode('ascii') return base64.urlsafe_b64encode(auth_json) def parse_auth(entries, raise_on_error=False): """ Parses authentication entries Args: entries: Dict of authentication entries. raise_on_error: If set to true, an invalid format will raise InvalidConfigFile Returns: Authentication registry. """ return AuthConfig.parse_auth(entries, raise_on_error) def load_config(config_path=None, config_dict=None, credstore_env=None): return AuthConfig.load_config(config_path, config_dict, credstore_env) def _load_legacy_config(config_file): log.debug("Attempting to parse legacy auth file format") try: data = [] with open(config_file) as f: for line in f.readlines(): data.append(line.strip().split(' = ')[1]) if len(data) < 2: # Not enough data raise errors.InvalidConfigFile( 'Invalid or empty configuration file!' ) username, password = decode_auth(data[0]) return {'auths': { INDEX_NAME: { 'username': username, 'password': password, 'email': data[1], 'serveraddress': INDEX_URL, } }} except Exception as e: log.debug(e) pass log.debug("All parsing attempts failed - returning empty config") return {}
#!/usr/bin/env python3 """Edit test cases to use PSA dependencies instead of classic dependencies. """ # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import re import sys CLASSIC_DEPENDENCIES = frozenset([ # This list is manually filtered from mbedtls_config.h. # Mbed TLS feature support. # Only features that affect what can be done are listed here. # Options that control optimizations or alternative implementations # are omitted. 'MBEDTLS_CIPHER_MODE_CBC', 'MBEDTLS_CIPHER_MODE_CFB', 'MBEDTLS_CIPHER_MODE_CTR', 'MBEDTLS_CIPHER_MODE_OFB', 'MBEDTLS_CIPHER_MODE_XTS', 'MBEDTLS_CIPHER_NULL_CIPHER', 'MBEDTLS_CIPHER_PADDING_PKCS7', 'MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS', 'MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN', 'MBEDTLS_CIPHER_PADDING_ZEROS', #curve#'MBEDTLS_ECP_DP_SECP192R1_ENABLED', #curve#'MBEDTLS_ECP_DP_SECP224R1_ENABLED', #curve#'MBEDTLS_ECP_DP_SECP256R1_ENABLED', #curve#'MBEDTLS_ECP_DP_SECP384R1_ENABLED', #curve#'MBEDTLS_ECP_DP_SECP521R1_ENABLED', #curve#'MBEDTLS_ECP_DP_SECP192K1_ENABLED', #curve#'MBEDTLS_ECP_DP_SECP224K1_ENABLED', #curve#'MBEDTLS_ECP_DP_SECP256K1_ENABLED', #curve#'MBEDTLS_ECP_DP_BP256R1_ENABLED', #curve#'MBEDTLS_ECP_DP_BP384R1_ENABLED', #curve#'MBEDTLS_ECP_DP_BP512R1_ENABLED', #curve#'MBEDTLS_ECP_DP_CURVE25519_ENABLED', #curve#'MBEDTLS_ECP_DP_CURVE448_ENABLED', 'MBEDTLS_ECDSA_DETERMINISTIC', #'MBEDTLS_GENPRIME', #needed for RSA key generation 'MBEDTLS_PKCS1_V15', 'MBEDTLS_PKCS1_V21', # Mbed TLS modules. # Only modules that provide cryptographic mechanisms are listed here. # Platform, data formatting, X.509 or TLS modules are omitted. 'MBEDTLS_AES_C', 'MBEDTLS_BIGNUM_C', 'MBEDTLS_CAMELLIA_C', 'MBEDTLS_ARIA_C', 'MBEDTLS_CCM_C', 'MBEDTLS_CHACHA20_C', 'MBEDTLS_CHACHAPOLY_C', 'MBEDTLS_CMAC_C', 'MBEDTLS_CTR_DRBG_C', 'MBEDTLS_DES_C', 'MBEDTLS_DHM_C', 'MBEDTLS_ECDH_C', 'MBEDTLS_ECDSA_C', 'MBEDTLS_ECJPAKE_C', 'MBEDTLS_ECP_C', 'MBEDTLS_ENTROPY_C', 'MBEDTLS_GCM_C', 'MBEDTLS_HKDF_C', 'MBEDTLS_HMAC_DRBG_C', 'MBEDTLS_NIST_KW_C', 'MBEDTLS_MD5_C', 'MBEDTLS_PKCS5_C', 'MBEDTLS_PKCS12_C', 'MBEDTLS_POLY1305_C', 'MBEDTLS_RIPEMD160_C', 'MBEDTLS_RSA_C', 'MBEDTLS_SHA1_C', 'MBEDTLS_SHA256_C', 'MBEDTLS_SHA512_C', ]) def is_classic_dependency(dep): """Whether dep is a classic dependency that PSA test cases should not use.""" if dep.startswith('!'): dep = dep[1:] return dep in CLASSIC_DEPENDENCIES def is_systematic_dependency(dep): """Whether dep is a PSA dependency which is determined systematically.""" if dep.startswith('PSA_WANT_ECC_'): return False return dep.startswith('PSA_WANT_') WITHOUT_SYSTEMATIC_DEPENDENCIES = frozenset([ 'PSA_ALG_AEAD_WITH_SHORTENED_TAG', # only a modifier 'PSA_ALG_ANY_HASH', # only meaningful in policies 'PSA_ALG_KEY_AGREEMENT', # only a way to combine algorithms 'PSA_ALG_TRUNCATED_MAC', # only a modifier 'PSA_KEY_TYPE_NONE', # not a real key type 'PSA_KEY_TYPE_DERIVE', # always supported, don't list it to reduce noise 'PSA_KEY_TYPE_RAW_DATA', # always supported, don't list it to reduce noise 'PSA_ALG_AT_LEAST_THIS_LENGTH_MAC', #only a modifier 'PSA_ALG_AEAD_WITH_AT_LEAST_THIS_LENGTH_TAG', #only a modifier ]) SPECIAL_SYSTEMATIC_DEPENDENCIES = { 'PSA_ALG_ECDSA_ANY': frozenset(['PSA_WANT_ALG_ECDSA']), 'PSA_ALG_RSA_PKCS1V15_SIGN_RAW': frozenset(['PSA_WANT_ALG_RSA_PKCS1V15_SIGN']), } def dependencies_of_symbol(symbol): """Return the dependencies for a symbol that designates a cryptographic mechanism.""" if symbol in WITHOUT_SYSTEMATIC_DEPENDENCIES: return frozenset() if symbol in SPECIAL_SYSTEMATIC_DEPENDENCIES: return SPECIAL_SYSTEMATIC_DEPENDENCIES[symbol] if symbol.startswith('PSA_ALG_CATEGORY_') or \ symbol.startswith('PSA_KEY_TYPE_CATEGORY_'): # Categories are used in test data when an unsupported but plausible # mechanism number needed. They have no associated dependency. return frozenset() return {symbol.replace('_', '_WANT_', 1)} def systematic_dependencies(file_name, function_name, arguments): """List the systematically determined dependency for a test case.""" deps = set() # Run key policy negative tests even if the algorithm to attempt performing # is not supported but in the case where the test is to check an # incompatibility between a requested algorithm for a cryptographic # operation and a key policy. In the latter, we want to filter out the # cases # where PSA_ERROR_NOT_SUPPORTED is returned instead of # PSA_ERROR_NOT_PERMITTED. if function_name.endswith('_key_policy') and \ arguments[-1].startswith('PSA_ERROR_') and \ arguments[-1] != ('PSA_ERROR_NOT_PERMITTED'): arguments[-2] = '' if function_name == 'copy_fail' and \ arguments[-1].startswith('PSA_ERROR_'): arguments[-2] = '' arguments[-3] = '' # Storage format tests that only look at how the file is structured and # don't care about the format of the key material don't depend on any # cryptographic mechanisms. if os.path.basename(file_name) == 'test_suite_psa_crypto_persistent_key.data' and \ function_name in {'format_storage_data_check', 'parse_storage_data_check'}: return [] for arg in arguments: for symbol in re.findall(r'PSA_(?:ALG|KEY_TYPE)_\w+', arg): deps.update(dependencies_of_symbol(symbol)) return sorted(deps) def updated_dependencies(file_name, function_name, arguments, dependencies): """Rework the list of dependencies into PSA_WANT_xxx. Remove classic crypto dependencies such as MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15, etc. Add systematic PSA_WANT_xxx dependencies based on the called function and its arguments, replacing existing PSA_WANT_xxx dependencies. """ automatic = systematic_dependencies(file_name, function_name, arguments) manual = [dep for dep in dependencies if not (is_systematic_dependency(dep) or is_classic_dependency(dep))] return automatic + manual def keep_manual_dependencies(file_name, function_name, arguments): #pylint: disable=unused-argument """Declare test functions with unusual dependencies here.""" # If there are no arguments, we can't do any useful work. Assume that if # there are dependencies, they are warranted. if not arguments: return True # When PSA_ERROR_NOT_SUPPORTED is expected, usually, at least one of the # constants mentioned in the test should not be supported. It isn't # possible to determine which one in a systematic way. So let the programmer # decide. if arguments[-1] == 'PSA_ERROR_NOT_SUPPORTED': return True return False def process_data_stanza(stanza, file_name, test_case_number): """Update PSA crypto dependencies in one Mbed TLS test case. stanza is the test case text (including the description, the dependencies, the line with the function and arguments, and optionally comments). Return a new stanza with an updated dependency line, preserving everything else (description, comments, arguments, etc.). """ if not stanza.lstrip('\n'): # Just blank lines return stanza # Expect 2 or 3 non-comment lines: description, optional dependencies, # function-and-arguments. content_matches = list(re.finditer(r'^[\t ]*([^\t #].*)$', stanza, re.M)) if len(content_matches) < 2: raise Exception('Not enough content lines in paragraph {} in {}' .format(test_case_number, file_name)) if len(content_matches) > 3: raise Exception('Too many content lines in paragraph {} in {}' .format(test_case_number, file_name)) arguments = content_matches[-1].group(0).split(':') function_name = arguments.pop(0) if keep_manual_dependencies(file_name, function_name, arguments): return stanza if len(content_matches) == 2: # Insert a line for the dependencies. If it turns out that there are # no dependencies, we'll remove that empty line below. dependencies_location = content_matches[-1].start() text_before = stanza[:dependencies_location] text_after = '\n' + stanza[dependencies_location:] old_dependencies = [] dependencies_leader = 'depends_on:' else: dependencies_match = content_matches[-2] text_before = stanza[:dependencies_match.start()] text_after = stanza[dependencies_match.end():] old_dependencies = dependencies_match.group(0).split(':') dependencies_leader = old_dependencies.pop(0) + ':' if dependencies_leader != 'depends_on:': raise Exception('Next-to-last line does not start with "depends_on:"' ' in paragraph {} in {}' .format(test_case_number, file_name)) new_dependencies = updated_dependencies(file_name, function_name, arguments, old_dependencies) if new_dependencies: stanza = (text_before + dependencies_leader + ':'.join(new_dependencies) + text_after) else: # The dependencies have become empty. Remove the depends_on: line. assert text_after[0] == '\n' stanza = text_before + text_after[1:] return stanza def process_data_file(file_name, old_content): """Update PSA crypto dependencies in an Mbed TLS test suite data file. Process old_content (the old content of the file) and return the new content. """ old_stanzas = old_content.split('\n\n') new_stanzas = [process_data_stanza(stanza, file_name, n) for n, stanza in enumerate(old_stanzas, start=1)] return '\n\n'.join(new_stanzas) def update_file(file_name, old_content, new_content): """Update the given file with the given new content. Replace the existing file. The previous version is renamed to *.bak. Don't modify the file if the content was unchanged. """ if new_content == old_content: return backup = file_name + '.bak' tmp = file_name + '.tmp' with open(tmp, 'w', encoding='utf-8') as new_file: new_file.write(new_content) os.replace(file_name, backup) os.replace(tmp, file_name) def process_file(file_name): """Update PSA crypto dependencies in an Mbed TLS test suite data file. Replace the existing file. The previous version is renamed to *.bak. Don't modify the file if the content was unchanged. """ old_content = open(file_name, encoding='utf-8').read() if file_name.endswith('.data'): new_content = process_data_file(file_name, old_content) else: raise Exception('File type not recognized: {}' .format(file_name)) update_file(file_name, old_content, new_content) def main(args): for file_name in args: process_file(file_name) if __name__ == '__main__': main(sys.argv[1:])
#!/usr/bin/env python # Copyright (c) 2012 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. """Utility for checking and processing licensing information in third_party directories. Usage: licenses.py <command> Commands: scan scan third_party directories, verifying that we have licensing info credits generate about:credits on stdout (You can also import this as a module.) """ import cgi import os import sys # Paths from the root of the tree to directories to skip. PRUNE_PATHS = set([ # Same module occurs in crypto/third_party/nss and net/third_party/nss, so # skip this one. os.path.join('third_party','nss'), # Placeholder directory only, not third-party code. os.path.join('third_party','adobe'), # Build files only, not third-party code. os.path.join('third_party','widevine'), # Only binaries, used during development. os.path.join('third_party','valgrind'), # Used for development and test, not in the shipping product. os.path.join('third_party','bison'), os.path.join('third_party','cygwin'), os.path.join('third_party','gnu_binutils'), os.path.join('third_party','gold'), os.path.join('third_party','gperf'), os.path.join('third_party','lighttpd'), os.path.join('third_party','llvm'), os.path.join('third_party','llvm-build'), os.path.join('third_party','mingw-w64'), os.path.join('third_party','nacl_sdk_binaries'), os.path.join('third_party','pefile'), os.path.join('third_party','perl'), os.path.join('third_party','psyco_win32'), os.path.join('third_party','pylib'), os.path.join('third_party','python_26'), os.path.join('third_party','pywebsocket'), os.path.join('third_party','syzygy'), # Chromium code in third_party. os.path.join('third_party','fuzzymatch'), # Stuff pulled in from chrome-internal for official builds/tools. os.path.join('third_party', 'clear_cache'), os.path.join('third_party', 'gnu'), os.path.join('third_party', 'googlemac'), os.path.join('third_party', 'pcre'), os.path.join('third_party', 'psutils'), os.path.join('third_party', 'sawbuck'), # Redistribution does not require attribution in documentation. os.path.join('third_party','directxsdk'), os.path.join('third_party','platformsdk_win2008_6_1'), os.path.join('third_party','platformsdk_win7'), ]) # Directories we don't scan through. PRUNE_DIRS = ('.svn', '.git', # VCS metadata 'out', 'Debug', 'Release', # build files 'layout_tests') # lots of subdirs ADDITIONAL_PATHS = ( os.path.join('breakpad'), os.path.join('chrome', 'common', 'extensions', 'docs', 'examples'), os.path.join('chrome', 'test', 'chromeos', 'autotest'), os.path.join('chrome', 'test', 'data'), os.path.join('googleurl'), os.path.join('native_client'), os.path.join('native_client_sdk'), os.path.join('net', 'tools', 'spdyshark'), os.path.join('ppapi'), os.path.join('sandbox', 'linux', 'seccomp-legacy'), os.path.join('sdch', 'open-vcdiff'), os.path.join('testing', 'gmock'), os.path.join('testing', 'gtest'), # The directory with the word list for Chinese and Japanese segmentation # with different license terms than ICU. os.path.join('third_party','icu','source','data','brkitr'), os.path.join('tools', 'grit'), os.path.join('tools', 'gyp'), os.path.join('tools', 'page_cycler', 'acid3'), os.path.join('v8'), # Fake directory so we can include the strongtalk license. os.path.join('v8', 'strongtalk'), ) # Directories where we check out directly from upstream, and therefore # can't provide a README.chromium. Please prefer a README.chromium # wherever possible. SPECIAL_CASES = { os.path.join('googleurl'): { "Name": "google-url", "URL": "http://code.google.com/p/google-url/", "License": "BSD and MPL 1.1/GPL 2.0/LGPL 2.1", "License File": "LICENSE.txt", }, os.path.join('native_client'): { "Name": "native client", "URL": "http://code.google.com/p/nativeclient", "License": "BSD", }, os.path.join('sandbox', 'linux', 'seccomp-legacy'): { "Name": "seccompsandbox", "URL": "http://code.google.com/p/seccompsandbox", "License": "BSD", }, os.path.join('sdch', 'open-vcdiff'): { "Name": "open-vcdiff", "URL": "http://code.google.com/p/open-vcdiff", "License": "Apache 2.0, MIT, GPL v2 and custom licenses", "License Android Compatible": "yes", }, os.path.join('testing', 'gmock'): { "Name": "gmock", "URL": "http://code.google.com/p/googlemock", "License": "BSD", "License File": "NOT_SHIPPED", }, os.path.join('testing', 'gtest'): { "Name": "gtest", "URL": "http://code.google.com/p/googletest", "License": "BSD", "License File": "NOT_SHIPPED", }, os.path.join('third_party', 'angle'): { "Name": "Almost Native Graphics Layer Engine", "URL": "http://code.google.com/p/angleproject/", "License": "BSD", }, os.path.join('third_party', 'cros_system_api'): { "Name": "Chromium OS system API", "URL": "http://www.chromium.org/chromium-os", "License": "BSD", # Absolute path here is resolved as relative to the source root. "License File": "/LICENSE.chromium_os", }, os.path.join('third_party', 'GTM'): { "Name": "Google Toolbox for Mac", "URL": "http://code.google.com/p/google-toolbox-for-mac/", "License": "Apache 2.0", "License File": "COPYING", }, os.path.join('third_party', 'lss'): { "Name": "linux-syscall-support", "URL": "http://code.google.com/p/linux-syscall-support/", "License": "BSD", "License File": "/LICENSE", }, os.path.join('third_party', 'ots'): { "Name": "OTS (OpenType Sanitizer)", "URL": "http://code.google.com/p/ots/", "License": "BSD", }, os.path.join('third_party', 'pdfsqueeze'): { "Name": "pdfsqueeze", "URL": "http://code.google.com/p/pdfsqueeze/", "License": "Apache 2.0", "License File": "COPYING", }, os.path.join('third_party', 'ppapi'): { "Name": "ppapi", "URL": "http://code.google.com/p/ppapi/", }, os.path.join('third_party', 'scons-2.0.1'): { "Name": "scons-2.0.1", "URL": "http://www.scons.org", "License": "MIT", "License File": "NOT_SHIPPED", }, os.path.join('third_party', 'trace-viewer'): { "Name": "trace-viewer", "URL": "http://code.google.com/p/trace-viewer", "License": "BSD", "License File": "NOT_SHIPPED", }, os.path.join('third_party', 'v8-i18n'): { "Name": "Internationalization Library for v8", "URL": "http://code.google.com/p/v8-i18n/", "License": "Apache 2.0", }, os.path.join('third_party', 'WebKit'): { "Name": "WebKit", "URL": "http://webkit.org/", "License": "BSD and GPL v2", # Absolute path here is resolved as relative to the source root. "License File": "/webkit/LICENSE", }, os.path.join('third_party', 'webpagereplay'): { "Name": "webpagereplay", "URL": "http://code.google.com/p/web-page-replay", "License": "Apache 2.0", "License File": "NOT_SHIPPED", }, os.path.join('tools', 'grit'): { "Name": "grit", "URL": "http://code.google.com/p/grit-i18n", "License": "BSD", "License File": "NOT_SHIPPED", }, os.path.join('tools', 'gyp'): { "Name": "gyp", "URL": "http://code.google.com/p/gyp", "License": "BSD", "License File": "NOT_SHIPPED", }, os.path.join('v8'): { "Name": "V8 JavaScript Engine", "URL": "http://code.google.com/p/v8", "License": "BSD", }, os.path.join('v8', 'strongtalk'): { "Name": "Strongtalk", "URL": "http://www.strongtalk.org/", "License": "BSD", # Absolute path here is resolved as relative to the source root. "License File": "/v8/LICENSE.strongtalk", }, } # Special value for 'License File' field used to indicate that the license file # should not be used in about:credits. NOT_SHIPPED = "NOT_SHIPPED" class LicenseError(Exception): """We raise this exception when a directory's licensing info isn't fully filled out.""" pass def AbsolutePath(path, filename, root): """Convert a path in README.chromium to be absolute based on the source root.""" if filename.startswith('/'): # Absolute-looking paths are relative to the source root # (which is the directory we're run from). absolute_path = os.path.join(root, filename[1:]) else: absolute_path = os.path.join(root, path, filename) if os.path.exists(absolute_path): return absolute_path return None def ParseDir(path, root, require_license_file=True): """Examine a third_party/foo component and extract its metadata.""" # Parse metadata fields out of README.chromium. # We examine "LICENSE" for the license file by default. metadata = { "License File": "LICENSE", # Relative path to license text. "Name": None, # Short name (for header on about:credits). "URL": None, # Project home page. "License": None, # Software license. } # Relative path to a file containing some html we're required to place in # about:credits. optional_keys = ["Required Text", "License Android Compatible"] if path in SPECIAL_CASES: metadata.update(SPECIAL_CASES[path]) else: # Try to find README.chromium. readme_path = os.path.join(root, path, 'README.chromium') if not os.path.exists(readme_path): raise LicenseError("missing README.chromium or licenses.py " "SPECIAL_CASES entry") for line in open(readme_path): line = line.strip() if not line: break for key in metadata.keys() + optional_keys: field = key + ": " if line.startswith(field): metadata[key] = line[len(field):] # Check that all expected metadata is present. for key, value in metadata.iteritems(): if not value: raise LicenseError("couldn't find '" + key + "' line " "in README.chromium or licences.py " "SPECIAL_CASES") # Special-case modules that aren't in the shipping product, so don't need # their license in about:credits. if metadata["License File"] != NOT_SHIPPED: # Check that the license file exists. for filename in (metadata["License File"], "COPYING"): license_path = AbsolutePath(path, filename, root) if license_path is not None: break if require_license_file and not license_path: raise LicenseError("License file not found. " "Either add a file named LICENSE, " "import upstream's COPYING if available, " "or add a 'License File:' line to " "README.chromium with the appropriate path.") metadata["License File"] = license_path if "Required Text" in metadata: required_path = AbsolutePath(path, metadata["Required Text"], root) if required_path is not None: metadata["Required Text"] = required_path else: raise LicenseError("Required text file listed but not found.") return metadata def ContainsFiles(path, root): """Determines whether any files exist in a directory or in any of its subdirectories.""" for _, _, files in os.walk(os.path.join(root, path)): if files: return True return False def FilterDirsWithFiles(dirs_list, root): # If a directory contains no files, assume it's a DEPS directory for a # project not used by our current configuration and skip it. return [x for x in dirs_list if ContainsFiles(x, root)] def FindThirdPartyDirs(prune_paths, root): """Find all third_party directories underneath the source root.""" third_party_dirs = [] for path, dirs, files in os.walk(root): path = path[len(root)+1:] # Pretty up the path. if path in prune_paths: dirs[:] = [] continue # Prune out directories we want to skip. # (Note that we loop over PRUNE_DIRS so we're not iterating over a # list that we're simultaneously mutating.) for skip in PRUNE_DIRS: if skip in dirs: dirs.remove(skip) if os.path.basename(path) == 'third_party': # Add all subdirectories that are not marked for skipping. for dir in dirs: dirpath = os.path.join(path, dir) if dirpath not in prune_paths: third_party_dirs.append(dirpath) # Don't recurse into any subdirs from here. dirs[:] = [] continue # Don't recurse into paths in ADDITIONAL_PATHS, like we do with regular # third_party/foo paths. if path in ADDITIONAL_PATHS: dirs[:] = [] for dir in ADDITIONAL_PATHS: if dir not in prune_paths: third_party_dirs.append(dir) return third_party_dirs def ScanThirdPartyDirs(root=None): """Scan a list of directories and report on any problems we find.""" if root is None: root = os.getcwd() third_party_dirs = FindThirdPartyDirs(PRUNE_PATHS, root) third_party_dirs = FilterDirsWithFiles(third_party_dirs, root) errors = [] for path in sorted(third_party_dirs): try: metadata = ParseDir(path, root) except LicenseError, e: errors.append((path, e.args[0])) continue for path, error in sorted(errors): print path + ": " + error return len(errors) == 0 def GenerateCredits(): """Generate about:credits.""" if len(sys.argv) not in (2, 3): print 'usage: licenses.py credits [output_file]' return False def EvaluateTemplate(template, env, escape=True): """Expand a template with variables like {{foo}} using a dictionary of expansions.""" for key, val in env.items(): if escape and not key.endswith("_unescaped"): val = cgi.escape(val) template = template.replace('{{%s}}' % key, val) return template root = os.path.join(os.path.dirname(__file__), '..') third_party_dirs = FindThirdPartyDirs(PRUNE_PATHS, root) entry_template = open(os.path.join(root, 'chrome', 'browser', 'resources', 'about_credits_entry.tmpl'), 'rb').read() entries = [] for path in sorted(third_party_dirs): try: metadata = ParseDir(path, root) except LicenseError: # TODO(phajdan.jr): Convert to fatal error (http://crbug.com/39240). continue if metadata['License File'] == NOT_SHIPPED: continue env = { 'name': metadata['Name'], 'url': metadata['URL'], 'license': open(metadata['License File'], 'rb').read(), 'license_unescaped': '', } if 'Required Text' in metadata: required_text = open(metadata['Required Text'], 'rb').read() env["license_unescaped"] = required_text entries.append(EvaluateTemplate(entry_template, env)) file_template = open(os.path.join(root, 'chrome', 'browser', 'resources', 'about_credits.tmpl'), 'rb').read() template_contents = "<!-- Generated by licenses.py; do not edit. -->" template_contents += EvaluateTemplate(file_template, {'entries': '\n'.join(entries)}, escape=False) if len(sys.argv) == 3: with open(sys.argv[2], 'w') as output_file: output_file.write(template_contents) elif len(sys.argv) == 2: print template_contents return True def main(): command = 'help' if len(sys.argv) > 1: command = sys.argv[1] if command == 'scan': if not ScanThirdPartyDirs(): return 1 elif command == 'credits': if not GenerateCredits(): return 1 else: print __doc__ return 1 if __name__ == '__main__': sys.exit(main())