gt stringclasses 1
value | context stringlengths 2.49k 119k |
|---|---|
# -*- 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):
# Adding model 'ReservableProductCartReservation'
db.create_table(u'shop_reservableproductcartreservation', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('cart', self.gf('django.db.models.fields.related.ForeignKey')(related_name=u'reservations', to=orm['shop.Cart'])),
('reservation', self.gf('django.db.models.fields.related.ForeignKey')(related_name=u'in_carts', to=orm['shop.ReservableProductReservation'])),
('last_updated', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
))
db.send_create_signal(u'shop', ['ReservableProductCartReservation'])
# Adding model 'ReservableProduct'
db.create_table(u'shop_reservableproduct', (
(u'product_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['shop.Product'], unique=True, primary_key=True)),
))
db.send_create_signal(u'shop', ['ReservableProduct'])
# Adding model 'ReservableProductOrderReservation'
db.create_table(u'shop_reservableproductorderreservation', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('order', self.gf('django.db.models.fields.related.ForeignKey')(related_name=u'reservations', to=orm['shop.Order'])),
('reservation', self.gf('django.db.models.fields.related.ForeignKey')(related_name=u'in_orders', to=orm['shop.ReservableProductReservation'])),
('last_updated', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
))
db.send_create_signal(u'shop', ['ReservableProductOrderReservation'])
# Adding model 'SpecialPrice'
db.create_table(u'shop_specialprice', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('price_change', self.gf('cartridge.shop.fields.MoneyField')(null=True, max_digits=10, decimal_places=2, blank=True)),
('special_type', self.gf('django.db.models.fields.CharField')(max_length=3)),
('product', self.gf('django.db.models.fields.related.ForeignKey')(related_name=u'specialprices', to=orm['shop.Product'])),
))
db.send_create_signal(u'shop', ['SpecialPrice'])
# Adding model 'ReservableProductReservation'
db.create_table(u'shop_reservableproductreservation', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('date', self.gf('django.db.models.fields.DateField')()),
('product', self.gf('django.db.models.fields.related.ForeignKey')(related_name=u'reservations', to=orm['shop.ReservableProduct'])),
))
db.send_create_signal(u'shop', ['ReservableProductReservation'])
# Adding model 'ReservableProductAvailability'
db.create_table(u'shop_reservableproductavailability', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('from_date', self.gf('django.db.models.fields.DateField')()),
('to_date', self.gf('django.db.models.fields.DateField')()),
('product', self.gf('django.db.models.fields.related.ForeignKey')(related_name=u'availabilities', to=orm['shop.ReservableProduct'])),
))
db.send_create_signal(u'shop', ['ReservableProductAvailability'])
# Adding field 'CartItem.from_date'
db.add_column(u'shop_cartitem', 'from_date',
self.gf('django.db.models.fields.DateField')(null=True),
keep_default=False)
# Adding field 'CartItem.to_date'
db.add_column(u'shop_cartitem', 'to_date',
self.gf('django.db.models.fields.DateField')(null=True),
keep_default=False)
# Adding field 'OrderItem.from_date'
db.add_column(u'shop_orderitem', 'from_date',
self.gf('django.db.models.fields.DateField')(null=True),
keep_default=False)
# Adding field 'OrderItem.to_date'
db.add_column(u'shop_orderitem', 'to_date',
self.gf('django.db.models.fields.DateField')(null=True),
keep_default=False)
# Adding field 'OrderItem.external_order_id'
db.add_column(u'shop_orderitem', 'external_order_id',
self.gf('django.db.models.fields.IntegerField')(null=True, blank=True),
keep_default=False)
# Adding field 'Product.content_model'
db.add_column(u'shop_product', 'content_model',
self.gf('django.db.models.fields.CharField')(max_length=50, null=True),
keep_default=False)
def backwards(self, orm):
# Deleting model 'ReservableProductCartReservation'
db.delete_table(u'shop_reservableproductcartreservation')
# Deleting model 'ReservableProduct'
db.delete_table(u'shop_reservableproduct')
# Deleting model 'ReservableProductOrderReservation'
db.delete_table(u'shop_reservableproductorderreservation')
# Deleting model 'SpecialPrice'
db.delete_table(u'shop_specialprice')
# Deleting model 'ReservableProductReservation'
db.delete_table(u'shop_reservableproductreservation')
# Deleting model 'ReservableProductAvailability'
db.delete_table(u'shop_reservableproductavailability')
# Deleting field 'CartItem.from_date'
db.delete_column(u'shop_cartitem', 'from_date')
# Deleting field 'CartItem.to_date'
db.delete_column(u'shop_cartitem', 'to_date')
# Deleting field 'OrderItem.from_date'
db.delete_column(u'shop_orderitem', 'from_date')
# Deleting field 'OrderItem.to_date'
db.delete_column(u'shop_orderitem', 'to_date')
# Deleting field 'OrderItem.external_order_id'
db.delete_column(u'shop_orderitem', 'external_order_id')
# Deleting field 'Product.content_model'
db.delete_column(u'shop_product', 'content_model')
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'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': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'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': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'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': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'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'}),
u'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'})
},
u'generic.assignedkeyword': {
'Meta': {'ordering': "(u'_order',)", 'object_name': 'AssignedKeyword'},
'_order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'keyword': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'assignments'", 'to': u"orm['generic.Keyword']"}),
'object_pk': ('django.db.models.fields.IntegerField', [], {})
},
u'generic.keyword': {
'Meta': {'object_name': 'Keyword'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['sites.Site']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'})
},
u'generic.rating': {
'Meta': {'object_name': 'Rating'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'object_pk': ('django.db.models.fields.IntegerField', [], {}),
'rating_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'ratings'", 'null': 'True', 'to': u"orm['auth.User']"}),
'value': ('django.db.models.fields.IntegerField', [], {})
},
u'pages.page': {
'Meta': {'ordering': "(u'titles',)", 'object_name': 'Page'},
'_meta_title': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}),
'_order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'content_model': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'expiry_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'gen_description': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'in_menus': ('mezzanine.pages.fields.MenusField', [], {'default': '(1, 2, 3)', 'max_length': '100', 'null': 'True', 'blank': 'True'}),
'in_sitemap': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'keywords': ('mezzanine.generic.fields.KeywordsField', [], {'object_id_field': "u'object_pk'", 'to': u"orm['generic.AssignedKeyword']"}),
u'keywords_string': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}),
'login_required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'children'", 'null': 'True', 'to': u"orm['pages.Page']"}),
'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['sites.Site']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'titles': ('django.db.models.fields.CharField', [], {'max_length': '1000', 'null': 'True'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True'})
},
u'shop.cart': {
'Meta': {'object_name': 'Cart'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True'})
},
u'shop.cartitem': {
'Meta': {'object_name': 'CartItem'},
'cart': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'items'", 'to': u"orm['shop.Cart']"}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '2000'}),
'from_date': ('django.db.models.fields.DateField', [], {'null': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'}),
'quantity': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'sku': ('cartridge.shop.fields.SKUField', [], {'max_length': '20'}),
'to_date': ('django.db.models.fields.DateField', [], {'null': 'True'}),
'total_price': ('cartridge.shop.fields.MoneyField', [], {'default': "'0'", 'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'unit_price': ('cartridge.shop.fields.MoneyField', [], {'default': "'0'", 'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'url': ('django.db.models.fields.CharField', [], {'max_length': '2000'})
},
u'shop.category': {
'Meta': {'ordering': "(u'_order',)", 'object_name': 'Category', '_ormbases': [u'pages.Page']},
'combined': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'content': ('mezzanine.core.fields.RichTextField', [], {}),
'featured_image': ('mezzanine.core.fields.FileField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'options': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'product_options'", 'blank': 'True', 'to': u"orm['shop.ProductOption']"}),
u'page_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['pages.Page']", 'unique': 'True', 'primary_key': 'True'}),
'price_max': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'price_min': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'products': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['shop.Product']", 'symmetrical': 'False', 'blank': 'True'}),
'sale': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['shop.Sale']", 'null': 'True', 'blank': 'True'})
},
u'shop.discountcode': {
'Meta': {'object_name': 'DiscountCode'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'categories': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'discountcode_related'", 'blank': 'True', 'to': u"orm['shop.Category']"}),
'code': ('cartridge.shop.fields.DiscountCodeField', [], {'unique': 'True', 'max_length': '20'}),
'discount_deduct': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'discount_exact': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'discount_percent': ('cartridge.shop.fields.PercentageField', [], {'null': 'True', 'max_digits': '5', 'decimal_places': '2', 'blank': 'True'}),
'free_shipping': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'min_purchase': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'products': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['shop.Product']", 'symmetrical': 'False', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'uses_remaining': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'valid_from': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'valid_to': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'})
},
u'shop.order': {
'Meta': {'ordering': "(u'-id',)", 'object_name': 'Order'},
'additional_instructions': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'billing_detail_city': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'billing_detail_country': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'billing_detail_email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
'billing_detail_first_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'billing_detail_last_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'billing_detail_phone': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}),
'billing_detail_postcode': ('django.db.models.fields.CharField', [], {'max_length': '10', 'blank': 'True'}),
'billing_detail_state': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'billing_detail_street': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'discount_code': ('cartridge.shop.fields.DiscountCodeField', [], {'max_length': '20', 'blank': 'True'}),
'discount_total': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'item_total': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'shipping_detail_city': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'shipping_detail_country': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'shipping_detail_first_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'shipping_detail_last_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'shipping_detail_phone': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}),
'shipping_detail_postcode': ('django.db.models.fields.CharField', [], {'max_length': '10', 'blank': 'True'}),
'shipping_detail_state': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'shipping_detail_street': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'shipping_total': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'shipping_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '1'}),
'tax_total': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'tax_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
'time': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'total': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'transaction_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'user_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'})
},
u'shop.orderitem': {
'Meta': {'object_name': 'OrderItem'},
'description': ('django.db.models.fields.CharField', [], {'max_length': '2000'}),
'external_order_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'from_date': ('django.db.models.fields.DateField', [], {'null': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'order': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'items'", 'to': u"orm['shop.Order']"}),
'quantity': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'sku': ('cartridge.shop.fields.SKUField', [], {'max_length': '20'}),
'to_date': ('django.db.models.fields.DateField', [], {'null': 'True'}),
'total_price': ('cartridge.shop.fields.MoneyField', [], {'default': "'0'", 'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'unit_price': ('cartridge.shop.fields.MoneyField', [], {'default': "'0'", 'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'})
},
u'shop.product': {
'Meta': {'object_name': 'Product'},
'_meta_title': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}),
'available': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'categories': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['shop.Category']", 'symmetrical': 'False', 'blank': 'True'}),
'content': ('mezzanine.core.fields.RichTextField', [], {}),
'content_model': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'date_added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'expiry_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'gen_description': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'in_sitemap': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'keywords': ('mezzanine.generic.fields.KeywordsField', [], {'object_id_field': "u'object_pk'", 'to': u"orm['generic.AssignedKeyword']"}),
u'keywords_string': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}),
'num_in_stock': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'rating': ('mezzanine.generic.fields.RatingField', [], {'object_id_field': "u'object_pk'", 'to': u"orm['generic.Rating']"}),
u'rating_average': ('django.db.models.fields.FloatField', [], {'default': '0'}),
u'rating_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
u'rating_sum': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'related_products': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'related_products_rel_+'", 'blank': 'True', 'to': u"orm['shop.Product']"}),
'sale_from': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'sale_id': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'sale_price': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'sale_to': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['sites.Site']"}),
'sku': ('cartridge.shop.fields.SKUField', [], {'max_length': '20', 'unique': 'True', 'null': 'True', 'blank': 'True'}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'unit_price': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'upsell_products': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'upsell_products_rel_+'", 'blank': 'True', 'to': u"orm['shop.Product']"})
},
u'shop.productaction': {
'Meta': {'unique_together': "((u'product', u'timestamp'),)", 'object_name': 'ProductAction'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'actions'", 'to': u"orm['shop.Product']"}),
'timestamp': ('django.db.models.fields.IntegerField', [], {}),
'total_cart': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'total_purchase': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
u'shop.productimage': {
'Meta': {'ordering': "(u'_order',)", 'object_name': 'ProductImage'},
'_order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'file': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'images'", 'to': u"orm['shop.Product']"})
},
u'shop.productoption': {
'Meta': {'object_name': 'ProductOption'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('cartridge.shop.fields.OptionField', [], {'max_length': '50', 'null': 'True'}),
'type': ('django.db.models.fields.IntegerField', [], {})
},
u'shop.productvariation': {
'Meta': {'ordering': "(u'-default',)", 'object_name': 'ProductVariation'},
'default': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['shop.ProductImage']", 'null': 'True', 'blank': 'True'}),
'num_in_stock': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
u'option1': ('cartridge.shop.fields.OptionField', [], {'max_length': '50', 'null': 'True'}),
u'option2': ('cartridge.shop.fields.OptionField', [], {'max_length': '50', 'null': 'True'}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'variations'", 'to': u"orm['shop.Product']"}),
'sale_from': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'sale_id': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'sale_price': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'sale_to': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'sku': ('cartridge.shop.fields.SKUField', [], {'max_length': '20', 'unique': 'True', 'null': 'True', 'blank': 'True'}),
'unit_price': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'})
},
u'shop.reservableproduct': {
'Meta': {'object_name': 'ReservableProduct', '_ormbases': [u'shop.Product']},
u'product_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['shop.Product']", 'unique': 'True', 'primary_key': 'True'})
},
u'shop.reservableproductavailability': {
'Meta': {'object_name': 'ReservableProductAvailability'},
'from_date': ('django.db.models.fields.DateField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'availabilities'", 'to': u"orm['shop.ReservableProduct']"}),
'to_date': ('django.db.models.fields.DateField', [], {})
},
u'shop.reservableproductcartreservation': {
'Meta': {'ordering': "[u'-last_updated']", 'object_name': 'ReservableProductCartReservation'},
'cart': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'reservations'", 'to': u"orm['shop.Cart']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'reservation': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'in_carts'", 'to': u"orm['shop.ReservableProductReservation']"})
},
u'shop.reservableproductorderreservation': {
'Meta': {'object_name': 'ReservableProductOrderReservation'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'order': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'reservations'", 'to': u"orm['shop.Order']"}),
'reservation': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'in_orders'", 'to': u"orm['shop.ReservableProductReservation']"})
},
u'shop.reservableproductreservation': {
'Meta': {'ordering': "[u'-date']", 'object_name': 'ReservableProductReservation'},
'date': ('django.db.models.fields.DateField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'reservations'", 'to': u"orm['shop.ReservableProduct']"})
},
u'shop.sale': {
'Meta': {'object_name': 'Sale'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'categories': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'sale_related'", 'blank': 'True', 'to': u"orm['shop.Category']"}),
'discount_deduct': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'discount_exact': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'discount_percent': ('cartridge.shop.fields.PercentageField', [], {'null': 'True', 'max_digits': '5', 'decimal_places': '2', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'products': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['shop.Product']", 'symmetrical': 'False', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'valid_from': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'valid_to': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'})
},
u'shop.specialprice': {
'Meta': {'object_name': 'SpecialPrice'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'price_change': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'specialprices'", 'to': u"orm['shop.Product']"}),
'special_type': ('django.db.models.fields.CharField', [], {'max_length': '3'})
},
u'sites.site': {
'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"},
'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
}
}
complete_apps = ['shop']
| |
import contextlib
import logging
import os
import re
import signal
import timeit
import hail as hl
from py4j.protocol import Py4JError
from .resources import all_resources
from .. import init_logging
class BenchmarkTimeoutError(KeyboardInterrupt):
pass
_timeout_state = False
_init_args = {}
# https://stackoverflow.com/questions/492519/timeout-on-a-function-call/494273#494273
@contextlib.contextmanager
def timeout_signal(time_in_seconds):
global _timeout_state
_timeout_state = False
def handler(signum, frame):
global _timeout_state
_timeout_state = True
hl.stop()
hl.init(**_init_args)
raise BenchmarkTimeoutError()
signal.signal(signal.SIGALRM, handler)
signal.alarm(time_in_seconds)
try:
yield
finally:
def no_op(signum, frame):
pass
signal.signal(signal.SIGALRM, no_op)
signal.alarm(0)
def benchmark(args=()):
if len(args) == 2 and callable(args[1]):
args = (args,)
groups = set(h[0] for h in args)
fs = tuple(h[1] for h in args)
def inner(f):
_registry[f.__name__] = Benchmark(f, f.__name__, groups, fs)
return inner
class Benchmark:
def __init__(self, f, name, groups, args):
self.name = name
self.f = f
self.groups = groups
self.args = args
def run(self, data_dir):
self.f(*(arg(data_dir) for arg in self.args))
class RunConfig:
def __init__(self, n_iter, handler, noisy, timeout, dry_run, data_dir, cores, verbose, log,
profiler_path, profile, prof_fmt):
self.n_iter = n_iter
self.handler = handler
self.noisy = noisy
self.timeout = timeout
self.dry_run = dry_run
self.data_dir = data_dir
self.cores = cores
self.hail_verbose = verbose
self.log = log
self.profiler_path = profiler_path
self.profile = profile
self.prof_fmt = prof_fmt
_registry = {}
_initialized = False
def ensure_single_resource(data_dir, group):
resources = [r for r in all_resources if r.name() == group]
if not resources:
raise RuntimeError(f"no group {group!r}")
ensure_resources(data_dir, resources)
def ensure_resources(data_dir, resources):
logging.info(f'using benchmark data directory {data_dir}')
os.makedirs(data_dir, exist_ok=True)
to_create = []
for rg in resources:
if not rg.exists(data_dir):
to_create.append(rg)
if to_create:
hl.init()
for rg in to_create:
rg.create(data_dir)
hl.stop()
def _ensure_initialized():
if not _initialized:
raise AssertionError("Hail benchmark environment not initialized. "
"Are you running benchmark from the main module?")
def initialize(config):
global _initialized, _mt, _init_args
assert not _initialized
_init_args = { 'master': f'local[{config.cores}]', 'quiet': not config.hail_verbose, 'log': config.log }
if config.profile is not None:
if config.prof_fmt == 'html':
filetype = 'html'
fmt_arg = 'tree=total'
elif config.prof_fmt == 'flame':
filetype = 'svg'
fmt_arg = 'svg=total'
else:
filetype = 'jfr'
fmt_arg = 'jfr'
prof_args = (
f'-agentpath:{config.profiler_path}/build/libasyncProfiler.so=start,'
f'event={config.profile},'
f'{fmt_arg},'
f'file=bench-profile-{config.profile}-%t.{filetype},'
'interval=1ms,'
'framebuf=15000000')
_init_args['spark_conf'] = {
'spark.driver.extraJavaOptions': prof_args,
'spark.executor.extraJavaOptions': prof_args}
hl.init(**_init_args)
_initialized = True
# make JVM do something to ensure that it is fresh
hl.utils.range_table(1)._force_count()
logging.getLogger('py4j').setLevel(logging.CRITICAL)
logging.getLogger('py4j.java_gateway').setLevel(logging.CRITICAL)
def run_with_timeout(b, config):
max_time = config.timeout
with timeout_signal(max_time):
try:
return timeit.Timer(lambda: b.run(config.data_dir)).timeit(1), False
except Py4JError as e:
if _timeout_state:
return max_time, True
raise
except BenchmarkTimeoutError as e:
return max_time, True
def _run(benchmark: Benchmark, config: RunConfig, context):
_ensure_initialized()
if config.noisy:
logging.info(f'{context}Running {benchmark.name}...')
times = []
timed_out = False
try:
burn_in_time, burn_in_timed_out = run_with_timeout(benchmark, config)
if burn_in_timed_out:
if config.noisy:
logging.warning(f'burn in timed out after {burn_in_time:.2f}s')
timed_out = True
times.append(float(burn_in_time))
elif config.noisy:
logging.info(f'burn in: {burn_in_time:.2f}s')
except Exception as e: # pylint: disable=broad-except
if config.noisy:
logging.error(f'burn in: Caught exception: {e}')
config.handler({'name': benchmark.name,
'failed': True})
return
for i in range(config.n_iter):
if timed_out:
continue
try:
t, run_timed_out = run_with_timeout(benchmark, config)
times.append(t)
if run_timed_out:
if config.noisy:
logging.warning(f'run {i + 1} timed out after {t:.2f}s')
timed_out = True
elif config.noisy:
logging.info(f'run {i + 1}: {t:.2f}s')
except Exception as e: # pylint: disable=broad-except
if config.noisy:
logging.error(f'run ${i + 1}: Caught exception: {e}')
config.handler({'name': benchmark.name,
'failed': True})
return
config.handler({'name': benchmark.name,
'failed': False,
'timed_out': timed_out,
'times': times})
def run_all(config: RunConfig):
run_list(list(_registry), config)
def run_pattern(pattern, config: RunConfig):
to_run = []
regex = re.compile(pattern)
for name in _registry:
if regex.search(name):
to_run.append(name)
if not to_run:
raise ValueError(f'pattern {pattern!r} matched no benchmarks')
run_list(to_run, config)
def run_list(tests, config: RunConfig):
n_tests = len(tests)
to_run = []
for i, name in enumerate(tests):
b = _registry.get(name)
if not b:
raise ValueError(f'test {name!r} not found')
if config.dry_run:
logging.info(f'found benchmark {name}')
else:
to_run.append(b)
resources = {rg for b in to_run for rg in b.groups}
ensure_resources(config.data_dir, resources)
initialize(config)
for i, b in enumerate(to_run):
_run(b, config, f'[{i + 1}/{n_tests}] ')
def list_benchmarks():
return list(_registry.values())
| |
#!/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.
# Virtual Me2Me implementation. This script runs and manages the processes
# required for a Virtual Me2Me desktop, which are: X server, X desktop
# session, and Host process.
# This script is intended to run continuously as a background daemon
# process, running under an ordinary (non-root) user account.
import atexit
import base64
import errno
import getpass
import hashlib
import hmac
import json
import logging
import optparse
import os
import random
import signal
import socket
import subprocess
import sys
import tempfile
import time
import urllib2
import uuid
# Local modules
import gaia_auth
import keygen
REMOTING_COMMAND = "remoting_me2me_host"
# Command-line switch for passing the config path to remoting_me2me_host.
HOST_CONFIG_SWITCH_NAME = "host-config"
# Needs to be an absolute path, since the current working directory is changed
# when this process self-daemonizes.
SCRIPT_PATH = os.path.dirname(sys.argv[0])
if SCRIPT_PATH:
SCRIPT_PATH = os.path.abspath(SCRIPT_PATH)
else:
SCRIPT_PATH = os.getcwd()
# These are relative to SCRIPT_PATH.
EXE_PATHS_TO_TRY = [
".",
"../../out/Debug",
"../../out/Release"
]
CONFIG_DIR = os.path.expanduser("~/.config/chrome-remote-desktop")
HOME_DIR = os.environ["HOME"]
X_LOCK_FILE_TEMPLATE = "/tmp/.X%d-lock"
FIRST_X_DISPLAY_NUMBER = 20
X_AUTH_FILE = os.path.expanduser("~/.Xauthority")
os.environ["XAUTHORITY"] = X_AUTH_FILE
# Globals needed by the atexit cleanup() handler.
g_desktops = []
g_pidfile = None
class Authentication:
"""Manage authentication tokens for Chromoting/xmpp"""
def __init__(self, config_file):
self.config_file = config_file
def generate_tokens(self):
"""Prompt for username/password and use them to generate new authentication
tokens.
Raises:
Exception: Failed to get new authentication tokens.
"""
print "Email:",
self.login = raw_input()
password = getpass.getpass("Password: ")
chromoting_auth = gaia_auth.GaiaAuthenticator('chromoting')
self.chromoting_auth_token = chromoting_auth.authenticate(self.login,
password)
xmpp_authenticator = gaia_auth.GaiaAuthenticator('chromiumsync')
self.xmpp_auth_token = xmpp_authenticator.authenticate(self.login,
password)
def load_config(self):
try:
settings_file = open(self.config_file, 'r')
data = json.load(settings_file)
settings_file.close()
self.login = data["xmpp_login"]
self.chromoting_auth_token = data["chromoting_auth_token"]
self.xmpp_auth_token = data["xmpp_auth_token"]
except:
return False
return True
def save_config(self):
data = {
"xmpp_login": self.login,
"chromoting_auth_token": self.chromoting_auth_token,
"xmpp_auth_token": self.xmpp_auth_token,
}
# File will contain private keys, so deny read/write access to others.
old_umask = os.umask(0066)
settings_file = open(self.config_file, 'w')
settings_file.write(json.dumps(data, indent=2))
settings_file.close()
os.umask(old_umask)
class Host:
"""This manages the configuration for a host.
Callers should instantiate a Host object (passing in a filename where the
config will be kept), then should call either of the methods:
* register(auth): Create a new Host configuration and register it
with the Directory Service (the "auth" parameter is used to
authenticate with the Service).
* load_config(): Load a config from disk, with details of an existing Host
registration.
After calling register() (or making any config changes) the method
save_config() should be called to save the details to disk.
"""
server = 'www.googleapis.com'
url = 'https://' + server + '/chromoting/v1/@me/hosts'
def __init__(self, config_file):
self.config_file = config_file
self.host_id = str(uuid.uuid1())
self.host_name = socket.gethostname()
self.host_secret_hash = None
self.private_key = None
def register(self, auth):
"""Generates a private key for the stored |host_id|, and registers it with
the Directory service.
Args:
auth: Authentication object with credentials for authenticating with the
Directory service.
Raises:
urllib2.HTTPError: An error occurred talking to the Directory server
(for example, if the |auth| credentials were rejected).
"""
logging.info("HostId: " + self.host_id)
logging.info("HostName: " + self.host_name)
logging.info("Generating RSA key pair...")
(self.private_key, public_key) = keygen.generateRSAKeyPair()
logging.info("Done")
json_data = {
"data": {
"hostId": self.host_id,
"hostName": self.host_name,
"publicKey": public_key,
}
}
params = json.dumps(json_data)
headers = {
"Authorization": "GoogleLogin auth=" + auth.chromoting_auth_token,
"Content-Type": "application/json",
}
request = urllib2.Request(self.url, params, headers)
opener = urllib2.OpenerDirector()
opener.add_handler(urllib2.HTTPDefaultErrorHandler())
logging.info("Registering host with directory service...")
res = urllib2.urlopen(request)
data = res.read()
logging.info("Done")
def ask_pin(self):
print \
"""Chromoting host supports PIN-based authentication, but it doesn't
work with Chrome 16 and Chrome 17 clients. Leave the PIN empty if you
need to use Chrome 16 or Chrome 17 clients. If you only use Chrome 18
or above, please set a non-empty PIN. You can change PIN later using
-p flag."""
while 1:
pin = getpass.getpass("Host PIN: ")
if len(pin) == 0:
print "Using empty PIN"
break
if len(pin) < 4:
print "PIN must be at least 4 characters long."
continue
pin2 = getpass.getpass("Confirm host PIN: ")
if pin2 != pin:
print "PINs didn't match. Please try again."
continue
break
self.set_pin(pin)
def set_pin(self, pin):
if pin == "":
self.host_secret_hash = "plain:"
else:
self.host_secret_hash = "hmac:" + base64.b64encode(
hmac.new(str(self.host_id), pin, hashlib.sha256).digest())
def is_pin_set(self):
return self.host_secret_hash
def load_config(self):
try:
settings_file = open(self.config_file, 'r')
data = json.load(settings_file)
settings_file.close()
except:
logging.info("Failed to load: " + self.config_file)
return False
self.host_id = data["host_id"]
self.host_name = data["host_name"]
self.host_secret_hash = data.get("host_secret_hash")
self.private_key = data["private_key"]
return True
def save_config(self):
data = {
"host_id": self.host_id,
"host_name": self.host_name,
"host_secret_hash": self.host_secret_hash,
"private_key": self.private_key,
}
if self.host_secret_hash:
data["host_secret_hash"] = self.host_secret_hash
old_umask = os.umask(0066)
settings_file = open(self.config_file, 'w')
settings_file.write(json.dumps(data, indent=2))
settings_file.close()
os.umask(old_umask)
class Desktop:
"""Manage a single virtual desktop"""
def __init__(self, width, height):
self.x_proc = None
self.session_proc = None
self.host_proc = None
self.width = width
self.height = height
g_desktops.append(self)
@staticmethod
def get_unused_display_number():
"""Return a candidate display number for which there is currently no
X Server lock file"""
display = FIRST_X_DISPLAY_NUMBER
while os.path.exists(X_LOCK_FILE_TEMPLATE % display):
display += 1
return display
def launch_x_server(self, extra_x_args):
display = self.get_unused_display_number()
ret_code = subprocess.call("xauth add :%d . `mcookie`" % display,
shell=True)
if ret_code != 0:
raise Exception("xauth failed with code %d" % ret_code)
logging.info("Starting Xvfb on display :%d" % display);
screen_option = "%dx%dx24" % (self.width, self.height)
self.x_proc = subprocess.Popen(["Xvfb", ":%d" % display,
"-auth", X_AUTH_FILE,
"-nolisten", "tcp",
"-screen", "0", screen_option
] + extra_x_args)
if not self.x_proc.pid:
raise Exception("Could not start Xvfb.")
# Create clean environment for new session, so it is cleanly separated from
# the user's console X session.
self.child_env = {
"DISPLAY": ":%d" % display,
"REMOTING_ME2ME_SESSION": "1" }
for key in [
"HOME",
"LANG",
"LOGNAME",
"PATH",
"SHELL",
"USER",
"USERNAME"]:
if os.environ.has_key(key):
self.child_env[key] = os.environ[key]
# Wait for X to be active.
for test in range(5):
proc = subprocess.Popen("xdpyinfo > /dev/null", env=self.child_env,
shell=True)
pid, retcode = os.waitpid(proc.pid, 0)
if retcode == 0:
break
time.sleep(0.5)
if retcode != 0:
raise Exception("Could not connect to Xvfb.")
else:
logging.info("Xvfb is active.")
def launch_x_session(self):
# Start desktop session
# The /dev/null input redirection is necessary to prevent Xsession from
# reading from stdin. If this code runs as a shell background job in a
# terminal, any reading from stdin causes the job to be suspended.
# Daemonization would solve this problem by separating the process from the
# controlling terminal.
#
# This assumes that GDM is installed and configured on the system.
self.session_proc = subprocess.Popen("/etc/gdm/Xsession",
stdin=open(os.devnull, "r"),
cwd=HOME_DIR,
env=self.child_env)
if not self.session_proc.pid:
raise Exception("Could not start X session")
def launch_host(self, host):
# Start remoting host
args = [locate_executable(REMOTING_COMMAND),
"--%s=%s" % (HOST_CONFIG_SWITCH_NAME, host.config_file)]
self.host_proc = subprocess.Popen(args, env=self.child_env)
if not self.host_proc.pid:
raise Exception("Could not start remoting host")
class PidFile:
"""Class to allow creating and deleting a file which holds the PID of the
running process. This is used to detect if a process is already running, and
inform the user of the PID. On process termination, the PID file is
deleted.
Note that PID files are not truly atomic or reliable, see
http://mywiki.wooledge.org/ProcessManagement for more discussion on this.
So this class is just to prevent the user from accidentally running two
instances of this script, and to report which PID may be the other running
instance.
"""
def __init__(self, filename):
"""Create an object to manage a PID file. This does not create the PID
file itself."""
self.filename = filename
self.created = False
def check(self):
"""Checks current status of the process.
Returns:
Tuple (running, pid):
|running| is True if the daemon is running.
|pid| holds the process ID of the running instance if |running| is True.
If the PID file exists but the PID couldn't be read from the file
(perhaps if the data hasn't been written yet), 0 is returned.
Raises:
IOError: Filesystem error occurred.
"""
if os.path.exists(self.filename):
pid_file = open(self.filename, 'r')
file_contents = pid_file.read()
pid_file.close()
try:
pid = int(file_contents)
except ValueError:
return True, 0
# Test to see if there's a process currently running with that PID.
# If there is no process running, the existing PID file is definitely
# stale and it is safe to overwrite it. Otherwise, report the PID as
# possibly a running instance of this script.
if os.path.exists("/proc/%d" % pid):
return True, pid
return False, 0
def create(self):
"""Creates an empty PID file."""
pid_file = open(self.filename, 'w')
pid_file.close()
self.created = True
def write_pid(self):
"""Write the current process's PID to the PID file.
This is done separately from create() as this needs to be called
after any daemonization, when the correct PID becomes known. But
check() and create() has to happen before daemonization, so that
if another instance is already running, this fact can be reported
to the user's terminal session. This also avoids corrupting the
log file of the other process, since daemonize() would create a
new log file.
"""
pid_file = open(self.filename, 'w')
pid_file.write('%d\n' % os.getpid())
pid_file.close()
self.created = True
def delete_file(self):
"""Delete the PID file if it was created by this instance.
This is called on process termination.
"""
if self.created:
os.remove(self.filename)
def locate_executable(exe_name):
for path in EXE_PATHS_TO_TRY:
exe_path = os.path.join(SCRIPT_PATH, path, exe_name)
if os.path.exists(exe_path):
return exe_path
raise Exception("Could not locate executable '%s'" % exe_name)
def daemonize(log_filename):
"""Background this process and detach from controlling terminal, redirecting
stdout/stderr to |log_filename|."""
# TODO(lambroslambrou): Having stdout/stderr redirected to a log file is not
# ideal - it could create a filesystem DoS if the daemon or a child process
# were to write excessive amounts to stdout/stderr. Ideally, stdout/stderr
# should be redirected to a pipe or socket, and a process at the other end
# should consume the data and write it to a logging facility which can do
# data-capping or log-rotation. The 'logger' command-line utility could be
# used for this, but it might cause too much syslog spam.
# Create new (temporary) file-descriptors before forking, so any errors get
# reported to the main process and set the correct exit-code.
# The mode is provided, since Python otherwise sets a default mode of 0777,
# which would result in the new file having permissions of 0777 & ~umask,
# possibly leaving the executable bits set.
devnull_fd = os.open(os.devnull, os.O_RDONLY)
log_fd = os.open(log_filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0600)
pid = os.fork()
if pid == 0:
# Child process
os.setsid()
# The second fork ensures that the daemon isn't a session leader, so that
# it doesn't acquire a controlling terminal.
pid = os.fork()
if pid == 0:
# Grandchild process
pass
else:
# Child process
os._exit(0)
else:
# Parent process
os._exit(0)
logging.info("Daemon process running, logging to '%s'" % log_filename)
os.chdir(HOME_DIR)
# Copy the file-descriptors to create new stdin, stdout and stderr. Note
# that dup2(oldfd, newfd) closes newfd first, so this will close the current
# stdin, stdout and stderr, detaching from the terminal.
os.dup2(devnull_fd, sys.stdin.fileno())
os.dup2(log_fd, sys.stdout.fileno())
os.dup2(log_fd, sys.stderr.fileno())
# Close the temporary file-descriptors.
os.close(devnull_fd)
os.close(log_fd)
def cleanup():
logging.info("Cleanup.")
if g_pidfile:
try:
g_pidfile.delete_file()
except Exception, e:
logging.error("Unexpected error deleting PID file: " + str(e))
for desktop in g_desktops:
if desktop.x_proc:
logging.info("Terminating Xvfb")
desktop.x_proc.terminate()
def reload_config():
for desktop in g_desktops:
if desktop.host_proc:
# Terminating the Host will cause the main loop to spawn another
# instance, which will read any changes made to the Host config file.
desktop.host_proc.terminate()
def signal_handler(signum, stackframe):
if signum == signal.SIGUSR1:
logging.info("SIGUSR1 caught, reloading configuration.")
reload_config()
else:
# Exit cleanly so the atexit handler, cleanup(), gets called.
raise SystemExit
def main():
parser = optparse.OptionParser(
"Usage: %prog [options] [ -- [ X server options ] ]")
parser.add_option("-s", "--size", dest="size", default="1280x1024",
help="dimensions of virtual desktop (default: %default)")
parser.add_option("-f", "--foreground", dest="foreground", default=False,
action="store_true",
help="don't run as a background daemon")
parser.add_option("-k", "--stop", dest="stop", default=False,
action="store_true",
help="stop the daemon currently running")
parser.add_option("-p", "--new-pin", dest="new_pin", default=False,
action="store_true",
help="set new PIN before starting the host")
parser.add_option("", "--check-running", dest="check_running", default=False,
action="store_true",
help="return 0 if the daemon is running, or 1 otherwise")
parser.add_option("", "--explicit-config", dest="explicit_config",
help="explicitly specify content of the config")
(options, args) = parser.parse_args()
size_components = options.size.split("x")
if len(size_components) != 2:
parser.error("Incorrect size format, should be WIDTHxHEIGHT");
host_hash = hashlib.md5(socket.gethostname()).hexdigest()
pid_filename = os.path.join(CONFIG_DIR, "host#%s.pid" % host_hash)
if options.check_running:
running, pid = PidFile(pid_filename).check()
return 0 if (running and pid != 0) else 1
if options.stop:
running, pid = PidFile(pid_filename).check()
if not running:
print "The daemon currently is not running"
else:
print "Killing process %s" % pid
os.kill(pid, signal.SIGTERM)
return 0
try:
width = int(size_components[0])
height = int(size_components[1])
# Enforce minimum desktop size, as a sanity-check. The limit of 100 will
# detect typos of 2 instead of 3 digits.
if width < 100 or height < 100:
raise ValueError
except ValueError:
parser.error("Width and height should be 100 pixels or greater")
atexit.register(cleanup)
for s in [signal.SIGHUP, signal.SIGINT, signal.SIGTERM, signal.SIGUSR1]:
signal.signal(s, signal_handler)
# Ensure full path to config directory exists.
if not os.path.exists(CONFIG_DIR):
os.makedirs(CONFIG_DIR, mode=0700)
if options.explicit_config:
for file_name in ["auth.json", "host#%s.json" % host_hash]:
settings_file = open(os.path.join(CONFIG_DIR, file_name), 'w')
settings_file.write(options.explicit_config)
settings_file.close()
auth = Authentication(os.path.join(CONFIG_DIR, "auth.json"))
need_auth_tokens = not auth.load_config()
host = Host(os.path.join(CONFIG_DIR, "host#%s.json" % host_hash))
register_host = not host.load_config()
# Outside the loop so user doesn't get asked twice.
if register_host:
host.ask_pin()
elif options.new_pin or not host.is_pin_set():
host.ask_pin()
host.save_config()
running, pid = PidFile(pid_filename).check()
if running and pid != 0:
os.kill(pid, signal.SIGUSR1)
print "The running instance has been updated with the new PIN."
return 0
if not options.explicit_config:
# The loop is to deal with the case of registering a new Host with
# previously-saved auth tokens (from a previous run of this script), which
# may require re-prompting for username & password.
while True:
try:
if need_auth_tokens:
auth.generate_tokens()
auth.save_config()
need_auth_tokens = False
except Exception:
logging.error("Authentication failed")
return 1
try:
if register_host:
host.register(auth)
host.save_config()
except urllib2.HTTPError, err:
if err.getcode() == 401:
# Authentication failed - re-prompt for username & password.
need_auth_tokens = True
continue
else:
# Not an authentication error.
logging.error("Directory returned error: " + str(err))
logging.error(err.read())
return 1
# |auth| and |host| are both set up, so break out of the loop.
break
global g_pidfile
g_pidfile = PidFile(pid_filename)
running, pid = g_pidfile.check()
if running:
print "An instance of this script is already running."
print "Use the -k flag to terminate the running instance."
print "If this isn't the case, delete '%s' and try again." % pid_filename
return 1
g_pidfile.create()
# daemonize() must only be called after prompting for user/password, as the
# process will become detached from the controlling terminal.
if not options.foreground:
log_file = tempfile.NamedTemporaryFile(prefix="me2me_host_", delete=False)
daemonize(log_file.name)
g_pidfile.write_pid()
logging.info("Using host_id: " + host.host_id)
desktop = Desktop(width, height)
# Remember the time when the last session was launched, in order to enforce
# a minimum time between launches. This avoids spinning in case of a
# misconfigured system, or other error that prevents a session from starting
# properly.
last_launch_time = 0
while True:
# If the session process stops running (e.g. because the user logged out),
# the X server should be reset and the session restarted, to provide a
# completely clean new session.
if desktop.session_proc is None and desktop.x_proc is not None:
logging.info("Terminating X server")
desktop.x_proc.terminate()
if desktop.x_proc is None:
if desktop.session_proc is not None:
# The X session would probably die soon if the X server is not
# running (because of the loss of the X connection). Terminate it
# anyway, to be sure.
logging.info("Terminating X session")
desktop.session_proc.terminate()
else:
# Neither X server nor X session are running.
elapsed = time.time() - last_launch_time
if elapsed < 60:
logging.error("The session lasted less than 1 minute. Waiting " +
"before starting new session.")
time.sleep(60 - elapsed)
logging.info("Launching X server and X session")
last_launch_time = time.time()
desktop.launch_x_server(args)
desktop.launch_x_session()
if desktop.host_proc is None:
logging.info("Launching host process")
desktop.launch_host(host)
try:
pid, status = os.wait()
except OSError, e:
if e.errno == errno.EINTR:
# Retry on EINTR, which can happen if a signal such as SIGUSR1 is
# received.
continue
else:
# Anything else is an unexpected error.
raise
logging.info("wait() returned (%s,%s)" % (pid, status))
# When os.wait() notifies that a process has terminated, any Popen instance
# for that process is no longer valid. Reset any affected instance to
# None.
if desktop.x_proc is not None and pid == desktop.x_proc.pid:
logging.info("X server process terminated")
desktop.x_proc = None
if desktop.session_proc is not None and pid == desktop.session_proc.pid:
logging.info("Session process terminated")
desktop.session_proc = None
if desktop.host_proc is not None and pid == desktop.host_proc.pid:
logging.info("Host process terminated")
desktop.host_proc = None
# These exit-codes must match the ones used by the host.
# See remoting/host/constants.h.
# Delete the host or auth configuration depending on the returned error
# code, so the next time this script is run, a new configuration
# will be created and registered.
if os.WEXITSTATUS(status) == 2:
logging.info("Host configuration is invalid - exiting.")
os.remove(auth.config_file)
os.remove(host.config_file)
return 0
elif os.WEXITSTATUS(status) == 3:
logging.info("Host ID has been deleted - exiting.")
os.remove(host.config_file)
return 0
elif os.WEXITSTATUS(status) == 4:
logging.info("OAuth credentials are invalid - exiting.")
os.remove(auth.config_file)
return 0
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
sys.exit(main())
| |
# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import re
import warnings
import getpass
import sys
import logging
import signal
import colorama
import pydoc
from botocore.compat import six
from six import print_
from six.moves import input
from ..core import ebglobals
from ..objects.exceptions import ValidationError
from ..resources.strings import prompts, strings
LOG = logging.getLogger(__name__)
color_on = False
def start_color():
global color_on
if not color_on and term_is_colorable():
colorama.init()
color_on = True
return color_on
def term_is_colorable():
return sys.stdout.isatty() # Live terminal
def bold(string):
s = _convert_to_string(string)
if start_color():
return colorama.Style.BRIGHT + s + colorama.Style.NORMAL
else:
return s
def reset_all_color():
if start_color():
return colorama.Style.RESET_ALL
else:
return ''
def _remap_color(color):
if color.upper() == 'ORANGE':
return 'YELLOW'
if color.upper() in {'GREY', 'GRAY'}:
return 'WHITE'
return color
def color(color, string):
s = _convert_to_string(string)
if start_color():
color = _remap_color(color)
color_code = getattr(colorama.Fore, color.upper())
return color_code + s + colorama.Fore.RESET
else:
return s
def on_color(color, string):
s = _convert_to_string(string)
if start_color():
color = _remap_color(color)
color_code = getattr(colorama.Back, color.upper())
return color_code + s + colorama.Back.RESET
else:
return s
def echo_and_justify(justify, *args):
s = ''.join(s.ljust(justify) for s in _convert_to_strings(args))
print_(s.rstrip())
def echo(*args, **kwargs):
if 'sep' not in kwargs:
kwargs['sep'] = ' '
print_(*_convert_to_strings(args), **kwargs)
def _convert_to_strings(list_of_things):
for data in list_of_things:
yield _convert_to_string(data)
def _convert_to_string(data):
scalar_types = six.string_types + six.integer_types
if isinstance(data, six.binary_type):
if sys.version_info[0] >= 3:
return data.decode('utf8')
else:
return data
elif isinstance(data, six.text_type):
if sys.version_info[0] >= 3:
return data
else:
return data.encode('utf8')
elif isinstance(data, scalar_types) or hasattr(data, '__str__'):
return str(data)
else:
LOG.error('echo called with an unsupported data type')
LOG.debug('data class = ' + data.__class__.__name__)
def log_alert(message):
echo('Alert:', message)
def log_info(message):
ebglobals.app.log.info(message)
def log_warning(message):
ebglobals.app.log.warn(message)
def log_error(message):
if ebglobals.app.pargs.debug: # Debug mode, use logger
ebglobals.app.log.error(message)
else: # Otherwise, use color
echo(bold(color('red', 'ERROR: {}'.format(message))))
def get_input(output, default=None):
# importing readline module allows user to use bash commands
## such as Ctrl+A etc.
## Only works on non windows
try:
import readline
except ImportError:
# oh well, we tried
pass
# Trim spaces
output = next(_convert_to_strings([output]))
result = input(output + ': ').strip()
if not result:
result = default
return result
def echo_with_pager(output):
# pydoc.pager handles pipes and everything
pydoc.pager(output)
def prompt(output, default=None):
return get_input('(' + output + ')', default)
def prompt_for_unique_name(default, unique_list):
with warnings.catch_warnings():
warnings.simplefilter('ignore')
assert default not in unique_list, 'Default name is not unique'
while True:
result = prompt('default is "' + default + '"', default=default)
if result in unique_list:
echo('Sorry that name already exists, try another.')
else:
break
return result
def prompt_for_environment_name(default_name='myEnv',
prompt_text='Enter Environment Name'):
""" Validate env_name: Spec says:
Constraint: Must be from 4 to 40 characters in length.
The name can contain only letters, numbers, and hyphens.
It cannot start or end with a hyphen.
"""
constraint_pattern = '^[a-z0-9][a-z0-9-]{2,38}[a-z0-9]$'
# Edit default name to fit standards.
if not re.match(constraint_pattern, default_name):
if not re.match('^[a-zA-Z0-9].*', default_name): # begins correctly
default_name = 'eb-' + default_name
default_name = default_name.replace('_', '-')
default_name = re.sub('[^a-z0-9A-Z-]', '', default_name)
if len(default_name) > 40:
default_name = default_name[:39]
if not re.match('.*[a-zA-Z0-9]$', default_name): # end correctly
default_name += '0'
while True:
echo(prompt_text)
env_name = prompt('default is ' + default_name)
if not env_name:
return default_name
if re.match(constraint_pattern, env_name.lower()):
break
else:
echo('Environment name must be 4 to 40 characters in length. It '
'can only contain letters, numbers, and hyphens. It can not '
'start or end with a hyphen')
return env_name
def get_pass(output):
while True:
result = getpass.getpass(output + ': ')
if result == getpass.getpass('Retype password to confirm: '):
return result
else:
echo()
log_error('Passwords do not match')
def validate_action(output, expected_input):
result = get_input(output)
if result != expected_input:
raise ValidationError(prompts['terminate.nomatch'])
def prompt_for_cname(default=None):
# Validate cname: spec says:
# Constraint: Must be from 4 to 40 characters in length.
# The name can contain only letters, numbers, and hyphens.
# It cannot start or end with a hyphen.
while True:
echo('Enter DNS CNAME prefix')
if default:
cname = prompt('default is ' + default)
else:
cname = prompt('defaults to an auto-generated value')
if not cname:
return default
if re.match('^[a-z0-9][a-z0-9-]{2,61}[a-z0-9]$', cname.lower()):
break
else:
echo('CNAME must be 4 to 63 characters in length. It can'
' only contain letters, numbers, and hyphens. It can not '
'start or end with a hyphen')
return cname
def update_upload_progress(progress):
"""
Displays or updates a console progress bar
:param progress: Accepts a float between 0 and 1.
Any int will be converted to a float.
A value under 0 represents a 'halt'.
A value at 1 or bigger represents 100%
"""
barLength = 50 # Modify this to change the length of the progress bar
status = ""
if isinstance(progress, int):
progress = float(progress)
if not isinstance(progress, float):
progress = 0
status = "error: progress var must be float\r\n"
if progress < 0:
progress = 0
status = "Halt...\r\n"
if progress >= 1:
progress = 1
status = "Done...\r\n"
block = int(round(barLength*progress))
progress = int(round(progress * 100))
text = "\rUploading: [{0}] {1}% {2}".format(
"#"*block + "-"*(barLength-block), progress, status)
sys.stdout.write(text)
sys.stdout.flush()
def get_boolean_response(text=None):
if text:
string = text + ' (y/n)'
else:
string = '(y/n)'
response = get_input(string, default='y').lower()
while response not in ('y', 'n', 'yes', 'no'):
echo(strings['prompt.invalid'],
strings['prompt.yes-or-no'])
response = prompt('y/n', default='y').lower()
if response in ('y', 'yes'):
return True
else:
return False
def get_event_streamer():
if sys.stdout.isatty():
return EventStreamer()
else:
return PipeStreamer()
class EventStreamer(object):
def __init__(self):
self.prompt = strings['events.streamprompt']
self.unsafe_prompt = strings['events.unsafestreamprompt']
self.eventcount = 0
def stream_event(self, message, safe_to_quit=True):
"""
Streams an event so a prompt is displayed at the bottom of the stream
:param safe_to_quit: this determines which static event prompt to show to the user
:param message: message to be streamed
"""
length = len(self.prompt)
echo('\r', message.ljust(length), sep='')
if safe_to_quit:
echo(self.prompt, end='')
else:
echo(self.unsafe_prompt, end='')
sys.stdout.flush()
self.eventcount += 1
def end_stream(self):
"""
Removes the self.prompt from the screen
"""
if self.eventcount < 1:
return # Nothing to clean up
length = len(self.prompt) + 3 # Cover up "^C" character as well
print_('\r'.ljust(length))
class PipeStreamer(EventStreamer):
""" Really just a wrapper for EventStreamer
We dont want to actually do any "streaming" if
a pipe is being used, so we will just use standard printing
"""
def stream_event(self, message, safe_to_quit=True):
echo(message)
def end_stream(self):
return
| |
#!/usr/bin/env python
# Some of this is from here:
# https://github.com/bvanheu/pytoutv/blob/master/toutvcli/app.py
# Copyright (c) 2012, Benjamin Vanheuverzwijn <bvanheu@gmail.com>
# Copyright (c) 2014, Philippe Proulx <eepp.ca>
# All rights reserved.
#
# Thanks to Marc-Etienne M. Leveille
#
# 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 pytoutv 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 Benjamin Vanheuverzwijn OR Philippe Proulx
# BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import datetime
import distutils.version
import json
import locale
import os
import os.path
import sys
import toutv.dl
import toutv.exceptions
import toutv.transport
import toutvcli.app
# Bitrates less than this value will be considered more or less the same when downloading
MAX_BITRATE_DIFFERENCE = 2000
# The maximum number of times an emission will be listed as new
MAX_NEW_COUNT = 3
# The maximum number of times per operation timeout errors will be ignored
MAX_TIMEOUTS = 10
def retry_function(function, *args, **kwargs):
for n in range(MAX_TIMEOUTS):
try:
result = function(*args, **kwargs)
break
except toutv.exceptions.RequestTimeoutError:
pass
if n == MAX_TIMEOUTS - 1:
sys.exit('Error: max timeout attempts reached\n')
return result
class App(toutvcli.app.App):
# Override
def run(self):
locale.setlocale(locale.LC_ALL, '')
# Override help messages
for action in self._argparser._actions[1]._choices_actions:
if action.dest == 'list':
action.help = 'List new emissions or episodes since last run'
for action in self._argparser._actions[1].choices['list']._actions:
if action.dest == 'all':
action.help = 'List all emissions or episodes'
super().run()
# Override
def _build_toutv_client(self, *args, **kwargs):
print('Please wait...\n')
client = super()._build_toutv_client(*args, **kwargs)
client._transport = JsonTransport()
return client
# Override
def _command_fetch(self, *args, **kwargs):
self._store = DataStore()
super()._command_fetch(*args, **kwargs)
self._store.write()
# Override
def _fetch_emission_episodes(self, emission, output_dir, bitrate, quality,
overwrite):
episodes = self._toutvclient.get_emission_episodes(emission)
if not episodes:
title = emission.get_title()
print('No episodes available for emission "{}"'.format(title))
return
# Sort episodes by season and episode so they're downloaded in order
def episode_sort_func(episode_id):
return distutils.version.LooseVersion(episodes[episode_id].SeasonAndEpisode)
episode_ids = list(episodes.keys())
episode_ids.sort(key=episode_sort_func)
for episode_id in episode_ids:
episode = episodes[episode_id]
title = episode.get_title()
if self._stop:
raise toutv.dl.CancelledByUserError()
try:
self._fetch_episode(episode, output_dir, bitrate, quality,
overwrite)
except toutv.exceptions.RequestTimeoutError:
tmpl = 'Error: cannot fetch "{}": request timeout'
print(tmpl.format(title), file=sys.stderr)
except toutv.exceptions.UnexpectedHttpStatusCodeError:
tmpl = 'Error: cannot fetch "{}": unexpected HTTP status code'
print(tmpl.format(title), file=sys.stderr)
except toutv.exceptions.NetworkError as e:
tmpl = 'Error: cannot fetch "{}": {}'
print(tmpl.format(title, e), file=sys.stderr)
except toutv.dl.FileExistsError as e:
tmpl = 'Error: cannot fetch "{}": destination file exists'
print(tmpl.format(title), file=sys.stderr)
except toutv.dl.CancelledByUserError as e:
raise e
except toutv.dl.DownloadError as e:
tmpl = 'Error: cannot fetch "{}": {}'
print(tmpl.format(title, e), file=sys.stderr)
except Exception as e:
tmpl = 'Error: cannot fetch "{}": {}'
print(tmpl.format(title, e), file=sys.stderr)
# Override
def _fetch_episode(self, episode, output_dir, bitrate, quality, overwrite):
def remove_special_chars(s):
# http://superuser.com/a/358861/93066
special_chars = ['\\', '/', ':', '*', '?', '"', '<', '>', '|']
for c in special_chars:
s = s.replace(c, '')
return s
def download_episode():
nonlocal store_episode
sys.stdout.write('\n')
# Create downloader
opu = self._on_dl_progress_update
self._dl = Downloader(episode, bitrate=bitrate,
output_dir=output_dir,
on_dl_start=self._on_dl_start,
on_progress_update=opu,
overwrite=overwrite)
# Start download
self._dl.download()
sys.stdout.flush()
# Rename downloaded file
filepath = os.path.join(output_dir, self._dl.filename)
if os.path.isfile(filepath):
# Base new filename on whether it's a film/documentary or not
if episode._emission.Genre.Title == 'Films et documentaires':
new_filepath = os.path.join(
output_dir,
'{} ({}).mp4'.format(
remove_special_chars(episode.Title),
remove_special_chars(episode.Year),
)
)
else:
new_filepath = os.path.join(
output_dir,
'{} - {} - {}.mp4'.format(
remove_special_chars(episode._emission.Title),
remove_special_chars(episode.SeasonAndEpisode),
remove_special_chars(episode.Title),
)
)
if os.path.isfile(new_filepath) and not overwrite:
sys.stderr.write(
'Warning: file already exists (use -f to override): {}'.format(
new_filepath))
else:
os.replace(filepath, new_filepath)
# Finished
self._dl = None
# Save the downloaded episode info to the datastore file
if store_episode is None:
store_episode = Episode()
store_episode.bitrate = bitrate
store_episode.id = episode.Id
store_episode.title = episode.Title
store_emission.episodes.append(store_episode)
else:
store_episode.bitrate = bitrate
self._store.write()
# Match the emission from the datastore file
store_emission = None
for em in self._store.emissions:
# Match first by Id
if hasattr(em, 'id') and em.id == episode._emission.Id:
if em.title.lower() != episode._emission.Title.lower():
sys.stderr.write(
'Warning: emission title mismatch\n'
'\tId: {}\n'
'\tTou.tv title: {}\n'
'\tData file title: {}\n'.format(
episode._emission.Id,
episode._emission.Title,
em.title
)
)
store_emission = em
break
if em.title.lower() == episode._emission.Title.lower():
if hasattr(em, 'id'):
if em.id != episode._emission.Id:
sys.stderr.write(
'Warning: emission Id mismatch\n'
'\tTitle: {}\n'
'\tTou.tv Id: {}\n'
'\tData file Id: {}\n'.format(
episode._emission.Title,
episode._emission.Id,
em.id
)
)
else:
# Imported emissions may not have Ids; add them
em.id = episode._emission.Id
store_emission = em
break
# Save the emission info to the datastore file if it doesn't exist
if store_emission is None:
store_emission = Emission()
store_emission.id = episode._emission.Id
store_emission.last_seen = None
store_emission.title = episode._emission.Title
self._store.emissions.append(store_emission)
# See if the episode has already been downloaded
store_episode = None
for ep in store_emission.episodes:
# Match first by Id
if hasattr(ep, 'id') and ep.id == episode.Id:
if ep.title.lower() != episode.Title.lower():
sys.stderr.write(
'Warning: episode title mismatch\n'
'\tId: {}\n'
'\tTou.tv title: {}\n'
'\tData file title: {}\n'.format(
episode.Id,
episode.Title,
ep.title
)
)
store_episode = ep
break
# Otherwise match by title
if ep.title.lower() == episode.Title.lower():
if hasattr(ep, 'id'):
if ep.id != episode.Id:
sys.stderr.write(
'Warning: episode Id mismatch\n'
'\tTitle: {}\n'
'\tTou.tv Id: {}\n'
'\tData file Id: {}\n'.format(
episode.Title,
episode.Id,
ep.id
)
)
else:
# Imported episodes may not have Ids; add them
ep.id = episode.Id
store_episode = ep
break
# Get available bitrates for episode
qualities = retry_function(episode.get_available_qualities)
# Choose bitrate
if bitrate is None:
if quality == toutvcli.app.App.QUALITY_MIN:
bitrate = qualities[0].bitrate
elif quality == toutvcli.app.App.QUALITY_MAX:
bitrate = qualities[-1].bitrate
elif quality == toutvcli.app.App.QUALITY_AVG:
bitrate = toutvcli.app.App._get_average_bitrate(qualities)
# Try to select a matching bitrate if it's within the specified tolerance
else:
for quality in qualities:
if abs(int(quality.bitrate) - int(bitrate)) <= MAX_BITRATE_DIFFERENCE:
bitrate = quality.bitrate
break
# Don't download if episode already downloaded
if store_episode is not None and not overwrite:
if abs(int(store_episode.bitrate) - int(bitrate)) <= MAX_BITRATE_DIFFERENCE:
print('Already downloaded (use -f to download anyway): {} - {} - {}'.format(
episode._emission.Title,
episode.SeasonAndEpisode,
episode.Title))
# TODO: temporary cleanup code; remove eventually
opu = self._on_dl_progress_update
self._dl = Downloader(episode, bitrate=bitrate,
output_dir=output_dir,
on_dl_start=self._on_dl_start,
on_progress_update=opu,
overwrite=overwrite)
filepath = os.path.join(output_dir, self._dl.filename)
if os.path.isfile(filepath) and os.path.getsize(filepath) == 0:
os.remove(filepath)
self._dl = None
else:
print('Already downloaded with bitrate {}: {} - {} - {}'.format(
store_episode.bitrate,
episode._emission.Title,
episode.SeasonAndEpisode,
episode.Title))
response = input('Do you wish to download with bitrate {}? (y/n) '.format(
bitrate))
if response.lower() == 'y':
download_episode()
else:
download_episode()
# Override
def _print_list_emissions(self, arg_all=False):
def list_emissions(all_emissions, emissions_to_list):
for emission_id in emissions_to_list:
emission = all_emissions[emission_id]
emission_string = ('{}\n\t{}\n\t{}'.format(
emission.Title,
emission.get_url(),
emission.Genre.Title,
))
if emission.Country is not None:
emission_string += '\n\t{}'.format(emission.Country)
print(emission_string)
def title_sort_func(ekey):
return locale.strxfrm(repertoire_emissions[ekey].get_title())
# Get the list of current emissions
repertoire = self._toutvclient.get_page_repertoire()
repertoire_emissions = repertoire.get_emissions()
today = datetime.datetime.now().strftime('%Y-%m-%d')
store = DataStore()
# If this is the first run ever or the first run of the day
if store.last_run != today:
# If this is the first run ever
if store.last_run is None:
store.last_run = today
# Start with a fresh list of new emissions
store.new_emissions = []
for emission_id in repertoire_emissions:
emission = None
# Get the emission from the datastore
for em in store.emissions:
# Match first by Id
if hasattr(em, 'id') and em.id == emission_id:
if em.title.lower() != repertoire_emissions[emission_id].Title.lower():
sys.stderr.write(
'Warning: emission title mismatch\n'
'\tId: {}\n'
'\tTou.tv title: {}\n'
'\tData file title: {}\n'.format(
emission_id,
repertoire_emissions[emission_id].Title,
em.title
)
)
if emission is not None:
sys.stderr.write('Warning: duplicate emission exists in datastore with Id {}\n'.format(emission_id))
else:
emission = em
elif em.title.lower() == repertoire_emissions[emission_id].Title.lower():
if hasattr(em, 'id'):
if em.id != emission_id:
sys.stderr.write(
'Warning: emission Id mismatch\n'
'\tTitle: {}\n'
'\tTou.tv Id: {}\n'
'\tData file Id: {}\n'.format(
repertoire_emissions[emission_id].Title,
emission_id,
em.id
)
)
else:
# Imported emissions may not have Ids; add them
em.id = emission_id
if emission is not None:
sys.stderr.write('Warning: duplicate emission exists in datastore with title {}\n'.format(
repertoire_emissions[emission_id].Title))
else:
emission = em
# If this is a completely new emission
if emission is None:
emission = Emission()
emission.id = emission_id
emission.last_seen = None
emission.title = repertoire_emissions[emission_id].Title
store.emissions.append(emission)
# If this is a completely new emission or an emission added by _fetch_episode()
if emission.last_seen == None:
emission.first_seen = today
# If this is a new emission since the last run
if emission.last_seen != store.last_run:
emission.new_count += 1
if emission.new_count <= MAX_NEW_COUNT:
store.new_emissions.append(emission_id)
emission.last_seen = today
# Sort the list of new emissions alphabetically
store.new_emissions.sort(key=title_sort_func)
store.last_run = today
store.write()
# List all emissions
if arg_all:
emissions_keys = list(repertoire_emissions.keys())
emissions_keys.sort(key=title_sort_func)
list_emissions(repertoire_emissions, emissions_keys)
# List only new emissions
else:
if len(store.new_emissions) == 0:
print('No new emissions since last run (use -a to list all emissions)')
else:
list_emissions(repertoire_emissions, store.new_emissions)
class DataStore():
def __init__(self):
self.emissions = []
self.last_run = None
data_path = self._get_data_file_path()
if os.path.exists(data_path):
with open(data_path, 'r') as data_file:
json_data = json.loads(data_file.read())
for data_key in json_data.keys():
if data_key == 'emissions':
for json_emission in json_data[data_key]:
emission = Emission()
for emission_key in json_emission.keys():
if emission_key == 'episodes':
for json_episode in json_emission[emission_key]:
episode = Episode()
for episode_key in json_episode.keys():
episode.__setattr__(episode_key, json_episode[episode_key])
emission.episodes.append(episode)
else:
emission.__setattr__(emission_key, json_emission[emission_key])
self.emissions.append(emission)
else:
self.__setattr__(data_key, json_data[data_key])
def _get_data_file_path(self):
DATA_FILE_NAME = 'toutv_data.json'
if 'XDG_DATA_HOME' in os.environ:
data_dir = os.environ['XDG_DATA_HOME']
xdg_data_path = os.path.join(data_dir, 'toutv')
if not os.path.exists(xdg_data_path):
os.makedirs(xdg_data_path)
data_path = os.path.join(xdg_data_path, DATA_FILE_NAME)
else:
home_dir = os.environ['HOME']
home_data_path = os.path.join(home_dir, '.local', 'share', 'toutv')
if not os.path.exists(home_data_path):
os.makedirs(home_data_path)
data_path = os.path.join(home_data_path, DATA_FILE_NAME)
return data_path
def write(self):
data_path = self._get_data_file_path()
with open(data_path, 'w') as data_file:
data_file.write(
json.dumps(
self,
cls=JsonObjectEncoder,
sort_keys=True,
indent=4,
ensure_ascii=False,
)
)
class Downloader(toutv.dl.Downloader):
# Override
def _do_request(self, *args, **kwargs):
return retry_function(super()._do_request, *args, **kwargs)
class Emission:
def __init__(self):
self.episodes = []
self.last_seen = None
self.new_count = 0
class Episode:
pass
class JsonObjectEncoder(json.JSONEncoder):
def default(self, o):
return o.__dict__
class JsonTransport(toutv.transport.JsonTransport):
# Override
def _do_query(self, *args, **kwargs):
return retry_function(super()._do_query, *args, **kwargs)
def run():
app = App(sys.argv[1:])
return app.run()
| |
#!/bin/env python
import os
import sys
import string
from xml.dom import minidom
#
# opgen.py -- generates tables and constants for decoding
#
# - itab.c
# - itab.h
#
#
# special mnemonic types for internal purposes.
#
spl_mnm_types = [ 'd3vil', \
'na', \
'grp_reg', \
'grp_rm', \
'grp_vendor', \
'grp_x87', \
'grp_mode', \
'grp_osize', \
'grp_asize', \
'grp_mod', \
'none' \
]
#
# opcode-vendor dictionary
#
vend_dict = {
'AMD' : '00',
'INTEL' : '01'
}
#
# opcode-mode dictionary
#
mode_dict = {
'16' : '00',
'32' : '01',
'64' : '02'
}
#
# opcode-operand dictionary
#
operand_dict = {
"Ap" : [ "OP_A" , "SZ_P" ],
"E" : [ "OP_E" , "SZ_NA" ],
"Eb" : [ "OP_E" , "SZ_B" ],
"Ew" : [ "OP_E" , "SZ_W" ],
"Ev" : [ "OP_E" , "SZ_V" ],
"Ed" : [ "OP_E" , "SZ_D" ],
"Ez" : [ "OP_E" , "SZ_Z" ],
"Ex" : [ "OP_E" , "SZ_MDQ" ],
"Ep" : [ "OP_E" , "SZ_P" ],
"G" : [ "OP_G" , "SZ_NA" ],
"Gb" : [ "OP_G" , "SZ_B" ],
"Gw" : [ "OP_G" , "SZ_W" ],
"Gv" : [ "OP_G" , "SZ_V" ],
"Gvw" : [ "OP_G" , "SZ_MDQ" ],
"Gd" : [ "OP_G" , "SZ_D" ],
"Gx" : [ "OP_G" , "SZ_MDQ" ],
"Gz" : [ "OP_G" , "SZ_Z" ],
"M" : [ "OP_M" , "SZ_NA" ],
"Mb" : [ "OP_M" , "SZ_B" ],
"Mw" : [ "OP_M" , "SZ_W" ],
"Ms" : [ "OP_M" , "SZ_W" ],
"Md" : [ "OP_M" , "SZ_D" ],
"Mq" : [ "OP_M" , "SZ_Q" ],
"Mt" : [ "OP_M" , "SZ_T" ],
"I1" : [ "OP_I1" , "SZ_NA" ],
"I3" : [ "OP_I3" , "SZ_NA" ],
"Ib" : [ "OP_I" , "SZ_B" ],
"Isb" : [ "OP_I" , "SZ_SB" ],
"Iw" : [ "OP_I" , "SZ_W" ],
"Iv" : [ "OP_I" , "SZ_V" ],
"Iz" : [ "OP_I" , "SZ_Z" ],
"Jv" : [ "OP_J" , "SZ_V" ],
"Jz" : [ "OP_J" , "SZ_Z" ],
"Jb" : [ "OP_J" , "SZ_B" ],
"R" : [ "OP_R" , "SZ_RDQ" ],
"C" : [ "OP_C" , "SZ_NA" ],
"D" : [ "OP_D" , "SZ_NA" ],
"S" : [ "OP_S" , "SZ_NA" ],
"Ob" : [ "OP_O" , "SZ_B" ],
"Ow" : [ "OP_O" , "SZ_W" ],
"Ov" : [ "OP_O" , "SZ_V" ],
"V" : [ "OP_V" , "SZ_NA" ],
"W" : [ "OP_W" , "SZ_NA" ],
"P" : [ "OP_P" , "SZ_NA" ],
"Q" : [ "OP_Q" , "SZ_NA" ],
"VR" : [ "OP_VR" , "SZ_NA" ],
"PR" : [ "OP_PR" , "SZ_NA" ],
"AL" : [ "OP_AL" , "SZ_NA" ],
"CL" : [ "OP_CL" , "SZ_NA" ],
"DL" : [ "OP_DL" , "SZ_NA" ],
"BL" : [ "OP_BL" , "SZ_NA" ],
"AH" : [ "OP_AH" , "SZ_NA" ],
"CH" : [ "OP_CH" , "SZ_NA" ],
"DH" : [ "OP_DH" , "SZ_NA" ],
"BH" : [ "OP_BH" , "SZ_NA" ],
"AX" : [ "OP_AX" , "SZ_NA" ],
"CX" : [ "OP_CX" , "SZ_NA" ],
"DX" : [ "OP_DX" , "SZ_NA" ],
"BX" : [ "OP_BX" , "SZ_NA" ],
"SI" : [ "OP_SI" , "SZ_NA" ],
"DI" : [ "OP_DI" , "SZ_NA" ],
"SP" : [ "OP_SP" , "SZ_NA" ],
"BP" : [ "OP_BP" , "SZ_NA" ],
"eAX" : [ "OP_eAX" , "SZ_NA" ],
"eCX" : [ "OP_eCX" , "SZ_NA" ],
"eDX" : [ "OP_eDX" , "SZ_NA" ],
"eBX" : [ "OP_eBX" , "SZ_NA" ],
"eSI" : [ "OP_eSI" , "SZ_NA" ],
"eDI" : [ "OP_eDI" , "SZ_NA" ],
"eSP" : [ "OP_eSP" , "SZ_NA" ],
"eBP" : [ "OP_eBP" , "SZ_NA" ],
"rAX" : [ "OP_rAX" , "SZ_NA" ],
"rCX" : [ "OP_rCX" , "SZ_NA" ],
"rBX" : [ "OP_rBX" , "SZ_NA" ],
"rDX" : [ "OP_rDX" , "SZ_NA" ],
"rSI" : [ "OP_rSI" , "SZ_NA" ],
"rDI" : [ "OP_rDI" , "SZ_NA" ],
"rSP" : [ "OP_rSP" , "SZ_NA" ],
"rBP" : [ "OP_rBP" , "SZ_NA" ],
"ES" : [ "OP_ES" , "SZ_NA" ],
"CS" : [ "OP_CS" , "SZ_NA" ],
"DS" : [ "OP_DS" , "SZ_NA" ],
"SS" : [ "OP_SS" , "SZ_NA" ],
"GS" : [ "OP_GS" , "SZ_NA" ],
"FS" : [ "OP_FS" , "SZ_NA" ],
"ST0" : [ "OP_ST0" , "SZ_NA" ],
"ST1" : [ "OP_ST1" , "SZ_NA" ],
"ST2" : [ "OP_ST2" , "SZ_NA" ],
"ST3" : [ "OP_ST3" , "SZ_NA" ],
"ST4" : [ "OP_ST4" , "SZ_NA" ],
"ST5" : [ "OP_ST5" , "SZ_NA" ],
"ST6" : [ "OP_ST6" , "SZ_NA" ],
"ST7" : [ "OP_ST7" , "SZ_NA" ],
"NONE" : [ "OP_NONE" , "SZ_NA" ],
"ALr8b" : [ "OP_ALr8b" , "SZ_NA" ],
"CLr9b" : [ "OP_CLr9b" , "SZ_NA" ],
"DLr10b" : [ "OP_DLr10b" , "SZ_NA" ],
"BLr11b" : [ "OP_BLr11b" , "SZ_NA" ],
"AHr12b" : [ "OP_AHr12b" , "SZ_NA" ],
"CHr13b" : [ "OP_CHr13b" , "SZ_NA" ],
"DHr14b" : [ "OP_DHr14b" , "SZ_NA" ],
"BHr15b" : [ "OP_BHr15b" , "SZ_NA" ],
"rAXr8" : [ "OP_rAXr8" , "SZ_NA" ],
"rCXr9" : [ "OP_rCXr9" , "SZ_NA" ],
"rDXr10" : [ "OP_rDXr10" , "SZ_NA" ],
"rBXr11" : [ "OP_rBXr11" , "SZ_NA" ],
"rSPr12" : [ "OP_rSPr12" , "SZ_NA" ],
"rBPr13" : [ "OP_rBPr13" , "SZ_NA" ],
"rSIr14" : [ "OP_rSIr14" , "SZ_NA" ],
"rDIr15" : [ "OP_rDIr15" , "SZ_NA" ],
"jWP" : [ "OP_J" , "SZ_WP" ],
"jDP" : [ "OP_J" , "SZ_DP" ],
}
#
# opcode prefix dictionary
#
pfx_dict = {
"aso" : "P_aso",
"oso" : "P_oso",
"rexw" : "P_rexw",
"rexb" : "P_rexb",
"rexx" : "P_rexx",
"rexr" : "P_rexr",
"inv64" : "P_inv64",
"def64" : "P_def64",
"depM" : "P_depM",
"cast1" : "P_c1",
"cast2" : "P_c2",
"cast3" : "P_c3"
}
#
# globals
#
opr_constants = []
siz_constants = []
tables = {}
table_sizes = {}
mnm_list = []
default_opr = 'O_NONE, O_NONE, O_NONE'
#
# collect the operand/size constants
#
for o in operand_dict.keys():
if not (operand_dict[o][0] in opr_constants):
opr_constants.append(operand_dict[o][0])
if not (operand_dict[o][1] in siz_constants):
siz_constants.append(operand_dict[o][1])
xmlDoc = minidom.parse( "../docs/x86optable.xml" )
tlNode = xmlDoc.firstChild
#
# look for top-level optable node
#
while tlNode and tlNode.localName != "x86optable": tlNode = tlNode.nextSibling
#
# creates a table entry
#
def centry(i, defmap):
if defmap["type"][0:3] == "grp":
opr = default_opr
mnm = 'UD_I' + defmap["type"].lower()
pfx = defmap["name"].upper()
elif defmap["type"] == "leaf":
mnm = "UD_I" + defmap["name"]
opr = defmap["opr"]
pfx = defmap["pfx"]
if len(mnm) == 0: mnm = "UD_Ina"
if len(opr) == 0: opr = default_opr
if len(pfx) == 0: pfx = "P_none"
else:
opr = default_opr
pfx = "P_none"
mnm = "UD_Iinvalid"
return " /* %s */ { %-16s %-26s %s },\n" % (i, mnm + ',', opr + ',', pfx)
#
# makes a new table and adds it to the global
# list of tables
#
def mktab(name, size):
if not (name in tables.keys()):
tables[name] = {}
table_sizes[name] = size
for node in tlNode.childNodes:
opcodes = []
iclass = ''
vendor = ''
# we are only interested in <instruction>
if node.localName != 'instruction':
continue
# we need the mnemonic attribute
if not ('mnemonic' in node.attributes.keys()):
print("error: no mnemonic given in <instruction>.")
sys.exit(-1)
# check if this instruction was already defined.
# else add it to the global list of mnemonics
mnemonic = node.attributes['mnemonic'].value
if mnemonic in mnm_list:
print("error: multiple declarations of mnemonic='%s'" % mnemonic)
sys.exit(-1)
else:
mnm_list.append(mnemonic)
#
# collect instruction
# - vendor
# - class
#
for n in node.childNodes:
if n.localName == 'vendor':
vendor = (n.firstChild.data).strip();
elif n.localName == 'class':
iclass = n.firstChild.data;
#
# for each opcode definition
#
for n in node.childNodes:
if n.localName != 'opcode':
continue;
opcode = n.firstChild.data.strip();
parts = opcode.split(";");
flags = []
opr = []
pfx = []
opr = []
pfx_c = []
# get cast attribute, if given
if 'cast' in n.attributes.keys():
pfx_c.append( "P_c" + n.attributes['cast'].value )
# get implicit addressing attribute, if given
if 'imp_addr' in n.attributes.keys():
if int( n.attributes['imp_addr'].value ):
pfx_c.append( "P_ImpAddr" )
# get mode attribute, if given
if 'mode' in n.attributes.keys():
v = (n.attributes['mode'].value).strip()
modef = v.split();
for m in modef:
if not (m in pfx_dict):
print("warning: unrecognized mode attribute '%s'" % m)
else:
pfx_c.append(pfx_dict[m])
#
# split opcode definition into
# 1. prefixes (pfx)
# 2. opcode bytes (opc)
# 3. operands
#
if len(parts) == 1:
opc = parts[0].split()
elif len(parts) == 2:
opc = parts[0].split()
opr = parts[1].split()
for o in opc:
if o in pfx_dict:
pfx = parts[0].split()
opc = parts[1].split()
break
elif len(parts) == 3:
pfx = parts[0].split()
opc = parts[1].split()
opr = parts[2].split()
else:
print("error: invalid opcode definition of %s\n" % mnemonic)
sys.exit(-1)
# Convert opcodes to upper case
for i in range(len(opc)):
opc[i] = opc[i].upper()
#
# check for special cases of instruction translation
# and ignore them
#
if mnemonic == 'pause' or \
( mnemonic == 'nop' and opc[0] == '90' ) or \
mnemonic == 'invalid' or \
mnemonic == 'db' :
continue
#
# Convert prefix
#
for p in pfx:
if not ( p in pfx_dict.keys() ):
print("error: invalid prefix specification: %s \n" % pfx)
pfx_c.append( pfx_dict[p] )
if len(pfx) == 0:
pfx_c.append( "P_none" )
pfx = "|".join( pfx_c )
#
# Convert operands
#
opr_c = [ "O_NONE", "O_NONE", "O_NONE" ]
for i in range(len(opr)):
if not (opr[i] in operand_dict.keys()):
print("error: invalid operand declaration: %s\n" % opr[i])
opr_c[i] = "O_" + opr[i]
opr = "%-8s %-8s %s" % (opr_c[0] + ",", opr_c[1] + ",", opr_c[2])
table_sse = ''
table_name = 'itab__1byte'
table_size = 256
table_index = ''
for op in opc:
if op[0:3] == 'SSE':
table_sse = op
elif op == '0F' and len(table_sse):
table_name = "itab__pfx_%s__0f" % table_sse
table_size = 256
table_sse = ''
elif op == '0F':
table_name = "itab__0f"
table_size = 256
elif op[0:5] == '/X87=':
tables[table_name][table_index] = { \
'type' : 'grp_x87', \
'name' : "%s__op_%s__x87" % (table_name, table_index) \
}
table_name = tables[table_name][table_index]['name']
table_index = "%02X" % int(op[5:7], 16)
table_size = 64
elif op[0:4] == '/RM=':
tables[table_name][table_index] = { \
'type' : 'grp_rm', \
'name' : "%s__op_%s__rm" % (table_name, table_index) \
}
table_name = tables[table_name][table_index]['name']
table_index = "%02X" % int(op[4:6])
table_size = 8
elif op[0:5] == '/MOD=':
tables[table_name][table_index] = { \
'type' : 'grp_mod', \
'name' : "%s__op_%s__mod" % (table_name, table_index) \
}
table_name = tables[table_name][table_index]['name']
if len(op) == 8:
v = op[5:8]
else:
v = op[5:7]
mod_dict = { '!11' : 0, '11' : 1 }
table_index = "%02X" % int(mod_dict[v])
table_size = 2
elif op[0:2] == '/O':
tables[table_name][table_index] = { \
'type' : 'grp_osize', \
'name' : "%s__op_%s__osize" % (table_name, table_index) \
}
table_name = tables[table_name][table_index]['name']
table_index = "%02X" % int(mode_dict[op[2:4]])
table_size = 3
elif op[0:2] == '/A':
tables[table_name][table_index] = { \
'type' : 'grp_asize', \
'name' : "%s__op_%s__asize" % (table_name, table_index) \
}
table_name = tables[table_name][table_index]['name']
table_index = "%02X" % int(mode_dict[op[2:4]])
table_size = 3
elif op[0:2] == '/M':
tables[table_name][table_index] = { \
'type' : 'grp_mode', \
'name' : "%s__op_%s__mode" % (table_name, table_index) \
}
table_name = tables[table_name][table_index]['name']
table_index = "%02X" % int(mode_dict[op[2:4]])
table_size = 3
elif op[0:6] == '/3DNOW':
table_name = "itab__3dnow"
table_size = 256
elif op[0:1] == '/':
tables[table_name][table_index] = { \
'type' : 'grp_reg', \
'name' : "%s__op_%s__reg" % (table_name, table_index) \
}
table_name = tables[table_name][table_index]['name']
table_index = "%02X" % int(op[1:2])
table_size = 8
else:
table_index = op
mktab(table_name, table_size)
if len(vendor):
tables[table_name][table_index] = { \
'type' : 'grp_vendor', \
'name' : "%s__op_%s__vendor" % (table_name, table_index) \
}
table_name = tables[table_name][table_index]['name']
table_index = vend_dict[vendor]
table_size = 2
mktab(table_name, table_size)
tables[table_name][table_index] = { \
'type' : 'leaf', \
'name' : mnemonic, \
'pfx' : pfx, \
'opr' : opr, \
'flags' : flags \
}
# ---------------------------------------------------------------------
# Generate itab.h
# ---------------------------------------------------------------------
f = open("itab.h", "w")
f.write('''
/* itab.h -- auto generated by opgen.py, do not edit. */
#ifndef UD_ITAB_H
#define UD_ITAB_H
''')
#
# Generate enumeration of size constants
#
siz_constants.sort()
f.write('''
''')
f.write("\nenum ud_itab_vendor_index {\n" )
f.write(" ITAB__VENDOR_INDX__AMD,\n" )
f.write(" ITAB__VENDOR_INDX__INTEL,\n" )
f.write("};\n\n")
f.write("\nenum ud_itab_mode_index {\n" )
f.write(" ITAB__MODE_INDX__16,\n" )
f.write(" ITAB__MODE_INDX__32,\n" )
f.write(" ITAB__MODE_INDX__64\n" )
f.write("};\n\n")
f.write("\nenum ud_itab_mod_index {\n" )
f.write(" ITAB__MOD_INDX__NOT_11,\n" )
f.write(" ITAB__MOD_INDX__11\n" )
f.write("};\n\n")
#
# Generate enumeration of the tables
#
table_names = tables.keys()
table_names = sorted(table_names)
f.write( "\nenum ud_itab_index {\n" )
for name in table_names:
f.write(" %s,\n" % name.upper() );
f.write( "};\n\n" )
#
# Generate mnemonics list
#
f.write("\nenum ud_mnemonic_code {\n")
for m in mnm_list:
f.write(" UD_I%s,\n" % m)
for m in spl_mnm_types:
f.write(" UD_I%s,\n" % m)
f.write("};\n\n")
#
# Generate struct defs
#
f.write( \
'''
extern const char* ud_mnemonics_str[];;
extern struct ud_itab_entry* ud_itab_list[];
''' )
f.write("#endif\n")
f.close()
# ---------------------------------------------------------------------
# Generate itab.c
# ---------------------------------------------------------------------
f = open("itab.c", "w")
f.write('''
/* itab.c -- auto generated by opgen.py, do not edit. */
#include "types.h"
#include "decode.h"
#include "itab.h"
''')
#
# generate mnemonic list
#
f.write("const char * ud_mnemonics_str[] = {\n")
for m in mnm_list:
f.write(" \"%s\",\n" % m )
f.write("};\n\n")
#
# generate instruction tables
#
f.write("\n")
for t in table_names:
f.write("\nstatic struct ud_itab_entry " + t.lower() + "[%d] = {\n" % table_sizes[t]);
for i in range(int(table_sizes[t])):
index = "%02X" % i
if index in tables[t]:
f.write(centry(index, tables[t][index]))
else:
f.write(centry(index,{"type":"invalid"}))
f.write("};\n");
#
# write the instruction table list
#
f.write( "\n/* the order of this table matches enum ud_itab_index */")
f.write( "\nstruct ud_itab_entry * ud_itab_list[] = {\n" )
for name in table_names:
f.write( " %s,\n" % name.lower() )
f.write( "};\n" );
f.close();
# vim:expandtab
# vim:sw=4
# vim:ts=4
| |
"""Fields tests."""
import datetime
import time
import six
import unittest2 as unittest
from domain_models import models
from domain_models import collections
from domain_models import fields
from domain_models import errors
class RelatedModel(models.DomainModel):
"""Example model that is used for testing relations."""
class ExampleModel(models.DomainModel):
"""Example model."""
field = fields.Field()
field_default = fields.Field(default=123)
field_default_callable = fields.Field(default=time.time)
field_required_default = fields.Field(default=123, required=True)
bool_field = fields.Bool()
int_field = fields.Int()
float_field = fields.Float()
string_field = fields.String()
binary_field = fields.Binary()
date_field = fields.Date()
datetime_field = fields.DateTime()
model_field = fields.Model(RelatedModel)
collection_field = fields.Collection(RelatedModel)
class RequiredFieldModel(models.DomainModel):
"""Example model for required fields."""
field_required = fields.Field(required=True)
class FieldTest(unittest.TestCase):
"""Base field tests."""
def test_get_set(self):
"""Test getting and setting of field value."""
model = ExampleModel()
model.field = 123
self.assertEquals(model.field, 123)
def test_reset_value(self):
"""Test resetting of value."""
model = ExampleModel()
model.field = 'Some value'
model.field = None
self.assertIsNone(model.field)
def test_model_cls_could_not_be_rebound(self):
"""Test that field model class could not be rebound."""
class Model(models.DomainModel):
"""Test model."""
field = fields.Field()
field.bind_model_cls(Model)
with self.assertRaises(errors.Error):
field.bind_model_cls(Model)
def test_field_default(self):
"""Test field default value."""
model = ExampleModel()
self.assertEquals(model.field_default, 123)
def test_field_default_callable(self):
"""Test field default callable value."""
model1 = ExampleModel()
time.sleep(0.1)
model2 = ExampleModel()
self.assertGreater(model2.field_default_callable,
model1.field_default_callable)
def test_field_required(self):
"""Test required field with default value."""
model = ExampleModel()
self.assertEquals(model.field_required_default, 123)
def test_field_required_set_valid(self):
"""Test required field with valid value."""
model = ExampleModel()
model.field_required_default = False
self.assertIs(model.field_required_default, False)
def test_field_required_set_invalid(self):
"""Test required field with invalid value."""
model = ExampleModel()
with self.assertRaises(AttributeError):
model.field_required_default = None
def test_field_required_init_valid_model(self):
"""Test required field with valid value as model keyword."""
model = RequiredFieldModel(field_required=False)
self.assertIs(model.field_required, False)
model.field_required = 123
self.assertEqual(model.field_required, 123)
def test_field_required_init_invalid_model(self):
"""Test required field with invalid value as model keyword."""
with self.assertRaises(AttributeError):
RequiredFieldModel()
with self.assertRaises(AttributeError):
RequiredFieldModel(field_required=None)
class BoolTest(unittest.TestCase):
"""Bool field tests."""
def test_set_value(self):
"""Test setting of correct value."""
model = ExampleModel()
model.bool_field = True
self.assertIs(model.bool_field, True)
def test_set_value_conversion_int(self):
"""Test setting of correct value."""
model = ExampleModel()
model.bool_field = 1
self.assertIs(model.bool_field, True)
def test_set_value_conversion_str(self):
"""Test setting of correct value."""
model = ExampleModel()
model.bool_field = '1'
self.assertIs(model.bool_field, True)
def test_set_value_conversion_empty_str(self):
"""Test setting of correct value."""
model = ExampleModel()
model.bool_field = ''
self.assertIs(model.bool_field, False)
def test_reset_value(self):
"""Test resetting of value."""
model = ExampleModel()
model.bool_field = True
model.bool_field = None
self.assertIsNone(model.bool_field)
class IntTest(unittest.TestCase):
"""Int field tests."""
def test_set_value(self):
"""Test setting of correct value."""
model = ExampleModel()
number = 2
model.int_field = number
self.assertEqual(model.int_field, number)
def test_set_value_conversion_float(self):
"""Test setting of correct value."""
model = ExampleModel()
model.int_field = 1.0
self.assertEqual(model.int_field, 1)
def test_set_value_conversion_str(self):
"""Test setting of correct value."""
model = ExampleModel()
model.int_field = '1'
self.assertEqual(model.int_field, 1)
def test_reset_value(self):
"""Test resetting of value."""
model = ExampleModel()
number = 2
model.int_field = number
model.int_field = None
self.assertIsNone(model.int_field)
def test_set_incorrect(self):
"""Test setting of incorrect value."""
model = ExampleModel()
with self.assertRaises(TypeError):
model.int_field = object()
with self.assertRaises(ValueError):
model.int_field = ''
class FloatTest(unittest.TestCase):
"""Float field tests."""
def test_set_value(self):
"""Test setting of correct value."""
model = ExampleModel()
number = 2.22
model.float_field = number
self.assertEqual(model.float_field, number)
def test_set_value_conversion_str(self):
"""Test setting of correct value."""
model = ExampleModel()
model.float_field = '2.22'
self.assertEqual(model.float_field, 2.22)
def test_reset_value(self):
"""Test resetting of value."""
model = ExampleModel()
number = 2.22
model.float_field = number
model.float_field = None
self.assertIsNone(model.float_field)
def test_set_incorrect(self):
"""Test setting of incorrect value."""
model = ExampleModel()
with self.assertRaises(TypeError):
model.float_field = object()
class StringTest(unittest.TestCase):
"""String field tests."""
def test_set_value(self):
"""Test setting of correct value."""
model = ExampleModel()
data = 'Hello, world!'
model.string_field = data
self.assertEqual(model.string_field, data)
def test_set_value_conversion_float(self):
"""Test setting of correct value."""
model = ExampleModel()
model.string_field = 2.22
self.assertEqual(model.string_field, '2.22')
def test_reset_value(self):
"""Test resetting of value."""
model = ExampleModel()
data = 'Hello, world!'
model.string_field = data
model.string_field = None
self.assertIsNone(model.string_field)
class BinaryTest(unittest.TestCase):
"""Binary field tests."""
def test_set_value(self):
"""Test setting of correct value."""
model = ExampleModel()
data = six.b('Hello, world!')
model.binary_field = data
self.assertEqual(model.binary_field, data)
def test_reset_value(self):
"""Test resetting of value."""
model = ExampleModel()
data = six.b('Hello, world!')
model.binary_field = data
model.binary_field = None
self.assertIsNone(model.binary_field)
class DateTest(unittest.TestCase):
"""Date field tests."""
def test_set_value(self):
"""Test setting of correct value."""
model = ExampleModel()
today = datetime.date.today()
model.date_field = today
self.assertEqual(model.date_field, today)
def test_reset_value(self):
"""Test resetting of value."""
model = ExampleModel()
today = datetime.date.today()
model.date_field = today
model.date_field = None
self.assertIsNone(model.date_field)
def test_set_incorrect(self):
"""Test setting of incorrect value."""
model = ExampleModel()
some_object = object()
with self.assertRaises(TypeError):
model.date_field = some_object
class DateTimeTest(unittest.TestCase):
"""Date and time field tests."""
def test_set_value(self):
"""Test setting of correct value."""
model = ExampleModel()
now = datetime.datetime.utcnow()
model.datetime_field = now
self.assertEqual(model.datetime_field, now)
def test_reset_value(self):
"""Test resetting of value."""
model = ExampleModel()
now = datetime.datetime.utcnow()
model.datetime_field = now
model.datetime_field = None
self.assertIsNone(model.datetime_field)
def test_set_incorrect(self):
"""Test setting of incorrect value."""
model = ExampleModel()
some_object = object()
with self.assertRaises(TypeError):
model.datetime_field = some_object
class ModelTest(unittest.TestCase):
"""Model field tests."""
def test_set_value(self):
"""Test setting of correct value."""
model = ExampleModel()
related_model = RelatedModel()
model.model_field = related_model
self.assertEqual(model.model_field, related_model)
def test_reset_value(self):
"""Test resetting of value."""
model = ExampleModel()
related_model = RelatedModel()
model.model_field = related_model
model.model_field = None
self.assertIsNone(model.model_field)
def test_set_incorrect(self):
"""Test setting of incorrect value."""
model = ExampleModel()
some_object = object()
with self.assertRaises(TypeError):
model.model_field = some_object
class CollectionTest(unittest.TestCase):
"""Collection field tests."""
def test_set_value(self):
"""Test setting of correct value."""
model = ExampleModel()
related_model = RelatedModel()
model.collection_field = [related_model]
self.assertEqual(model.collection_field, [related_model])
self.assertIsInstance(model.collection_field, collections.Collection)
def test_set_collection(self):
"""Test setting of collection."""
model = ExampleModel()
related_model = RelatedModel()
some_collection = RelatedModel.Collection([related_model])
model.collection_field = some_collection
self.assertIs(model.collection_field, some_collection)
def test_set_child_collection(self):
"""Test setting of collection."""
class RelatedModelChild(RelatedModel):
"""Child class of related model."""
model = ExampleModel()
related_model = RelatedModelChild()
some_collection = RelatedModelChild.Collection([related_model])
model.collection_field = some_collection
self.assertIsNot(model.collection_field, some_collection)
self.assertIsInstance(model.collection_field, RelatedModel.Collection)
self.assertIs(model.collection_field.value_type, RelatedModel)
self.assertEqual(model.collection_field, [related_model])
def test_reset_value(self):
"""Test resetting of value."""
model = ExampleModel()
related_model = RelatedModel()
model.collection_field = [related_model]
model.collection_field = None
self.assertIsNone(model.collection_field)
def test_set_incorrect(self):
"""Test setting of incorrect value."""
model = ExampleModel()
some_object = object()
with self.assertRaises(TypeError):
model.collection_field = [some_object]
| |
# orm/attributes.py
# Copyright (C) 2005-2014 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Defines instrumentation for class attributes and their interaction
with instances.
This module is usually not directly visible to user applications, but
defines a large part of the ORM's interactivity.
"""
import operator
from .. import util, event, inspection
from . import interfaces, collections, exc as orm_exc
from .base import instance_state, instance_dict, manager_of_class
from .base import PASSIVE_NO_RESULT, ATTR_WAS_SET, ATTR_EMPTY, NO_VALUE,\
NEVER_SET, NO_CHANGE, CALLABLES_OK, SQL_OK, RELATED_OBJECT_OK,\
INIT_OK, NON_PERSISTENT_OK, LOAD_AGAINST_COMMITTED, PASSIVE_OFF,\
PASSIVE_RETURN_NEVER_SET, PASSIVE_NO_INITIALIZE, PASSIVE_NO_FETCH,\
PASSIVE_NO_FETCH_RELATED, PASSIVE_ONLY_PERSISTENT, NO_AUTOFLUSH
from .base import state_str, instance_str
@inspection._self_inspects
class QueryableAttribute(interfaces._MappedAttribute,
interfaces._InspectionAttr,
interfaces.PropComparator):
"""Base class for :term:`descriptor` objects that intercept
attribute events on behalf of a :class:`.MapperProperty`
object. The actual :class:`.MapperProperty` is accessible
via the :attr:`.QueryableAttribute.property`
attribute.
.. seealso::
:class:`.InstrumentedAttribute`
:class:`.MapperProperty`
:attr:`.Mapper.all_orm_descriptors`
:attr:`.Mapper.attrs`
"""
is_attribute = True
def __init__(self, class_, key, impl=None,
comparator=None, parententity=None,
of_type=None):
self.class_ = class_
self.key = key
self.impl = impl
self.comparator = comparator
self._parententity = parententity
self._of_type = of_type
manager = manager_of_class(class_)
# manager is None in the case of AliasedClass
if manager:
# propagate existing event listeners from
# immediate superclass
for base in manager._bases:
if key in base:
self.dispatch._update(base[key].dispatch)
@util.memoized_property
def _supports_population(self):
return self.impl.supports_population
def get_history(self, instance, passive=PASSIVE_OFF):
return self.impl.get_history(instance_state(instance),
instance_dict(instance), passive)
def __selectable__(self):
# TODO: conditionally attach this method based on clause_element ?
return self
@util.memoized_property
def info(self):
"""Return the 'info' dictionary for the underlying SQL element.
The behavior here is as follows:
* If the attribute is a column-mapped property, i.e.
:class:`.ColumnProperty`, which is mapped directly
to a schema-level :class:`.Column` object, this attribute
will return the :attr:`.SchemaItem.info` dictionary associated
with the core-level :class:`.Column` object.
* If the attribute is a :class:`.ColumnProperty` but is mapped to
any other kind of SQL expression other than a :class:`.Column`,
the attribute will refer to the :attr:`.MapperProperty.info` dictionary
associated directly with the :class:`.ColumnProperty`, assuming the SQL
expression itself does not have it's own ``.info`` attribute
(which should be the case, unless a user-defined SQL construct
has defined one).
* If the attribute refers to any other kind of :class:`.MapperProperty`,
including :class:`.RelationshipProperty`, the attribute will refer
to the :attr:`.MapperProperty.info` dictionary associated with
that :class:`.MapperProperty`.
* To access the :attr:`.MapperProperty.info` dictionary of the :class:`.MapperProperty`
unconditionally, including for a :class:`.ColumnProperty` that's
associated directly with a :class:`.schema.Column`, the attribute
can be referred to using :attr:`.QueryableAttribute.property`
attribute, as ``MyClass.someattribute.property.info``.
.. versionadded:: 0.8.0
.. seealso::
:attr:`.SchemaItem.info`
:attr:`.MapperProperty.info`
"""
return self.comparator.info
@util.memoized_property
def parent(self):
"""Return an inspection instance representing the parent.
This will be either an instance of :class:`.Mapper`
or :class:`.AliasedInsp`, depending upon the nature
of the parent entity which this attribute is associated
with.
"""
return inspection.inspect(self._parententity)
@property
def expression(self):
return self.comparator.__clause_element__()
def __clause_element__(self):
return self.comparator.__clause_element__()
def _query_clause_element(self):
"""like __clause_element__(), but called specifically
by :class:`.Query` to allow special behavior."""
return self.comparator._query_clause_element()
def adapt_to_entity(self, adapt_to_entity):
assert not self._of_type
return self.__class__(adapt_to_entity.entity, self.key, impl=self.impl,
comparator=self.comparator.adapt_to_entity(adapt_to_entity),
parententity=adapt_to_entity)
def of_type(self, cls):
return QueryableAttribute(
self.class_,
self.key,
self.impl,
self.comparator.of_type(cls),
self._parententity,
of_type=cls)
def label(self, name):
return self._query_clause_element().label(name)
def operate(self, op, *other, **kwargs):
return op(self.comparator, *other, **kwargs)
def reverse_operate(self, op, other, **kwargs):
return op(other, self.comparator, **kwargs)
def hasparent(self, state, optimistic=False):
return self.impl.hasparent(state, optimistic=optimistic) is not False
def __getattr__(self, key):
try:
return getattr(self.comparator, key)
except AttributeError:
raise AttributeError(
'Neither %r object nor %r object associated with %s '
'has an attribute %r' % (
type(self).__name__,
type(self.comparator).__name__,
self,
key)
)
def __str__(self):
return "%s.%s" % (self.class_.__name__, self.key)
@util.memoized_property
def property(self):
"""Return the :class:`.MapperProperty` associated with this
:class:`.QueryableAttribute`.
Return values here will commonly be instances of
:class:`.ColumnProperty` or :class:`.RelationshipProperty`.
"""
return self.comparator.property
class InstrumentedAttribute(QueryableAttribute):
"""Class bound instrumented attribute which adds basic
:term:`descriptor` methods.
See :class:`.QueryableAttribute` for a description of most features.
"""
def __set__(self, instance, value):
self.impl.set(instance_state(instance),
instance_dict(instance), value, None)
def __delete__(self, instance):
self.impl.delete(instance_state(instance), instance_dict(instance))
def __get__(self, instance, owner):
if instance is None:
return self
dict_ = instance_dict(instance)
if self._supports_population and self.key in dict_:
return dict_[self.key]
else:
return self.impl.get(instance_state(instance), dict_)
def create_proxied_attribute(descriptor):
"""Create an QueryableAttribute / user descriptor hybrid.
Returns a new QueryableAttribute type that delegates descriptor
behavior and getattr() to the given descriptor.
"""
# TODO: can move this to descriptor_props if the need for this
# function is removed from ext/hybrid.py
class Proxy(QueryableAttribute):
"""Presents the :class:`.QueryableAttribute` interface as a
proxy on top of a Python descriptor / :class:`.PropComparator`
combination.
"""
def __init__(self, class_, key, descriptor,
comparator,
adapt_to_entity=None, doc=None,
original_property=None):
self.class_ = class_
self.key = key
self.descriptor = descriptor
self.original_property = original_property
self._comparator = comparator
self._adapt_to_entity = adapt_to_entity
self.__doc__ = doc
@property
def property(self):
return self.comparator.property
@util.memoized_property
def comparator(self):
if util.callable(self._comparator):
self._comparator = self._comparator()
if self._adapt_to_entity:
self._comparator = self._comparator.adapt_to_entity(
self._adapt_to_entity)
return self._comparator
def adapt_to_entity(self, adapt_to_entity):
return self.__class__(adapt_to_entity.entity, self.key, self.descriptor,
self._comparator,
adapt_to_entity)
def __get__(self, instance, owner):
if instance is None:
return self
else:
return self.descriptor.__get__(instance, owner)
def __str__(self):
return "%s.%s" % (self.class_.__name__, self.key)
def __getattr__(self, attribute):
"""Delegate __getattr__ to the original descriptor and/or
comparator."""
try:
return getattr(descriptor, attribute)
except AttributeError:
try:
return getattr(self.comparator, attribute)
except AttributeError:
raise AttributeError(
'Neither %r object nor %r object associated with %s '
'has an attribute %r' % (
type(descriptor).__name__,
type(self.comparator).__name__,
self,
attribute)
)
Proxy.__name__ = type(descriptor).__name__ + 'Proxy'
util.monkeypatch_proxied_specials(Proxy, type(descriptor),
name='descriptor',
from_instance=descriptor)
return Proxy
OP_REMOVE = util.symbol("REMOVE")
OP_APPEND = util.symbol("APPEND")
OP_REPLACE = util.symbol("REPLACE")
class Event(object):
"""A token propagated throughout the course of a chain of attribute
events.
Serves as an indicator of the source of the event and also provides
a means of controlling propagation across a chain of attribute
operations.
The :class:`.Event` object is sent as the ``initiator`` argument
when dealing with the :meth:`.AttributeEvents.append`,
:meth:`.AttributeEvents.set`,
and :meth:`.AttributeEvents.remove` events.
The :class:`.Event` object is currently interpreted by the backref
event handlers, and is used to control the propagation of operations
across two mutually-dependent attributes.
.. versionadded:: 0.9.0
"""
impl = None
"""The :class:`.AttributeImpl` which is the current event initiator.
"""
op = None
"""The symbol :attr:`.OP_APPEND`, :attr:`.OP_REMOVE` or :attr:`.OP_REPLACE`,
indicating the source operation.
"""
def __init__(self, attribute_impl, op):
self.impl = attribute_impl
self.op = op
self.parent_token = self.impl.parent_token
@property
def key(self):
return self.impl.key
def hasparent(self, state):
return self.impl.hasparent(state)
class AttributeImpl(object):
"""internal implementation for instrumented attributes."""
def __init__(self, class_, key,
callable_, dispatch, trackparent=False, extension=None,
compare_function=None, active_history=False,
parent_token=None, expire_missing=True,
send_modified_events=True,
**kwargs):
"""Construct an AttributeImpl.
\class_
associated class
key
string name of the attribute
\callable_
optional function which generates a callable based on a parent
instance, which produces the "default" values for a scalar or
collection attribute when it's first accessed, if not present
already.
trackparent
if True, attempt to track if an instance has a parent attached
to it via this attribute.
extension
a single or list of AttributeExtension object(s) which will
receive set/delete/append/remove/etc. events. Deprecated.
The event package is now used.
compare_function
a function that compares two values which are normally
assignable to this attribute.
active_history
indicates that get_history() should always return the "old" value,
even if it means executing a lazy callable upon attribute change.
parent_token
Usually references the MapperProperty, used as a key for
the hasparent() function to identify an "owning" attribute.
Allows multiple AttributeImpls to all match a single
owner attribute.
expire_missing
if False, don't add an "expiry" callable to this attribute
during state.expire_attributes(None), if no value is present
for this key.
send_modified_events
if False, the InstanceState._modified_event method will have no effect;
this means the attribute will never show up as changed in a
history entry.
"""
self.class_ = class_
self.key = key
self.callable_ = callable_
self.dispatch = dispatch
self.trackparent = trackparent
self.parent_token = parent_token or self
self.send_modified_events = send_modified_events
if compare_function is None:
self.is_equal = operator.eq
else:
self.is_equal = compare_function
# TODO: pass in the manager here
# instead of doing a lookup
attr = manager_of_class(class_)[key]
for ext in util.to_list(extension or []):
ext._adapt_listener(attr, ext)
if active_history:
self.dispatch._active_history = True
self.expire_missing = expire_missing
def __str__(self):
return "%s.%s" % (self.class_.__name__, self.key)
def _get_active_history(self):
"""Backwards compat for impl.active_history"""
return self.dispatch._active_history
def _set_active_history(self, value):
self.dispatch._active_history = value
active_history = property(_get_active_history, _set_active_history)
def hasparent(self, state, optimistic=False):
"""Return the boolean value of a `hasparent` flag attached to
the given state.
The `optimistic` flag determines what the default return value
should be if no `hasparent` flag can be located.
As this function is used to determine if an instance is an
*orphan*, instances that were loaded from storage should be
assumed to not be orphans, until a True/False value for this
flag is set.
An instance attribute that is loaded by a callable function
will also not have a `hasparent` flag.
"""
msg = "This AttributeImpl is not configured to track parents."
assert self.trackparent, msg
return state.parents.get(id(self.parent_token), optimistic) \
is not False
def sethasparent(self, state, parent_state, value):
"""Set a boolean flag on the given item corresponding to
whether or not it is attached to a parent object via the
attribute represented by this ``InstrumentedAttribute``.
"""
msg = "This AttributeImpl is not configured to track parents."
assert self.trackparent, msg
id_ = id(self.parent_token)
if value:
state.parents[id_] = parent_state
else:
if id_ in state.parents:
last_parent = state.parents[id_]
if last_parent is not False and \
last_parent.key != parent_state.key:
if last_parent.obj() is None:
raise orm_exc.StaleDataError(
"Removing state %s from parent "
"state %s along attribute '%s', "
"but the parent record "
"has gone stale, can't be sure this "
"is the most recent parent." %
(state_str(state),
state_str(parent_state),
self.key))
return
state.parents[id_] = False
def set_callable(self, state, callable_):
"""Set a callable function for this attribute on the given object.
This callable will be executed when the attribute is next
accessed, and is assumed to construct part of the instances
previously stored state. When its value or values are loaded,
they will be established as part of the instance's *committed
state*. While *trackparent* information will be assembled for
these instances, attribute-level event handlers will not be
fired.
The callable overrides the class level callable set in the
``InstrumentedAttribute`` constructor.
"""
state.callables[self.key] = callable_
def get_history(self, state, dict_, passive=PASSIVE_OFF):
raise NotImplementedError()
def get_all_pending(self, state, dict_):
"""Return a list of tuples of (state, obj)
for all objects in this attribute's current state
+ history.
Only applies to object-based attributes.
This is an inlining of existing functionality
which roughly corresponds to:
get_state_history(
state,
key,
passive=PASSIVE_NO_INITIALIZE).sum()
"""
raise NotImplementedError()
def initialize(self, state, dict_):
"""Initialize the given state's attribute with an empty value."""
dict_[self.key] = None
return None
def get(self, state, dict_, passive=PASSIVE_OFF):
"""Retrieve a value from the given object.
If a callable is assembled on this object's attribute, and
passive is False, the callable will be executed and the
resulting value will be set as the new value for this attribute.
"""
if self.key in dict_:
return dict_[self.key]
else:
# if history present, don't load
key = self.key
if key not in state.committed_state or \
state.committed_state[key] is NEVER_SET:
if not passive & CALLABLES_OK:
return PASSIVE_NO_RESULT
if key in state.callables:
callable_ = state.callables[key]
value = callable_(state, passive)
elif self.callable_:
value = self.callable_(state, passive)
else:
value = ATTR_EMPTY
if value is PASSIVE_NO_RESULT or value is NEVER_SET:
return value
elif value is ATTR_WAS_SET:
try:
return dict_[key]
except KeyError:
# TODO: no test coverage here.
raise KeyError(
"Deferred loader for attribute "
"%r failed to populate "
"correctly" % key)
elif value is not ATTR_EMPTY:
return self.set_committed_value(state, dict_, value)
if not passive & INIT_OK:
return NEVER_SET
else:
# Return a new, empty value
return self.initialize(state, dict_)
def append(self, state, dict_, value, initiator, passive=PASSIVE_OFF):
self.set(state, dict_, value, initiator, passive=passive)
def remove(self, state, dict_, value, initiator, passive=PASSIVE_OFF):
self.set(state, dict_, None, initiator,
passive=passive, check_old=value)
def pop(self, state, dict_, value, initiator, passive=PASSIVE_OFF):
self.set(state, dict_, None, initiator,
passive=passive, check_old=value, pop=True)
def set(self, state, dict_, value, initiator,
passive=PASSIVE_OFF, check_old=None, pop=False):
raise NotImplementedError()
def get_committed_value(self, state, dict_, passive=PASSIVE_OFF):
"""return the unchanged value of this attribute"""
if self.key in state.committed_state:
value = state.committed_state[self.key]
if value is NO_VALUE:
return None
else:
return value
else:
return self.get(state, dict_, passive=passive)
def set_committed_value(self, state, dict_, value):
"""set an attribute value on the given instance and 'commit' it."""
dict_[self.key] = value
state._commit(dict_, [self.key])
return value
class ScalarAttributeImpl(AttributeImpl):
"""represents a scalar value-holding InstrumentedAttribute."""
accepts_scalar_loader = True
uses_objects = False
supports_population = True
collection = False
def delete(self, state, dict_):
# TODO: catch key errors, convert to attributeerror?
if self.dispatch._active_history:
old = self.get(state, dict_, PASSIVE_RETURN_NEVER_SET)
else:
old = dict_.get(self.key, NO_VALUE)
if self.dispatch.remove:
self.fire_remove_event(state, dict_, old, self._remove_token)
state._modified_event(dict_, self, old)
del dict_[self.key]
def get_history(self, state, dict_, passive=PASSIVE_OFF):
if self.key in dict_:
return History.from_scalar_attribute(self, state, dict_[self.key])
else:
if passive & INIT_OK:
passive ^= INIT_OK
current = self.get(state, dict_, passive=passive)
if current is PASSIVE_NO_RESULT:
return HISTORY_BLANK
else:
return History.from_scalar_attribute(self, state, current)
def set(self, state, dict_, value, initiator,
passive=PASSIVE_OFF, check_old=None, pop=False):
if self.dispatch._active_history:
old = self.get(state, dict_, PASSIVE_RETURN_NEVER_SET)
else:
old = dict_.get(self.key, NO_VALUE)
if self.dispatch.set:
value = self.fire_replace_event(state, dict_,
value, old, initiator)
state._modified_event(dict_, self, old)
dict_[self.key] = value
@util.memoized_property
def _replace_token(self):
return Event(self, OP_REPLACE)
@util.memoized_property
def _append_token(self):
return Event(self, OP_REPLACE)
@util.memoized_property
def _remove_token(self):
return Event(self, OP_REMOVE)
def fire_replace_event(self, state, dict_, value, previous, initiator):
for fn in self.dispatch.set:
value = fn(state, value, previous, initiator or self._replace_token)
return value
def fire_remove_event(self, state, dict_, value, initiator):
for fn in self.dispatch.remove:
fn(state, value, initiator or self._remove_token)
@property
def type(self):
self.property.columns[0].type
class ScalarObjectAttributeImpl(ScalarAttributeImpl):
"""represents a scalar-holding InstrumentedAttribute,
where the target object is also instrumented.
Adds events to delete/set operations.
"""
accepts_scalar_loader = False
uses_objects = True
supports_population = True
collection = False
def delete(self, state, dict_):
old = self.get(state, dict_)
self.fire_remove_event(state, dict_, old, self._remove_token)
del dict_[self.key]
def get_history(self, state, dict_, passive=PASSIVE_OFF):
if self.key in dict_:
return History.from_object_attribute(self, state, dict_[self.key])
else:
if passive & INIT_OK:
passive ^= INIT_OK
current = self.get(state, dict_, passive=passive)
if current is PASSIVE_NO_RESULT:
return HISTORY_BLANK
else:
return History.from_object_attribute(self, state, current)
def get_all_pending(self, state, dict_):
if self.key in dict_:
current = dict_[self.key]
if current is not None:
ret = [(instance_state(current), current)]
else:
ret = [(None, None)]
if self.key in state.committed_state:
original = state.committed_state[self.key]
if original not in (NEVER_SET, PASSIVE_NO_RESULT, None) and \
original is not current:
ret.append((instance_state(original), original))
return ret
else:
return []
def set(self, state, dict_, value, initiator,
passive=PASSIVE_OFF, check_old=None, pop=False):
"""Set a value on the given InstanceState.
"""
if self.dispatch._active_history:
old = self.get(state, dict_, passive=PASSIVE_ONLY_PERSISTENT | NO_AUTOFLUSH)
else:
old = self.get(state, dict_, passive=PASSIVE_NO_FETCH)
if check_old is not None and \
old is not PASSIVE_NO_RESULT and \
check_old is not old:
if pop:
return
else:
raise ValueError(
"Object %s not associated with %s on attribute '%s'" % (
instance_str(check_old),
state_str(state),
self.key
))
value = self.fire_replace_event(state, dict_, value, old, initiator)
dict_[self.key] = value
def fire_remove_event(self, state, dict_, value, initiator):
if self.trackparent and value is not None:
self.sethasparent(instance_state(value), state, False)
for fn in self.dispatch.remove:
fn(state, value, initiator or self._remove_token)
state._modified_event(dict_, self, value)
def fire_replace_event(self, state, dict_, value, previous, initiator):
if self.trackparent:
if (previous is not value and
previous is not None and
previous is not PASSIVE_NO_RESULT):
self.sethasparent(instance_state(previous), state, False)
for fn in self.dispatch.set:
value = fn(state, value, previous, initiator or self._replace_token)
state._modified_event(dict_, self, previous)
if self.trackparent:
if value is not None:
self.sethasparent(instance_state(value), state, True)
return value
class CollectionAttributeImpl(AttributeImpl):
"""A collection-holding attribute that instruments changes in membership.
Only handles collections of instrumented objects.
InstrumentedCollectionAttribute holds an arbitrary, user-specified
container object (defaulting to a list) and brokers access to the
CollectionAdapter, a "view" onto that object that presents consistent bag
semantics to the orm layer independent of the user data implementation.
"""
accepts_scalar_loader = False
uses_objects = True
supports_population = True
collection = True
def __init__(self, class_, key, callable_, dispatch,
typecallable=None, trackparent=False, extension=None,
copy_function=None, compare_function=None, **kwargs):
super(CollectionAttributeImpl, self).__init__(
class_,
key,
callable_, dispatch,
trackparent=trackparent,
extension=extension,
compare_function=compare_function,
**kwargs)
if copy_function is None:
copy_function = self.__copy
self.copy = copy_function
self.collection_factory = typecallable
def __copy(self, item):
return [y for y in collections.collection_adapter(item)]
def get_history(self, state, dict_, passive=PASSIVE_OFF):
current = self.get(state, dict_, passive=passive)
if current is PASSIVE_NO_RESULT:
return HISTORY_BLANK
else:
return History.from_collection(self, state, current)
def get_all_pending(self, state, dict_):
if self.key not in dict_:
return []
current = dict_[self.key]
current = getattr(current, '_sa_adapter')
if self.key in state.committed_state:
original = state.committed_state[self.key]
if original not in (NO_VALUE, NEVER_SET):
current_states = [((c is not None) and
instance_state(c) or None, c)
for c in current]
original_states = [((c is not None) and
instance_state(c) or None, c)
for c in original]
current_set = dict(current_states)
original_set = dict(original_states)
return \
[(s, o) for s, o in current_states
if s not in original_set] + \
[(s, o) for s, o in current_states
if s in original_set] + \
[(s, o) for s, o in original_states
if s not in current_set]
return [(instance_state(o), o) for o in current]
@util.memoized_property
def _append_token(self):
return Event(self, OP_APPEND)
@util.memoized_property
def _remove_token(self):
return Event(self, OP_REMOVE)
def fire_append_event(self, state, dict_, value, initiator):
for fn in self.dispatch.append:
value = fn(state, value, initiator or self._append_token)
state._modified_event(dict_, self, NEVER_SET, True)
if self.trackparent and value is not None:
self.sethasparent(instance_state(value), state, True)
return value
def fire_pre_remove_event(self, state, dict_, initiator):
state._modified_event(dict_, self, NEVER_SET, True)
def fire_remove_event(self, state, dict_, value, initiator):
if self.trackparent and value is not None:
self.sethasparent(instance_state(value), state, False)
for fn in self.dispatch.remove:
fn(state, value, initiator or self._remove_token)
state._modified_event(dict_, self, NEVER_SET, True)
def delete(self, state, dict_):
if self.key not in dict_:
return
state._modified_event(dict_, self, NEVER_SET, True)
collection = self.get_collection(state, state.dict)
collection.clear_with_event()
# TODO: catch key errors, convert to attributeerror?
del dict_[self.key]
def initialize(self, state, dict_):
"""Initialize this attribute with an empty collection."""
_, user_data = self._initialize_collection(state)
dict_[self.key] = user_data
return user_data
def _initialize_collection(self, state):
return state.manager.initialize_collection(
self.key, state, self.collection_factory)
def append(self, state, dict_, value, initiator, passive=PASSIVE_OFF):
collection = self.get_collection(state, dict_, passive=passive)
if collection is PASSIVE_NO_RESULT:
value = self.fire_append_event(state, dict_, value, initiator)
assert self.key not in dict_, \
"Collection was loaded during event handling."
state._get_pending_mutation(self.key).append(value)
else:
collection.append_with_event(value, initiator)
def remove(self, state, dict_, value, initiator, passive=PASSIVE_OFF):
collection = self.get_collection(state, state.dict, passive=passive)
if collection is PASSIVE_NO_RESULT:
self.fire_remove_event(state, dict_, value, initiator)
assert self.key not in dict_, \
"Collection was loaded during event handling."
state._get_pending_mutation(self.key).remove(value)
else:
collection.remove_with_event(value, initiator)
def pop(self, state, dict_, value, initiator, passive=PASSIVE_OFF):
try:
# TODO: better solution here would be to add
# a "popper" role to collections.py to complement
# "remover".
self.remove(state, dict_, value, initiator, passive=passive)
except (ValueError, KeyError, IndexError):
pass
def set(self, state, dict_, value, initiator,
passive=PASSIVE_OFF, pop=False):
"""Set a value on the given object.
"""
self._set_iterable(
state, dict_, value,
lambda adapter, i: adapter.adapt_like_to_iterable(i))
def _set_iterable(self, state, dict_, iterable, adapter=None):
"""Set a collection value from an iterable of state-bearers.
``adapter`` is an optional callable invoked with a CollectionAdapter
and the iterable. Should return an iterable of state-bearing
instances suitable for appending via a CollectionAdapter. Can be used
for, e.g., adapting an incoming dictionary into an iterator of values
rather than keys.
"""
# pulling a new collection first so that an adaptation exception does
# not trigger a lazy load of the old collection.
new_collection, user_data = self._initialize_collection(state)
if adapter:
new_values = list(adapter(new_collection, iterable))
else:
new_values = list(iterable)
old = self.get(state, dict_, passive=PASSIVE_ONLY_PERSISTENT)
if old is PASSIVE_NO_RESULT:
old = self.initialize(state, dict_)
elif old is iterable:
# ignore re-assignment of the current collection, as happens
# implicitly with in-place operators (foo.collection |= other)
return
# place a copy of "old" in state.committed_state
state._modified_event(dict_, self, old, True)
old_collection = getattr(old, '_sa_adapter')
dict_[self.key] = user_data
collections.bulk_replace(new_values, old_collection, new_collection)
old_collection.unlink(old)
def _invalidate_collection(self, collection):
adapter = getattr(collection, '_sa_adapter')
adapter.invalidated = True
def set_committed_value(self, state, dict_, value):
"""Set an attribute value on the given instance and 'commit' it."""
collection, user_data = self._initialize_collection(state)
if value:
collection.append_multiple_without_event(value)
state.dict[self.key] = user_data
state._commit(dict_, [self.key])
if self.key in state._pending_mutations:
# pending items exist. issue a modified event,
# add/remove new items.
state._modified_event(dict_, self, user_data, True)
pending = state._pending_mutations.pop(self.key)
added = pending.added_items
removed = pending.deleted_items
for item in added:
collection.append_without_event(item)
for item in removed:
collection.remove_without_event(item)
return user_data
def get_collection(self, state, dict_,
user_data=None, passive=PASSIVE_OFF):
"""Retrieve the CollectionAdapter associated with the given state.
Creates a new CollectionAdapter if one does not exist.
"""
if user_data is None:
user_data = self.get(state, dict_, passive=passive)
if user_data is PASSIVE_NO_RESULT:
return user_data
return getattr(user_data, '_sa_adapter')
def backref_listeners(attribute, key, uselist):
"""Apply listeners to synchronize a two-way relationship."""
# use easily recognizable names for stack traces
parent_token = attribute.impl.parent_token
parent_impl = attribute.impl
def _acceptable_key_err(child_state, initiator, child_impl):
raise ValueError(
"Bidirectional attribute conflict detected: "
'Passing object %s to attribute "%s" '
'triggers a modify event on attribute "%s" '
'via the backref "%s".' % (
state_str(child_state),
initiator.parent_token,
child_impl.parent_token,
attribute.impl.parent_token
)
)
def emit_backref_from_scalar_set_event(state, child, oldchild, initiator):
if oldchild is child:
return child
if oldchild is not None and oldchild is not PASSIVE_NO_RESULT:
# With lazy=None, there's no guarantee that the full collection is
# present when updating via a backref.
old_state, old_dict = instance_state(oldchild),\
instance_dict(oldchild)
impl = old_state.manager[key].impl
if initiator.impl is not impl or \
initiator.op not in (OP_REPLACE, OP_REMOVE):
impl.pop(old_state,
old_dict,
state.obj(),
parent_impl._append_token,
passive=PASSIVE_NO_FETCH)
if child is not None:
child_state, child_dict = instance_state(child),\
instance_dict(child)
child_impl = child_state.manager[key].impl
if initiator.parent_token is not parent_token and \
initiator.parent_token is not child_impl.parent_token:
_acceptable_key_err(state, initiator, child_impl)
elif initiator.impl is not child_impl or \
initiator.op not in (OP_APPEND, OP_REPLACE):
child_impl.append(
child_state,
child_dict,
state.obj(),
initiator,
passive=PASSIVE_NO_FETCH)
return child
def emit_backref_from_collection_append_event(state, child, initiator):
if child is None:
return
child_state, child_dict = instance_state(child), \
instance_dict(child)
child_impl = child_state.manager[key].impl
if initiator.parent_token is not parent_token and \
initiator.parent_token is not child_impl.parent_token:
_acceptable_key_err(state, initiator, child_impl)
elif initiator.impl is not child_impl or \
initiator.op not in (OP_APPEND, OP_REPLACE):
child_impl.append(
child_state,
child_dict,
state.obj(),
initiator,
passive=PASSIVE_NO_FETCH)
return child
def emit_backref_from_collection_remove_event(state, child, initiator):
if child is not None:
child_state, child_dict = instance_state(child),\
instance_dict(child)
child_impl = child_state.manager[key].impl
if initiator.impl is not child_impl or \
initiator.op not in (OP_REMOVE, OP_REPLACE):
child_impl.pop(
child_state,
child_dict,
state.obj(),
initiator,
passive=PASSIVE_NO_FETCH)
if uselist:
event.listen(attribute, "append",
emit_backref_from_collection_append_event,
retval=True, raw=True)
else:
event.listen(attribute, "set",
emit_backref_from_scalar_set_event,
retval=True, raw=True)
# TODO: need coverage in test/orm/ of remove event
event.listen(attribute, "remove",
emit_backref_from_collection_remove_event,
retval=True, raw=True)
_NO_HISTORY = util.symbol('NO_HISTORY')
_NO_STATE_SYMBOLS = frozenset([
id(PASSIVE_NO_RESULT),
id(NO_VALUE),
id(NEVER_SET)])
History = util.namedtuple("History", [
"added", "unchanged", "deleted"
])
class History(History):
"""A 3-tuple of added, unchanged and deleted values,
representing the changes which have occurred on an instrumented
attribute.
The easiest way to get a :class:`.History` object for a particular
attribute on an object is to use the :func:`.inspect` function::
from sqlalchemy import inspect
hist = inspect(myobject).attrs.myattribute.history
Each tuple member is an iterable sequence:
* ``added`` - the collection of items added to the attribute (the first
tuple element).
* ``unchanged`` - the collection of items that have not changed on the
attribute (the second tuple element).
* ``deleted`` - the collection of items that have been removed from the
attribute (the third tuple element).
"""
def __bool__(self):
return self != HISTORY_BLANK
__nonzero__ = __bool__
def empty(self):
"""Return True if this :class:`.History` has no changes
and no existing, unchanged state.
"""
return not bool(
(self.added or self.deleted)
or self.unchanged and self.unchanged != [None]
)
def sum(self):
"""Return a collection of added + unchanged + deleted."""
return (self.added or []) +\
(self.unchanged or []) +\
(self.deleted or [])
def non_deleted(self):
"""Return a collection of added + unchanged."""
return (self.added or []) +\
(self.unchanged or [])
def non_added(self):
"""Return a collection of unchanged + deleted."""
return (self.unchanged or []) +\
(self.deleted or [])
def has_changes(self):
"""Return True if this :class:`.History` has changes."""
return bool(self.added or self.deleted)
def as_state(self):
return History(
[(c is not None)
and instance_state(c) or None
for c in self.added],
[(c is not None)
and instance_state(c) or None
for c in self.unchanged],
[(c is not None)
and instance_state(c) or None
for c in self.deleted],
)
@classmethod
def from_scalar_attribute(cls, attribute, state, current):
original = state.committed_state.get(attribute.key, _NO_HISTORY)
if original is _NO_HISTORY:
if current is NEVER_SET:
return cls((), (), ())
else:
return cls((), [current], ())
# don't let ClauseElement expressions here trip things up
elif attribute.is_equal(current, original) is True:
return cls((), [current], ())
else:
# current convention on native scalars is to not
# include information
# about missing previous value in "deleted", but
# we do include None, which helps in some primary
# key situations
if id(original) in _NO_STATE_SYMBOLS:
deleted = ()
else:
deleted = [original]
if current is NEVER_SET:
return cls((), (), deleted)
else:
return cls([current], (), deleted)
@classmethod
def from_object_attribute(cls, attribute, state, current):
original = state.committed_state.get(attribute.key, _NO_HISTORY)
if original is _NO_HISTORY:
if current is NO_VALUE or current is NEVER_SET:
return cls((), (), ())
else:
return cls((), [current], ())
elif current is original:
return cls((), [current], ())
else:
# current convention on related objects is to not
# include information
# about missing previous value in "deleted", and
# to also not include None - the dependency.py rules
# ignore the None in any case.
if id(original) in _NO_STATE_SYMBOLS or original is None:
deleted = ()
else:
deleted = [original]
if current is NO_VALUE or current is NEVER_SET:
return cls((), (), deleted)
else:
return cls([current], (), deleted)
@classmethod
def from_collection(cls, attribute, state, current):
original = state.committed_state.get(attribute.key, _NO_HISTORY)
if current is NO_VALUE or current is NEVER_SET:
return cls((), (), ())
current = getattr(current, '_sa_adapter')
if original in (NO_VALUE, NEVER_SET):
return cls(list(current), (), ())
elif original is _NO_HISTORY:
return cls((), list(current), ())
else:
current_states = [((c is not None) and instance_state(c)
or None, c)
for c in current
]
original_states = [((c is not None) and instance_state(c)
or None, c)
for c in original
]
current_set = dict(current_states)
original_set = dict(original_states)
return cls(
[o for s, o in current_states if s not in original_set],
[o for s, o in current_states if s in original_set],
[o for s, o in original_states if s not in current_set]
)
HISTORY_BLANK = History(None, None, None)
def get_history(obj, key, passive=PASSIVE_OFF):
"""Return a :class:`.History` record for the given object
and attribute key.
:param obj: an object whose class is instrumented by the
attributes package.
:param key: string attribute name.
:param passive: indicates loading behavior for the attribute
if the value is not already present. This is a
bitflag attribute, which defaults to the symbol
:attr:`.PASSIVE_OFF` indicating all necessary SQL
should be emitted.
"""
if passive is True:
util.warn_deprecated("Passing True for 'passive' is deprecated. "
"Use attributes.PASSIVE_NO_INITIALIZE")
passive = PASSIVE_NO_INITIALIZE
elif passive is False:
util.warn_deprecated("Passing False for 'passive' is "
"deprecated. Use attributes.PASSIVE_OFF")
passive = PASSIVE_OFF
return get_state_history(instance_state(obj), key, passive)
def get_state_history(state, key, passive=PASSIVE_OFF):
return state.get_history(key, passive)
def has_parent(cls, obj, key, optimistic=False):
"""TODO"""
manager = manager_of_class(cls)
state = instance_state(obj)
return manager.has_parent(state, key, optimistic)
def register_attribute(class_, key, **kw):
comparator = kw.pop('comparator', None)
parententity = kw.pop('parententity', None)
doc = kw.pop('doc', None)
desc = register_descriptor(class_, key,
comparator, parententity, doc=doc)
register_attribute_impl(class_, key, **kw)
return desc
def register_attribute_impl(class_, key,
uselist=False, callable_=None,
useobject=False,
impl_class=None, backref=None, **kw):
manager = manager_of_class(class_)
if uselist:
factory = kw.pop('typecallable', None)
typecallable = manager.instrument_collection_class(
key, factory or list)
else:
typecallable = kw.pop('typecallable', None)
dispatch = manager[key].dispatch
if impl_class:
impl = impl_class(class_, key, typecallable, dispatch, **kw)
elif uselist:
impl = CollectionAttributeImpl(class_, key, callable_, dispatch,
typecallable=typecallable, **kw)
elif useobject:
impl = ScalarObjectAttributeImpl(class_, key, callable_,
dispatch, **kw)
else:
impl = ScalarAttributeImpl(class_, key, callable_, dispatch, **kw)
manager[key].impl = impl
if backref:
backref_listeners(manager[key], backref, uselist)
manager.post_configure_attribute(key)
return manager[key]
def register_descriptor(class_, key, comparator=None,
parententity=None, doc=None):
manager = manager_of_class(class_)
descriptor = InstrumentedAttribute(class_, key, comparator=comparator,
parententity=parententity)
descriptor.__doc__ = doc
manager.instrument_attribute(key, descriptor)
return descriptor
def unregister_attribute(class_, key):
manager_of_class(class_).uninstrument_attribute(key)
def init_collection(obj, key):
"""Initialize a collection attribute and return the collection adapter.
This function is used to provide direct access to collection internals
for a previously unloaded attribute. e.g.::
collection_adapter = init_collection(someobject, 'elements')
for elem in values:
collection_adapter.append_without_event(elem)
For an easier way to do the above, see
:func:`~sqlalchemy.orm.attributes.set_committed_value`.
obj is an instrumented object instance. An InstanceState
is accepted directly for backwards compatibility but
this usage is deprecated.
"""
state = instance_state(obj)
dict_ = state.dict
return init_state_collection(state, dict_, key)
def init_state_collection(state, dict_, key):
"""Initialize a collection attribute and return the collection adapter."""
attr = state.manager[key].impl
user_data = attr.initialize(state, dict_)
return attr.get_collection(state, dict_, user_data)
def set_committed_value(instance, key, value):
"""Set the value of an attribute with no history events.
Cancels any previous history present. The value should be
a scalar value for scalar-holding attributes, or
an iterable for any collection-holding attribute.
This is the same underlying method used when a lazy loader
fires off and loads additional data from the database.
In particular, this method can be used by application code
which has loaded additional attributes or collections through
separate queries, which can then be attached to an instance
as though it were part of its original loaded state.
"""
state, dict_ = instance_state(instance), instance_dict(instance)
state.manager[key].impl.set_committed_value(state, dict_, value)
def set_attribute(instance, key, value):
"""Set the value of an attribute, firing history events.
This function may be used regardless of instrumentation
applied directly to the class, i.e. no descriptors are required.
Custom attribute management schemes will need to make usage
of this method to establish attribute state as understood
by SQLAlchemy.
"""
state, dict_ = instance_state(instance), instance_dict(instance)
state.manager[key].impl.set(state, dict_, value, None)
def get_attribute(instance, key):
"""Get the value of an attribute, firing any callables required.
This function may be used regardless of instrumentation
applied directly to the class, i.e. no descriptors are required.
Custom attribute management schemes will need to make usage
of this method to make usage of attribute state as understood
by SQLAlchemy.
"""
state, dict_ = instance_state(instance), instance_dict(instance)
return state.manager[key].impl.get(state, dict_)
def del_attribute(instance, key):
"""Delete the value of an attribute, firing history events.
This function may be used regardless of instrumentation
applied directly to the class, i.e. no descriptors are required.
Custom attribute management schemes will need to make usage
of this method to establish attribute state as understood
by SQLAlchemy.
"""
state, dict_ = instance_state(instance), instance_dict(instance)
state.manager[key].impl.delete(state, dict_)
def flag_modified(instance, key):
"""Mark an attribute on an instance as 'modified'.
This sets the 'modified' flag on the instance and
establishes an unconditional change event for the given attribute.
"""
state, dict_ = instance_state(instance), instance_dict(instance)
impl = state.manager[key].impl
state._modified_event(dict_, impl, NO_VALUE)
| |
import itertools
from nose.tools import assert_equal, assert_true, assert_false, assert_raises
import networkx as nx
from networkx.algorithms import flow
from networkx.algorithms.connectivity import local_edge_connectivity
from networkx.algorithms.connectivity import local_node_connectivity
flow_funcs = [
flow.boykov_kolmogorov,
flow.dinitz,
flow.edmonds_karp,
flow.preflow_push,
flow.shortest_augmenting_path,
]
msg = "Assertion failed in function: {0}"
# helper functions for tests
def _generate_no_biconnected(max_attempts=50):
attempts = 0
while True:
G = nx.fast_gnp_random_graph(100, 0.0575)
if nx.is_connected(G) and not nx.is_biconnected(G):
attempts = 0
yield G
else:
if attempts >= max_attempts:
msg = "Tried %d times: no suitable Graph."
raise Exception(msg % max_attempts)
else:
attempts += 1
def test_average_connectivity():
# figure 1 from:
# Beineke, L., O. Oellermann, and R. Pippert (2002). The average
# connectivity of a graph. Discrete mathematics 252(1-3), 31-45
# http://www.sciencedirect.com/science/article/pii/S0012365X01001807
G1 = nx.path_graph(3)
G1.add_edges_from([(1, 3),(1, 4)])
G2 = nx.path_graph(3)
G2.add_edges_from([(1, 3),(1, 4),(0, 3),(0, 4),(3, 4)])
G3 = nx.Graph()
for flow_func in flow_funcs:
kwargs = dict(flow_func=flow_func)
assert_equal(nx.average_node_connectivity(G1, **kwargs), 1,
msg=msg.format(flow_func.__name__))
assert_equal(nx.average_node_connectivity(G2, **kwargs), 2.2,
msg=msg.format(flow_func.__name__))
assert_equal(nx.average_node_connectivity(G3, **kwargs), 0,
msg=msg.format(flow_func.__name__))
def test_average_connectivity_directed():
G = nx.DiGraph([(1,3),(1,4),(1,5)])
for flow_func in flow_funcs:
assert_equal(nx.average_node_connectivity(G), 0.25,
msg=msg.format(flow_func.__name__))
def test_articulation_points():
Ggen = _generate_no_biconnected()
for flow_func in flow_funcs:
for i in range(3):
G = next(Ggen)
assert_equal(nx.node_connectivity(G, flow_func=flow_func), 1,
msg=msg.format(flow_func.__name__))
def test_brandes_erlebach():
# Figure 1 chapter 7: Connectivity
# http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf
G = nx.Graph()
G.add_edges_from([(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 6), (3, 4),
(3, 6), (4, 6), (4, 7), (5, 7), (6, 8), (6, 9), (7, 8),
(7, 10), (8, 11), (9, 10), (9, 11), (10, 11)])
for flow_func in flow_funcs:
kwargs = dict(flow_func=flow_func)
assert_equal(3, local_edge_connectivity(G, 1, 11, **kwargs),
msg=msg.format(flow_func.__name__))
assert_equal(3, nx.edge_connectivity(G, 1, 11, **kwargs),
msg=msg.format(flow_func.__name__))
assert_equal(2, local_node_connectivity(G, 1, 11, **kwargs),
msg=msg.format(flow_func.__name__))
assert_equal(2, nx.node_connectivity(G, 1, 11, **kwargs),
msg=msg.format(flow_func.__name__))
assert_equal(2, nx.edge_connectivity(G, **kwargs), # node 5 has degree 2
msg=msg.format(flow_func.__name__))
assert_equal(2, nx.node_connectivity(G, **kwargs),
msg=msg.format(flow_func.__name__))
def test_white_harary_1():
# Figure 1b white and harary (2001)
# # http://eclectic.ss.uci.edu/~drwhite/sm-w23.PDF
# A graph with high adhesion (edge connectivity) and low cohesion
# (vertex connectivity)
G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
G.remove_node(7)
for i in range(4, 7):
G.add_edge(0, i)
G = nx.disjoint_union(G, nx.complete_graph(4))
G.remove_node(G.order() - 1)
for i in range(7, 10):
G.add_edge(0, i)
for flow_func in flow_funcs:
assert_equal(1, nx.node_connectivity(G, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
assert_equal(3, nx.edge_connectivity(G, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
def test_white_harary_2():
# Figure 8 white and harary (2001)
# # http://eclectic.ss.uci.edu/~drwhite/sm-w23.PDF
G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
G.add_edge(0, 4)
# kappa <= lambda <= delta
assert_equal(3, min(nx.core_number(G).values()))
for flow_func in flow_funcs:
assert_equal(1, nx.node_connectivity(G, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
assert_equal(1, nx.edge_connectivity(G, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
def test_complete_graphs():
for n in range(5, 20, 5):
for flow_func in flow_funcs:
G = nx.complete_graph(n)
assert_equal(n-1, nx.node_connectivity(G, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
assert_equal(n-1, nx.node_connectivity(G.to_directed(),
flow_func=flow_func),
msg=msg.format(flow_func.__name__))
assert_equal(n-1, nx.edge_connectivity(G, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
assert_equal(n-1, nx.edge_connectivity(G.to_directed(),
flow_func=flow_func),
msg=msg.format(flow_func.__name__))
def test_empty_graphs():
for k in range(5, 25, 5):
G = nx.empty_graph(k)
for flow_func in flow_funcs:
assert_equal(0, nx.node_connectivity(G, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
assert_equal(0, nx.edge_connectivity(G, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
def test_petersen():
G = nx.petersen_graph()
for flow_func in flow_funcs:
assert_equal(3, nx.node_connectivity(G, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
assert_equal(3, nx.edge_connectivity(G, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
def test_tutte():
G = nx.tutte_graph()
for flow_func in flow_funcs:
assert_equal(3, nx.node_connectivity(G, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
assert_equal(3, nx.edge_connectivity(G, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
def test_dodecahedral():
G = nx.dodecahedral_graph()
for flow_func in flow_funcs:
assert_equal(3, nx.node_connectivity(G, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
assert_equal(3, nx.edge_connectivity(G, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
def test_octahedral():
G=nx.octahedral_graph()
for flow_func in flow_funcs:
assert_equal(4, nx.node_connectivity(G, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
assert_equal(4, nx.edge_connectivity(G, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
def test_icosahedral():
G=nx.icosahedral_graph()
for flow_func in flow_funcs:
assert_equal(5, nx.node_connectivity(G, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
assert_equal(5, nx.edge_connectivity(G, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
def test_missing_source():
G = nx.path_graph(4)
for flow_func in flow_funcs:
assert_raises(nx.NetworkXError, nx.node_connectivity, G, 10, 1,
flow_func=flow_func)
def test_missing_target():
G = nx.path_graph(4)
for flow_func in flow_funcs:
assert_raises(nx.NetworkXError, nx.node_connectivity, G, 1, 10,
flow_func=flow_func)
def test_edge_missing_source():
G = nx.path_graph(4)
for flow_func in flow_funcs:
assert_raises(nx.NetworkXError, nx.edge_connectivity, G, 10, 1,
flow_func=flow_func)
def test_edge_missing_target():
G = nx.path_graph(4)
for flow_func in flow_funcs:
assert_raises(nx.NetworkXError, nx.edge_connectivity, G, 1, 10,
flow_func=flow_func)
def test_not_weakly_connected():
G = nx.DiGraph()
nx.add_path(G, [1, 2, 3])
nx.add_path(G, [4, 5])
for flow_func in flow_funcs:
assert_equal(nx.node_connectivity(G), 0,
msg=msg.format(flow_func.__name__))
assert_equal(nx.edge_connectivity(G), 0,
msg=msg.format(flow_func.__name__))
def test_not_connected():
G = nx.Graph()
nx.add_path(G, [1, 2, 3])
nx.add_path(G, [4, 5])
for flow_func in flow_funcs:
assert_equal(nx.node_connectivity(G), 0,
msg=msg.format(flow_func.__name__))
assert_equal(nx.edge_connectivity(G), 0,
msg=msg.format(flow_func.__name__))
def test_directed_edge_connectivity():
G = nx.cycle_graph(10, create_using=nx.DiGraph()) # only one direction
D = nx.cycle_graph(10).to_directed() # 2 reciprocal edges
for flow_func in flow_funcs:
assert_equal(1, nx.edge_connectivity(G, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
assert_equal(1, local_edge_connectivity(G, 1, 4, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
assert_equal(1, nx.edge_connectivity(G, 1, 4, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
assert_equal(2, nx.edge_connectivity(D, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
assert_equal(2, local_edge_connectivity(D, 1, 4, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
assert_equal(2, nx.edge_connectivity(D, 1, 4, flow_func=flow_func),
msg=msg.format(flow_func.__name__))
def test_cutoff():
G = nx.complete_graph(5)
for local_func in [local_edge_connectivity, local_node_connectivity]:
for flow_func in flow_funcs:
if flow_func is flow.preflow_push:
# cutoff is not supported by preflow_push
continue
for cutoff in [3, 2, 1]:
result = local_func(G, 0, 4, flow_func=flow_func, cutoff=cutoff)
assert_equal(cutoff, result,
msg="cutoff error in {0}".format(flow_func.__name__))
def test_invalid_auxiliary():
G = nx.complete_graph(5)
assert_raises(nx.NetworkXError, local_node_connectivity, G, 0, 3,
auxiliary=G)
def test_interface_only_source():
G = nx.complete_graph(5)
for interface_func in [nx.node_connectivity, nx.edge_connectivity]:
assert_raises(nx.NetworkXError, interface_func, G, s=0)
def test_interface_only_target():
G = nx.complete_graph(5)
for interface_func in [nx.node_connectivity, nx.edge_connectivity]:
assert_raises(nx.NetworkXError, interface_func, G, t=3)
def test_edge_connectivity_flow_vs_stoer_wagner():
graph_funcs = [
nx.icosahedral_graph,
nx.octahedral_graph,
nx.dodecahedral_graph,
]
for graph_func in graph_funcs:
G = graph_func()
assert_equal(nx.stoer_wagner(G)[0], nx.edge_connectivity(G))
class TestAllPairsNodeConnectivity:
def setUp(self):
self.path = nx.path_graph(7)
self.directed_path = nx.path_graph(7, create_using=nx.DiGraph())
self.cycle = nx.cycle_graph(7)
self.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
self.gnp = nx.gnp_random_graph(30, 0.1)
self.directed_gnp = nx.gnp_random_graph(30, 0.1, directed=True)
self.K20 = nx.complete_graph(20)
self.K10 = nx.complete_graph(10)
self.K5 = nx.complete_graph(5)
self.G_list = [self.path, self.directed_path, self.cycle,
self.directed_cycle, self.gnp, self.directed_gnp, self.K10,
self.K5, self.K20]
def test_cycles(self):
K_undir = nx.all_pairs_node_connectivity(self.cycle)
for source in K_undir:
for target, k in K_undir[source].items():
assert_true(k == 2)
K_dir = nx.all_pairs_node_connectivity(self.directed_cycle)
for source in K_dir:
for target, k in K_dir[source].items():
assert_true(k == 1)
def test_complete(self):
for G in [self.K10, self.K5, self.K20]:
K = nx.all_pairs_node_connectivity(G)
for source in K:
for target, k in K[source].items():
assert_true(k == len(G)-1)
def test_paths(self):
K_undir = nx.all_pairs_node_connectivity(self.path)
for source in K_undir:
for target, k in K_undir[source].items():
assert_true(k == 1)
K_dir = nx.all_pairs_node_connectivity(self.directed_path)
for source in K_dir:
for target, k in K_dir[source].items():
if source < target:
assert_true(k == 1)
else:
assert_true(k == 0)
def test_all_pairs_connectivity_nbunch(self):
G = nx.complete_graph(5)
nbunch = [0, 2, 3]
C = nx.all_pairs_node_connectivity(G, nbunch=nbunch)
assert_equal(len(C), len(nbunch))
def test_all_pairs_connectivity_icosahedral(self):
G = nx.icosahedral_graph()
C = nx.all_pairs_node_connectivity(G)
assert_true(all(5 == C[u][v] for u, v in itertools.combinations(G, 2)))
def test_all_pairs_connectivity(self):
G = nx.Graph()
nodes = [0, 1, 2, 3]
nx.add_path(G, nodes)
A = {n: {} for n in G}
for u, v in itertools.combinations(nodes,2):
A[u][v] = A[v][u] = nx.node_connectivity(G, u, v)
C = nx.all_pairs_node_connectivity(G)
assert_equal(sorted((k, sorted(v)) for k, v in A.items()),
sorted((k, sorted(v)) for k, v in C.items()))
def test_all_pairs_connectivity_directed(self):
G = nx.DiGraph()
nodes = [0, 1, 2, 3]
nx.add_path(G, nodes)
A = {n: {} for n in G}
for u, v in itertools.permutations(nodes, 2):
A[u][v] = nx.node_connectivity(G, u, v)
C = nx.all_pairs_node_connectivity(G)
assert_equal(sorted((k, sorted(v)) for k, v in A.items()),
sorted((k, sorted(v)) for k, v in C.items()))
def test_all_pairs_connectivity_nbunch(self):
G = nx.complete_graph(5)
nbunch = [0, 2, 3]
A = {n: {} for n in nbunch}
for u, v in itertools.combinations(nbunch, 2):
A[u][v] = A[v][u] = nx.node_connectivity(G, u, v)
C = nx.all_pairs_node_connectivity(G, nbunch=nbunch)
assert_equal(sorted((k, sorted(v)) for k, v in A.items()),
sorted((k, sorted(v)) for k, v in C.items()))
def test_all_pairs_connectivity_nbunch_iter(self):
G = nx.complete_graph(5)
nbunch = [0, 2, 3]
A = {n: {} for n in nbunch}
for u, v in itertools.combinations(nbunch, 2):
A[u][v] = A[v][u] = nx.node_connectivity(G, u, v)
C = nx.all_pairs_node_connectivity(G, nbunch=iter(nbunch))
assert_equal(sorted((k, sorted(v)) for k, v in A.items()),
sorted((k, sorted(v)) for k, v in C.items()))
| |
import os
import sys
import datetime
import re
import shutil
import webbrowser
FILEDIR = "templates"
DESIGNDIR = "design"
ASSETSDIR = "assets_url"
ASSETS_ORG = "assets"
notParse = ['404.html', 'layout.html']
SUBCONTENT = "{{ content }}"
now = datetime.datetime.now()
nowDate = now.strftime("%Y-%m-%d %H:%M")
menuBlok = """<ul class="nav">
<li><a href="home.html">Home</a></li>
<li><a href="for_sale.html">For Sale</a></li>
<li><a href="auctions.html">Auctions</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="about_us.html">About Us</a></li>
<li><a href="login.html" id="">Login</a></li>
<li><a href="register.html">Register</a></li>
</ul>
"""
mailListBlok = """
<DIV ID="mail_list_form" DIR="LTR">
<FORM NAME="form" ACTION="../shellscript" METHOD="POST">
<P><A NAME="id_email"></A><A NAME="mail_list_submit_btn"></A>Enter
Your Email Address: <INPUT TYPE=TEXT NAME="email" SIZE=22 MAXLENGTH=75 STYLE="width: 1.92in; height: 0.31in">
<INPUT TYPE=SUBMIT VALUE="Subscribe" STYLE="width: 1.16in; height: 0.4in">
</P>
</FORM>
</DIV>
"""
forLinks = """
<P><A HREF="home.html">Home</A></P>
<P><A HREF="auctions.html">Auctions</A></P>
<P><A HREF="for_sale.html">For Sale</A></P>
<P><A HREF="login.html">Login</A></P>
<P><A HREF="register.html">Register</A></P>
"""
searchBlock = """
{% if results|length == 60 %}
<div class="NoResults">
<div class="span2 debar-nav well hidden-phone">
<ul class="nav nav-list unstyled">
{% for categories in shop_categories %}
<li><a href="/search/?q={{categories.name}}">{{ categories.name }}</a></li>
{% endfor %}
</ul>
</div>
<div class="span8">
<h2>Sorry we didn't have what you wanted...</h2>
<h3>Please Look at Our...</h3>
<b><a href="/for_sale/">Rare Coins For Sale</a></b>
<p><b> <a href="/auctions/">Online Coin Auctions</a></b></p>
<p><b> <a href="/home">Our Home Page</a></b></p>
</div>
</div>
</div>
{% else %}"""
def replaceCSS(path):
cssFile = open(path)
cssFileContent = cssFile.read()
cssFileContent = re.sub( r'({{ (.*) }})', lambda L: cssChange(L), cssFileContent)
cssFile = open(path, 'w')
cssFile.write(cssFileContent)
def cssChange(arg):
assets = arg.group(2)
name, asset = assets.split("|")
name = name.replace("'", "").strip()
name = name.replace("{{", "")
name = name.replace("}}", "")
name = name.strip()
cssPath = name
return cssPath
def replaceLinks(arg):
assets = arg.group(2)
assets = assets.replace('href="', "")
name, asset = assets.split("|")
name = name.replace("'", "").strip()
name = name.replace("{{", "")
name = name.replace("}}", "")
name = name.strip()
cssPath = 'assets_url/' + name
replaceCSS(cssPath)
return 'href="../assets_url/' + name
def replaceImg(arg):
assets = arg.group(2)
assets = assets.replace('src="', "")
if len(assets.split("|")) == 2:
name, asset = assets.split("|")
name = name.replace("'", "").strip()
name = name.replace("{{", "")
name = name.replace("}}", "")
name = name.strip()
return 'src="../assets_url/' + name
def replaceDict(dictName, htmlString):
htmlOut = htmlString
for key in dictName:
htmlOut = htmlOut.replace(key, dictName[key])
if "for link in links" in htmlOut:
htmlOut = re.sub('\{% for link .*[\w\s]*.*[\w\s]*\{% endfor %\}', forLinks, htmlOut)
#htmlOut = re.sub(r'{% for link in links %} .*{% endfor %}', forLinks, htmlOut )
return htmlOut
replaceDir= {
'{{ url_terms_of_service }}': 'terms_of_service.html',
'{{ url_privacy_policy }}': 'privacy_policies.html',
'{{ url_refund }}': 'refund.html',
'{{ about|truncate(100) }}': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut massa sed lacus feugiat cras amet. ',
'{{ url_my_orders }}': 'my_orders.html', '{{ home.image.url }}': 'http://s3.amazonaws.com/market-media.greatcoins.com/img/no-photo-shop.png ',
'{{ url_terms_of_service }}': 'terms_of_service.html',
'{{ url_privacy_policy }}': 'privacy_policies.html',
'{{ url_refund }}': 'refund.html',
'{{item.url}}': 'view_item.html',
'{{ home.body }}': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut massa sed lacus feugiat cras amet. ',
'{{ home.title }}': 'Django Market Home Page',
'{{ shop_name }}': 'Django Market Theme Designer',
'{{ shop_name|title }}': 'Django Market Theme Designer ',
'{{ url_search }}': 'search.html',
'{{ url_my_shopping }}': 'my_shopping.html',
'{{ total_cart_items }}': '10',
'{{ page_description }}': ' ',
'{{item.title|title}}': 'For Sale Item 1',
'{{ header }}': '',
'searchBlock': '',
'<a href="/about_us/">': 'about_us.html',
'{{item.description|truncate(100)}}': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.Lorem ipsum dolor sit amet,Lorem ipsum dolor sit amet',
'<h3>No items for sale.</h3>': '',
'{{item.description|truncate(100)}}': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.Lorem ipsum dolor sit amet,Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.Lorem ipsum dolor sit amet,',
'{{lot.title|title}}': 'Lot Title 1 For Bid',
'{{lot.title|title}}': 'Lot Title 1 For Bid',
'{{ lot.time_left }} ({{ lot.session_end }})': '14 Hours, 2 Minutes',
'{{lot.price}}': '$1232.32',
'{{ lot.category }}': 'Gold',
'{{ item.category }}': 'Gold',
'{{ item.subcategory }}': 'Double Eagles',
'{{ post.url }}': 'view_post.html',
'{{ post.title }}': 'Blog Post Title',
'/for_sale/': 'for_sale.html',
'/auctions/': 'auctions.html',
'/home': 'home.html',
'{{ post.date_time }}': nowDate,
'{{ post.body|safe|truncate(400) }}': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce',
'{{ post.title|title }}': 'View Blog Post Title',
'{{ post.body }}': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.',
'<h3 class="title">No lots in this session.</h3>': ' ',
'{{ lot.subcategory }}': 'Quarter Eagle',
'{{ item.description }}': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.',
'{{ lipsum(5,false,20,35) }}': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.Lorem ipsum dolor sit amet,',
'{{ lot.description }}': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.',
'{{item.price}}': '$1232.32',
'{{ about.title|title }}': 'About Django Market Shop',
'{{ sessions }}': '<ul class="nav"><li class="active">Session 1:</li><li>Febuary 10th 2014</li><li>Session 2</li><li>Febuary 18th 2092</li></ul>',
'{{ about.body }}': 'Django Market Is the Python Open source alternative to other PHP based shopping carts. In addition, we have a built in marketplace for our shops to enable them to see additonal goods and services. See GitHub For more information',
'<img src="{% if item.image.small %}{{ item.image.small }}{% else %}{{ ': '',
'no_photo_small.png': '',
'|asset_url }}{% endif %}" alt="{{ item.title }}" />': '<script src="holder.js"></script> <img src="holder.js/100x100">',
'{{ flash }}': '',
'{{ categories.name }}': 'Gold',
'{{ footer }}': '',
'{{ menu }}': menuBlok,
'{{ about|truncate(100) }}': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.',
'{{ last_post.body|truncate(100) }}': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.',
'{{ last_post.url }}' : 'blog.html',
'{{ last_post.title }}': 'Django Market Blog Post',
'{{ last_post.date_time }}': nowDate,
'{{ mailing_list }}': mailListBlok
}
if not os.path.exists(DESIGNDIR):
os.makedirs(DESIGNDIR)
else:
answer = raw_input('Folder designer exists.Do you want to remove it and recreate it with new files? Y/N')
if answer in ['y', 'Y']:
shutil.rmtree(DESIGNDIR)
print 'Folder designer deleted and recreated'
os.makedirs(DESIGNDIR)
else:
sys.exit()
if not os.path.exists(ASSETSDIR):
shutil.copytree(ASSETS_ORG, ASSETSDIR)
else:
answer = raw_input('Folder assets_url exists.Do you want to remove it and recreate it with new files? Y/N')
if answer in ['y', 'Y']:
shutil.rmtree(ASSETSDIR)
print 'Folder assets_url deleted and recreated'
shutil.copytree(ASSETS_ORG, ASSETSDIR)
else:
sys.exit()
layoutFile= open(FILEDIR + os.sep + "layout.html")
layoutHTML = layoutFile.read()
layoutHTML = replaceDict(replaceDir, layoutHTML)
layoutHTML = re.sub( r'href="({{ (.*) }})', lambda L: replaceLinks(L), layoutHTML)
def stripAllTags(html):
outHtml = re.sub( r'{% (.*) %}', "", html)
return outHtml
for fileName in os.popen("ls " + FILEDIR):
fileName = fileName.strip()
replaceDir['{{ page_title }}'] = 'Django Market ' + fileName
fileHTML = open(FILEDIR + os.sep + fileName.strip())
fileHTML = fileHTML.read()
if fileName in notParse:
continue
newContent = layoutHTML.replace(SUBCONTENT, fileHTML)
newContent = replaceDict(replaceDir, newContent)
newContent = stripAllTags(newContent)
newContent = re.sub( r'src="({{ (.*) }})', lambda L: replaceImg(L), newContent)
outputFile = open(DESIGNDIR + os.sep + fileName, 'w')
outputFile.write(newContent)
print 'DONE'
os.system("open "+DESIGNDIR +os.sep+"home.html");
| |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from . import ops
from .groupby import DataArrayGroupBy, DatasetGroupBy
from .pycompat import dask_array_type, OrderedDict
RESAMPLE_DIM = '__resample_dim__'
class Resample(object):
"""An object that extends the `GroupBy` object with additional logic
for handling specialized re-sampling operations.
You should create a `Resample` object by using the `DataArray.resample` or
`Dataset.resample` methods. The dimension along re-sampling
See Also
--------
DataArray.resample
Dataset.resample
"""
def _upsample(self, method, *args, **kwargs):
"""Dispatch function to call appropriate up-sampling methods on
data.
This method should not be called directly; instead, use one of the
wrapper functions supplied by `Resample`.
Parameters
----------
method : str {'asfreq', 'pad', 'ffill', 'backfill', 'bfill', 'nearest',
'interpolate'}
Method to use for up-sampling
See Also
--------
Resample.asfreq
Resample.pad
Resample.backfill
Resample.interpolate
"""
upsampled_index = self._full_index
# Drop non-dimension coordinates along the resampled dimension
for k, v in self._obj.coords.items():
if k == self._dim:
continue
if self._dim in v.dims:
self._obj = self._obj.drop(k)
if method == 'asfreq':
return self.mean(self._dim)
elif method in ['pad', 'ffill', 'backfill', 'bfill', 'nearest']:
kwargs = kwargs.copy()
kwargs.update(**{self._dim: upsampled_index})
return self._obj.reindex(method=method, *args, **kwargs)
elif method == 'interpolate':
return self._interpolate(*args, **kwargs)
else:
raise ValueError('Specified method was "{}" but must be one of'
'"asfreq", "ffill", "bfill", or "interpolate"'
.format(method))
def asfreq(self):
"""Return values of original object at the new up-sampling frequency;
essentially a re-index with new times set to NaN.
"""
return self._upsample('asfreq')
def pad(self):
"""Forward fill new values at up-sampled frequency.
"""
return self._upsample('pad')
ffill = pad
def backfill(self):
"""Backward fill new values at up-sampled frequency.
"""
return self._upsample('backfill')
bfill = backfill
def nearest(self):
"""Take new values from nearest original coordinate to up-sampled
frequency coordinates.
"""
return self._upsample('nearest')
def interpolate(self, kind='linear'):
"""Interpolate up-sampled data using the original data
as knots.
Parameters
----------
kind : str {'linear', 'nearest', 'zero', 'slinear',
'quadratic', 'cubic'}
Interpolation scheme to use
See Also
--------
scipy.interpolate.interp1d
"""
return self._interpolate(kind=kind)
def _interpolate(self, kind='linear'):
raise NotImplementedError
class DataArrayResample(DataArrayGroupBy, Resample):
"""DataArrayGroupBy object specialized to time resampling operations over a
specified dimension
"""
def __init__(self, *args, **kwargs):
self._dim = kwargs.pop('dim', None)
self._resample_dim = kwargs.pop('resample_dim', None)
if self._dim == self._resample_dim:
raise ValueError("Proxy resampling dimension ('{}') "
"cannot have the same name as actual dimension "
"('{}')! ".format(self._resample_dim, self._dim))
super(DataArrayResample, self).__init__(*args, **kwargs)
def apply(self, func, shortcut=False, **kwargs):
"""Apply a function over each array in the group and concatenate them
together into a new array.
`func` is called like `func(ar, *args, **kwargs)` for each array `ar`
in this group.
Apply uses heuristics (like `pandas.GroupBy.apply`) to figure out how
to stack together the array. The rule is:
1. If the dimension along which the group coordinate is defined is
still in the first grouped array after applying `func`, then stack
over this dimension.
2. Otherwise, stack over the new dimension given by name of this
grouping (the argument to the `groupby` function).
Parameters
----------
func : function
Callable to apply to each array.
shortcut : bool, optional
Whether or not to shortcut evaluation under the assumptions that:
(1) The action of `func` does not depend on any of the array
metadata (attributes or coordinates) but only on the data and
dimensions.
(2) The action of `func` creates arrays with homogeneous metadata,
that is, with the same dimensions and attributes.
If these conditions are satisfied `shortcut` provides significant
speedup. This should be the case for many common groupby operations
(e.g., applying numpy ufuncs).
**kwargs
Used to call `func(ar, **kwargs)` for each array `ar`.
Returns
-------
applied : DataArray or DataArray
The result of splitting, applying and combining this array.
"""
combined = super(DataArrayResample, self).apply(
func, shortcut=shortcut, **kwargs)
# If the aggregation function didn't drop the original resampling
# dimension, then we need to do so before we can rename the proxy
# dimension we used.
if self._dim in combined.coords:
combined = combined.drop(self._dim)
if self._resample_dim in combined.dims:
combined = combined.rename({self._resample_dim: self._dim})
return combined
def _interpolate(self, kind='linear'):
"""Apply scipy.interpolate.interp1d along resampling dimension."""
from .dataarray import DataArray
from scipy.interpolate import interp1d
if isinstance(self._obj.data, dask_array_type):
raise TypeError(
"Up-sampling via interpolation was attempted on the the "
"variable '{}', but it is a dask array; dask arrays are not "
"yet supported in resample.interpolate(). Load into "
"memory with Dataset.load() before resampling."
.format(self._obj.data.name)
)
x = self._obj[self._dim].astype('float')
y = self._obj.data
axis = self._obj.get_axis_num(self._dim)
f = interp1d(x, y, kind=kind, axis=axis, bounds_error=True,
assume_sorted=True)
new_x = self._full_index.values.astype('float')
# construct new up-sampled DataArray
dummy = self._obj.copy()
dims = dummy.dims
# drop any existing non-dimension coordinates along the resampling
# dimension
coords = OrderedDict()
for k, v in dummy.coords.items():
# is the resampling dimension
if k == self._dim:
coords[self._dim] = self._full_index
# else, check if resampling dim is in coordinate dimensions
elif self._dim not in v.dims:
coords[k] = v
return DataArray(f(new_x), coords, dims, name=dummy.name,
attrs=dummy.attrs)
ops.inject_reduce_methods(DataArrayResample)
ops.inject_binary_ops(DataArrayResample)
class DatasetResample(DatasetGroupBy, Resample):
"""DatasetGroupBy object specialized to resampling a specified dimension
"""
def __init__(self, *args, **kwargs):
self._dim = kwargs.pop('dim', None)
self._resample_dim = kwargs.pop('resample_dim', None)
if self._dim == self._resample_dim:
raise ValueError("Proxy resampling dimension ('{}') "
"cannot have the same name as actual dimension "
"('{}')! ".format(self._resample_dim, self._dim))
super(DatasetResample, self).__init__(*args, **kwargs)
def apply(self, func, **kwargs):
"""Apply a function over each Dataset in the groups generated for
resampling and concatenate them together into a new Dataset.
`func` is called like `func(ds, *args, **kwargs)` for each dataset `ds`
in this group.
Apply uses heuristics (like `pandas.GroupBy.apply`) to figure out how
to stack together the datasets. The rule is:
1. If the dimension along which the group coordinate is defined is
still in the first grouped item after applying `func`, then stack
over this dimension.
2. Otherwise, stack over the new dimension given by name of this
grouping (the argument to the `groupby` function).
Parameters
----------
func : function
Callable to apply to each sub-dataset.
**kwargs
Used to call `func(ds, **kwargs)` for each sub-dataset `ar`.
Returns
-------
applied : Dataset or DataArray
The result of splitting, applying and combining this dataset.
"""
kwargs.pop('shortcut', None) # ignore shortcut if set (for now)
applied = (func(ds, **kwargs) for ds in self._iter_grouped())
combined = self._combine(applied)
return combined.rename({self._resample_dim: self._dim})
def reduce(self, func, dim=None, keep_attrs=False, **kwargs):
"""Reduce the items in this group by applying `func` along the
pre-defined resampling dimension.
Note that `dim` is by default here and ignored if passed by the user;
this ensures compatibility with the existing reduce interface.
Parameters
----------
func : function
Function which can be called in the form
`func(x, axis=axis, **kwargs)` to return the result of collapsing
an np.ndarray over an integer valued axis.
keep_attrs : bool, optional
If True, the datasets's attributes (`attrs`) will be copied from
the original object to the new one. If False (default), the new
object will be returned without attributes.
**kwargs : dict
Additional keyword arguments passed on to `func`.
Returns
-------
reduced : Array
Array with summarized data and the indicated dimension(s)
removed.
"""
return super(DatasetResample, self).reduce(
func, self._dim, keep_attrs, **kwargs)
def _interpolate(self, kind='linear'):
"""Apply scipy.interpolate.interp1d along resampling dimension."""
from .dataset import Dataset
from .variable import Variable
from scipy.interpolate import interp1d
old_times = self._obj[self._dim].astype(float)
new_times = self._full_index.values.astype(float)
data_vars = OrderedDict()
coords = OrderedDict()
# Apply the interpolation to each DataArray in our original Dataset
for name, variable in self._obj.variables.items():
if name in self._obj.coords:
if name == self._dim:
coords[self._dim] = self._full_index
elif self._dim not in variable.dims:
coords[name] = variable
else:
if isinstance(variable.data, dask_array_type):
raise TypeError(
"Up-sampling via interpolation was attempted on the "
"variable '{}', but it is a dask array; dask arrays "
"are not yet supprted in resample.interpolate(). Load "
"into memory with Dataset.load() before resampling."
.format(name)
)
axis = variable.get_axis_num(self._dim)
# We've previously checked for monotonicity along the
# re-sampling dimension (in __init__ via the GroupBy
# constructor), so we can avoid sorting the data again by
# passing 'assume_sorted=True'
f = interp1d(old_times, variable.data, kind=kind,
axis=axis, bounds_error=True,
assume_sorted=True)
interpolated = Variable(variable.dims, f(new_times))
data_vars[name] = interpolated
return Dataset(data_vars, coords)
ops.inject_reduce_methods(DatasetResample)
ops.inject_binary_ops(DatasetResample)
| |
# Copyright (c) 2011 Justin Santa Barbara
#
# 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_serialization import jsonutils
from oslo_utils import netutils
import requests
from six.moves import urllib
from cinder.i18n import _
from cinder.tests.unit import fake_constants as fake
class OpenStackApiException(Exception):
def __init__(self, message=None, response=None):
self.response = response
if not message:
message = 'Unspecified error'
if response:
message = _('%(message)s\nStatus Code: %(_status)s\n'
'Body: %(_body)s') % {'_status': response.status_code,
'_body': response.text}
super(OpenStackApiException, self).__init__(message)
class OpenStackApiAuthenticationException(OpenStackApiException):
def __init__(self, response=None, message=None):
if not message:
message = _("Authentication error")
super(OpenStackApiAuthenticationException, self).__init__(message,
response)
class OpenStackApiAuthorizationException(OpenStackApiException):
def __init__(self, response=None, message=None):
if not message:
message = _("Authorization error")
super(OpenStackApiAuthorizationException, self).__init__(message,
response)
class OpenStackApiNotFoundException(OpenStackApiException):
def __init__(self, response=None, message=None):
if not message:
message = _("Item not found")
super(OpenStackApiNotFoundException, self).__init__(message, response)
class TestOpenStackClient(object):
"""Simple OpenStack API Client.
This is a really basic OpenStack API client that is under our control,
so we can make changes / insert hooks for testing
"""
def __init__(self, auth_user, auth_key, auth_uri):
super(TestOpenStackClient, self).__init__()
self.auth_result = None
self.auth_user = auth_user
self.auth_key = auth_key
self.auth_uri = auth_uri
# default project_id
self.project_id = fake.PROJECT_ID
def request(self, url, method='GET', body=None, headers=None,
ssl_verify=True, stream=False):
_headers = {'Content-Type': 'application/json'}
_headers.update(headers or {})
parsed_url = urllib.parse.urlparse(url)
port = parsed_url.port
hostname = parsed_url.hostname
scheme = parsed_url.scheme
if netutils.is_valid_ipv6(hostname):
hostname = "[%s]" % hostname
relative_url = parsed_url.path
if parsed_url.query:
relative_url = relative_url + "?" + parsed_url.query
if port:
_url = "%s://%s:%d%s" % (scheme, hostname, int(port), relative_url)
else:
_url = "%s://%s%s" % (scheme, hostname, relative_url)
response = requests.request(method, _url, data=body, headers=_headers,
verify=ssl_verify, stream=stream)
return response
def _authenticate(self):
if self.auth_result:
return self.auth_result
auth_uri = self.auth_uri
headers = {'X-Auth-User': self.auth_user,
'X-Auth-Key': self.auth_key,
'X-Auth-Project-Id': self.project_id}
response = self.request(auth_uri,
headers=headers)
http_status = response.status_code
if http_status == 401:
raise OpenStackApiAuthenticationException(response=response)
self.auth_result = response.headers
return self.auth_result
def api_request(self, relative_uri, check_response_status=None, **kwargs):
auth_result = self._authenticate()
# NOTE(justinsb): httplib 'helpfully' converts headers to lower case
base_uri = auth_result['x-server-management-url']
full_uri = '%s/%s' % (base_uri, relative_uri)
headers = kwargs.setdefault('headers', {})
headers['X-Auth-Token'] = auth_result['x-auth-token']
response = self.request(full_uri, **kwargs)
http_status = response.status_code
if check_response_status:
if http_status not in check_response_status:
if http_status == 404:
raise OpenStackApiNotFoundException(response=response)
elif http_status == 401:
raise OpenStackApiAuthorizationException(response=response)
else:
raise OpenStackApiException(
message=_("Unexpected status code"),
response=response)
return response
def _decode_json(self, response):
body = response.text
if body:
return jsonutils.loads(body)
else:
return ""
def api_get(self, relative_uri, **kwargs):
kwargs.setdefault('check_response_status', [200])
response = self.api_request(relative_uri, **kwargs)
return self._decode_json(response)
def api_post(self, relative_uri, body, **kwargs):
kwargs['method'] = 'POST'
if body:
headers = kwargs.setdefault('headers', {})
headers['Content-Type'] = 'application/json'
kwargs['body'] = jsonutils.dumps(body)
kwargs.setdefault('check_response_status', [200, 202])
response = self.api_request(relative_uri, **kwargs)
return self._decode_json(response)
def api_put(self, relative_uri, body, **kwargs):
kwargs['method'] = 'PUT'
if body:
headers = kwargs.setdefault('headers', {})
headers['Content-Type'] = 'application/json'
kwargs['body'] = jsonutils.dumps(body)
kwargs.setdefault('check_response_status', [200, 202, 204])
response = self.api_request(relative_uri, **kwargs)
return self._decode_json(response)
def api_delete(self, relative_uri, **kwargs):
kwargs['method'] = 'DELETE'
kwargs.setdefault('check_response_status', [200, 202, 204])
return self.api_request(relative_uri, **kwargs)
def get_volume(self, volume_id):
return self.api_get('/volumes/%s' % volume_id)['volume']
def get_volumes(self, detail=True):
rel_url = '/volumes/detail' if detail else '/volumes'
return self.api_get(rel_url)['volumes']
def post_volume(self, volume):
return self.api_post('/volumes', volume)['volume']
def delete_volume(self, volume_id):
return self.api_delete('/volumes/%s' % volume_id)
def put_volume(self, volume_id, volume):
return self.api_put('/volumes/%s' % volume_id, volume)['volume']
def create_type(self, type_name, extra_specs=None):
type = {"volume_type": {"name": type_name}}
if extra_specs:
type['extra_specs'] = extra_specs
return self.api_post('/types', type)['volume_type']
| |
"""
Unittests for the ffs.filesystem module
"""
from __future__ import with_statement
import getpass
import os
import sys
import tempfile
import unittest
from mock import MagicMock, patch
if sys.version_info < (2, 7): import unittest2 as unittest
from ffs import exceptions, filesystem, nix
class BaseFilesystemTestCase(unittest.TestCase):
def setUp(self):
self.fs = filesystem.BaseFilesystem()
def test_exists(self):
"Interface raises"
with self.assertRaises(NotImplementedError):
self.fs.exists(None)
def test_sep(self):
"Sep raises"
with self.assertRaises(NotImplementedError):
sep = self.fs.sep
def test_getwd(self):
"Getwd raises"
with self.assertRaises(NotImplementedError):
self.fs.getwd()
def test_ls(self):
"Ls raises"
with self.assertRaises(NotImplementedError):
self.fs.ls(None)
def test_cd(self):
"Cd raises"
with self.assertRaises(NotImplementedError):
self.fs.cd(None)
def test_is_abspath(self):
"Is_abspath raises"
with self.assertRaises(NotImplementedError):
self.fs.is_abspath(None)
def test_open(self):
"Open raises"
with self.assertRaises(NotImplementedError):
self.fs.open(None)
def test_is_branch(self):
"Is_branch raises"
with self.assertRaises(NotImplementedError):
self.fs.is_branch(None)
def test_is_leaf(self):
"Is_leaf raises"
with self.assertRaises(NotImplementedError):
self.fs.is_leaf(None)
def test_expanduser(self):
"Expanduser raises"
with self.assertRaises(NotImplementedError):
self.fs.expanduser(None)
def test_abspath(self):
"Abspath raises"
with self.assertRaises(NotImplementedError):
self.fs.abspath(None)
def test_parent(self):
"Parent raises"
with self.assertRaises(NotImplementedError):
self.fs.parent(None)
def test_mkdir(self):
"Mkdir raises"
with self.assertRaises(NotImplementedError):
self.fs.mkdir(None)
def test_cp(self):
"Cp raises"
with self.assertRaises(NotImplementedError):
self.fs.cp(None, None)
def test_ln(self):
"Ln raises"
with self.assertRaises(NotImplementedError):
self.fs.ln(None, None)
def test_mv(self):
"Mv raises"
with self.assertRaises(NotImplementedError):
self.fs.mv(None, None)
def test_rm(self):
"Rm raises"
with self.assertRaises(NotImplementedError):
self.fs.rm(None)
def test_stat(self):
"Stat raises"
with self.assertRaises(NotImplementedError):
self.fs.stat(None)
def test_touch(self):
"Touch raises"
with self.assertRaises(NotImplementedError):
self.fs.touch(None)
def test_tempfile(self):
"Tempfile raises"
with self.assertRaises(NotImplementedError):
self.fs.tempfile()
def test_tempdir(self):
"Tempdir raises"
with self.assertRaises(NotImplementedError):
self.fs.tempdir()
class ReadOnlyFilesystemTestCase(unittest.TestCase):
def setUp(self):
self.fs = filesystem.ReadOnlyFilesystem()
def test_mkdir(self):
"Mkdir raises"
with self.assertRaises(exceptions.InappropriateError):
self.fs.mkdir(None)
def test_cp(self):
"Cp raises"
with self.assertRaises(exceptions.InappropriateError):
self.fs.cp(None, None)
def test_ln(self):
"Ln raises"
with self.assertRaises(exceptions.InappropriateError):
self.fs.ln(None, None)
def test_mv(self):
"Mv raises"
with self.assertRaises(exceptions.InappropriateError):
self.fs.mv(None, None)
def test_rm(self):
"Rm raises"
with self.assertRaises(exceptions.InappropriateError):
self.fs.rm(None)
def test_touch(self):
"Touch raises"
with self.assertRaises(exceptions.InappropriateError):
self.fs.touch(None)
def test_tempfile(self):
"Tempfile raises"
with self.assertRaises(exceptions.InappropriateError):
self.fs.tempfile()
def test_tempdir(self):
"Tempdir raises"
with self.assertRaises(exceptions.InappropriateError):
self.fs.tempdir()
class DiskFilesystemTestCase(unittest.TestCase):
def setUp(self):
self.tfile = tempfile.mktemp()
self.tdir = tempfile.mkdtemp()
nix.touch(self.tfile)
nix.mkdir_p(self.tdir)
self.fs = filesystem.DiskFilesystem()
def tearDown(self):
nix.rm(self.tfile, force=True)
nix.rm_r(self.tdir)
def test_exists(self):
"Call exists"
self.assertEqual(True, self.fs.exists(self.tfile))
self.assertEqual(False, self.fs.exists(tempfile.mktemp()))
def test_sep(self):
"Should be os.sep"
self.assertEqual(os.sep, self.fs.sep)
def test_getwd(self):
"Should be the curdir"
self.assertEqual(os.getcwd(), self.fs.getwd())
def test_ls(self):
"Should list"
with patch('ffs.filesystem.nix.ls', return_value=['this.txt']) as pls:
self.assertEqual(['this.txt'], self.fs.ls('/foo'))
pls.assert_called_with('/foo', all=None)
def test_cd(self):
"Should change dir"
with patch('ffs.filesystem.nix.cd') as pcd:
self.fs.cd('/foo')
pcd.assert_called_with('/foo')
def test_is_abspath(self):
"Yes or no for an abspath"
cases = [
(True, os.path.abspath('.')),
(False, 'foo')
]
for expected, p in cases:
self.assertEqual(expected, self.fs.is_abspath(p))
def test_is_branch(self):
"Predicate for dirs"
cases = [
(True, self.tdir),
(False, self.tfile)
]
for expected, p in cases:
self.assertEqual(expected, self.fs.is_branch(p))
def test_is_leaf(self):
"Predicate for files"
cases = [
(False, self.tdir),
(True, self.tfile)
]
for expected, p in cases:
self.assertEqual(expected, self.fs.is_leaf(p))
def test_parent(self):
"Parent branch"
self.assertEqual('/foo', self.fs.parent('/foo/bar'))
def test_open(self):
"Openit."
with patch('ffs.filesystem.open', create=True) as po:
po.return_value = 'filelike'
with patch.object(self.fs, 'expanduser') as pe:
pe.side_effect = lambda x: x
fh = self.fs.open(self.tfile, 'wb')
self.assertEqual('filelike', fh)
po.assert_called_with(self.tfile, 'wb')
pe.assert_called_with(self.tfile)
def test_expanduser(self):
"Expand ~"
if not sys.platform.startswith('win'):
user = getpass.getuser()
home = 'home'
if sys.platform == 'darwin':
home = 'Users'
expected = '/{0}/{1}/.emacs'.format(home, user)
self.assertEqual(expected, self.fs.expanduser('~/.emacs'))
def test_abspath(self):
"Abspath it"
with patch('os.path.abspath') as pabs:
self.fs.abspath('foo')
pabs.assert_called_with('foo')
def test_abspath_expanduser(self):
"Implicitly expanduser in abspath"
if not sys.platform.startswith('win'):
user = getpass.getuser()
home = 'home'
if sys.platform == 'darwin':
home = 'Users'
expected = '/{0}/{1}/.emacs'.format(home, user)
self.assertEqual(expected, self.fs.abspath('~/.emacs'))
def test_mkdir(self):
"Mkdir it"
with patch('ffs.nix.mkdir') as pabs:
self.fs.mkdir('foo')
pabs.assert_called_with('foo', parents=False)
def test_mkdir_parents(self):
"Should make parents"
with patch('ffs.nix.mkdir') as pabs:
self.fs.mkdir('foo', parents=True)
pabs.assert_called_with('foo', parents=True)
def test_cp(self):
"Copy it"
with patch('ffs.nix.cp') as pcp:
self.fs.cp('foo', 'bar')
pcp.assert_called_with('foo', 'bar', recursive = False)
def test_cp_recursive(self):
"Copy recursive"
with patch('ffs.nix.cp') as pcp:
self.fs.cp('foo', 'bar', recursive = True)
pcp.assert_called_with('foo', 'bar', recursive = True)
def test_ln(self):
"Link it"
with patch('ffs.nix.ln') as pln:
self.fs.ln('foo', 'bar')
pln.assert_called_with('foo', 'bar', symbolic=False)
def test_ln_s(self):
"Link it symbolically"
with patch('ffs.nix.ln_s') as pln:
self.fs.ln('foo', 'bar', symbolic=True)
pln.assert_called_with('foo', 'bar')
def test_mv(self):
"Move it"
with patch('ffs.nix.mv') as pmv:
self.fs.mv('foo', 'bar')
pmv.assert_called_with('foo', 'bar')
def test_touch(self):
"Should be able to touch"
newfile = self.fs.sep.join([self.tdir, 'some.txt'])
self.fs.touch(newfile)
self.assertTrue(os.path.exists(newfile))
def test_tempfile(self):
"Create something temporary"
tmpfile = self.fs.tempfile()
self.assertTrue(os.path.exists(tmpfile))
self.assertTrue(os.path.isfile(tmpfile))
def test_tempdir(self):
"Create a temp dir"
tmpdir = self.fs.tempdir()
self.assertTrue(os.path.exists(tmpdir))
self.assertTrue(os.path.isdir(tmpdir))
def test_rm(self):
"Remove a file"
self.assertTrue(os.path.exists(self.tfile))
self.fs.rm(self.tfile)
self.assertFalse(os.path.exists(self.tfile))
# def test_ln(self):
# "Link it"
# with patch('ffs.nix.ln') as pln:
# self.fs.ln('foo', 'bar')
# pln.assert_called_with('foo', 'bar', symbolic=False)
if __name__ == '__main__':
unittest.main()
| |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright 2011 - 2012, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Shared code between AMQP based openstack.common.rpc implementations.
The code in this module is shared between the rpc implementations based on
AMQP. Specifically, this includes impl_kombu and impl_qpid. impl_carrot also
uses AMQP, but is deprecated and predates this code.
"""
import collections
import logging
import threading
import uuid
from oslo.config import cfg
import six
from oslo.messaging._drivers import common as rpc_common
from oslo.messaging._drivers import pool
# FIXME(markmc): remove this
_ = lambda s: s
amqp_opts = [
cfg.BoolOpt('amqp_durable_queues',
default=False,
deprecated_name='rabbit_durable_queues',
deprecated_group='DEFAULT',
help='Use durable queues in amqp.'),
cfg.BoolOpt('amqp_auto_delete',
default=False,
help='Auto-delete queues in amqp.'),
# FIXME(markmc): this was toplevel in openstack.common.rpc
cfg.IntOpt('rpc_conn_pool_size',
default=30,
help='Size of RPC connection pool.'),
]
UNIQUE_ID = '_unique_id'
LOG = logging.getLogger(__name__)
class ConnectionPool(pool.Pool):
"""Class that implements a Pool of Connections."""
def __init__(self, conf, connection_cls):
self.connection_cls = connection_cls
self.conf = conf
super(ConnectionPool, self).__init__(self.conf.rpc_conn_pool_size)
self.reply_proxy = None
# TODO(comstud): Timeout connections not used in a while
def create(self):
LOG.debug(_('Pool creating new connection'))
return self.connection_cls(self.conf)
def empty(self):
for item in self.iter_free():
item.close()
# Force a new connection pool to be created.
# Note that this was added due to failing unit test cases. The issue
# is the above "while loop" gets all the cached connections from the
# pool and closes them, but never returns them to the pool, a pool
# leak. The unit tests hang waiting for an item to be returned to the
# pool. The unit tests get here via the tearDown() method. In the run
# time code, it gets here via cleanup() and only appears in service.py
# just before doing a sys.exit(), so cleanup() only happens once and
# the leakage is not a problem.
self.connection_cls.pool = None
_pool_create_sem = threading.Lock()
def get_connection_pool(conf, connection_cls):
with _pool_create_sem:
# Make sure only one thread tries to create the connection pool.
if not connection_cls.pool:
connection_cls.pool = ConnectionPool(conf, connection_cls)
return connection_cls.pool
class ConnectionContext(rpc_common.Connection):
"""The class that is actually returned to the create_connection() caller.
This is essentially a wrapper around Connection that supports 'with'.
It can also return a new Connection, or one from a pool.
The function will also catch when an instance of this class is to be
deleted. With that we can return Connections to the pool on exceptions
and so forth without making the caller be responsible for catching them.
If possible the function makes sure to return a connection to the pool.
"""
def __init__(self, conf, connection_pool, pooled=True, server_params=None):
"""Create a new connection, or get one from the pool."""
self.connection = None
self.conf = conf
self.connection_pool = connection_pool
if pooled:
self.connection = connection_pool.get()
else:
self.connection = connection_pool.connection_cls(
conf,
server_params=server_params)
self.pooled = pooled
def __enter__(self):
"""When with ConnectionContext() is used, return self."""
return self
def _done(self):
"""If the connection came from a pool, clean it up and put it back.
If it did not come from a pool, close it.
"""
if self.connection:
if self.pooled:
# Reset the connection so it's ready for the next caller
# to grab from the pool
self.connection.reset()
self.connection_pool.put(self.connection)
else:
try:
self.connection.close()
except Exception:
pass
self.connection = None
def __exit__(self, exc_type, exc_value, tb):
"""End of 'with' statement. We're done here."""
self._done()
def __del__(self):
"""Caller is done with this connection. Make sure we cleaned up."""
self._done()
def close(self):
"""Caller is done with this connection."""
self._done()
def create_consumer(self, topic, proxy, fanout=False):
self.connection.create_consumer(topic, proxy, fanout)
def create_worker(self, topic, proxy, pool_name):
self.connection.create_worker(topic, proxy, pool_name)
def join_consumer_pool(self, callback, pool_name, topic, exchange_name):
self.connection.join_consumer_pool(callback,
pool_name,
topic,
exchange_name)
def consume_in_thread(self):
self.connection.consume_in_thread()
def __getattr__(self, key):
"""Proxy all other calls to the Connection instance."""
if self.connection:
return getattr(self.connection, key)
else:
raise rpc_common.InvalidRPCConnectionReuse()
class ReplyProxy(ConnectionContext):
"""Connection class for RPC replies / callbacks."""
def __init__(self, conf, connection_pool):
self._call_waiters = {}
self._num_call_waiters = 0
self._num_call_waiters_wrn_threshold = 10
self._reply_q = 'reply_' + uuid.uuid4().hex
super(ReplyProxy, self).__init__(conf, connection_pool, pooled=False)
self.declare_direct_consumer(self._reply_q, self._process_data)
self.consume_in_thread()
def _process_data(self, message_data):
msg_id = message_data.pop('_msg_id', None)
waiter = self._call_waiters.get(msg_id)
if not waiter:
LOG.warn(_('No calling threads waiting for msg_id : %(msg_id)s'
', message : %(data)s'), {'msg_id': msg_id,
'data': message_data})
LOG.warn(_('_call_waiters: %s') % str(self._call_waiters))
else:
waiter.put(message_data)
def add_call_waiter(self, waiter, msg_id):
self._num_call_waiters += 1
if self._num_call_waiters > self._num_call_waiters_wrn_threshold:
LOG.warn(_('Number of call waiters is greater than warning '
'threshold: %d. There could be a MulticallProxyWaiter '
'leak.') % self._num_call_waiters_wrn_threshold)
self._num_call_waiters_wrn_threshold *= 2
self._call_waiters[msg_id] = waiter
def del_call_waiter(self, msg_id):
self._num_call_waiters -= 1
del self._call_waiters[msg_id]
def get_reply_q(self):
return self._reply_q
def msg_reply(conf, msg_id, reply_q, connection_pool, reply=None,
failure=None, ending=False, log_failure=True):
"""Sends a reply or an error on the channel signified by msg_id.
Failure should be a sys.exc_info() tuple.
"""
with ConnectionContext(conf, connection_pool) as conn:
if failure:
failure = rpc_common.serialize_remote_exception(failure,
log_failure)
msg = {'result': reply, 'failure': failure}
if ending:
msg['ending'] = True
_add_unique_id(msg)
# If a reply_q exists, add the msg_id to the reply and pass the
# reply_q to direct_send() to use it as the response queue.
# Otherwise use the msg_id for backward compatibility.
if reply_q:
msg['_msg_id'] = msg_id
conn.direct_send(reply_q, rpc_common.serialize_msg(msg))
else:
conn.direct_send(msg_id, rpc_common.serialize_msg(msg))
class RpcContext(rpc_common.CommonRpcContext):
"""Context that supports replying to a rpc.call."""
def __init__(self, **kwargs):
self.msg_id = kwargs.pop('msg_id', None)
self.reply_q = kwargs.pop('reply_q', None)
self.conf = kwargs.pop('conf')
super(RpcContext, self).__init__(**kwargs)
def deepcopy(self):
values = self.to_dict()
values['conf'] = self.conf
values['msg_id'] = self.msg_id
values['reply_q'] = self.reply_q
return self.__class__(**values)
def reply(self, reply=None, failure=None, ending=False,
connection_pool=None, log_failure=True):
if self.msg_id:
msg_reply(self.conf, self.msg_id, self.reply_q, connection_pool,
reply, failure, ending, log_failure)
if ending:
self.msg_id = None
def unpack_context(conf, msg):
"""Unpack context from msg."""
context_dict = {}
for key in list(msg.keys()):
# NOTE(vish): Some versions of Python don't like unicode keys
# in kwargs.
key = str(key)
if key.startswith('_context_'):
value = msg.pop(key)
context_dict[key[9:]] = value
context_dict['msg_id'] = msg.pop('_msg_id', None)
context_dict['reply_q'] = msg.pop('_reply_q', None)
context_dict['conf'] = conf
ctx = RpcContext.from_dict(context_dict)
rpc_common._safe_log(LOG.debug, _('unpacked context: %s'), ctx.to_dict())
return ctx
def pack_context(msg, context):
"""Pack context into msg.
Values for message keys need to be less than 255 chars, so we pull
context out into a bunch of separate keys. If we want to support
more arguments in rabbit messages, we may want to do the same
for args at some point.
"""
if isinstance(context, dict):
context_d = six.iteritems(context)
else:
context_d = six.iteritems(context.to_dict())
msg.update(('_context_%s' % key, value)
for (key, value) in context_d)
class _MsgIdCache(object):
"""This class checks any duplicate messages."""
# NOTE: This value is considered can be a configuration item, but
# it is not necessary to change its value in most cases,
# so let this value as static for now.
DUP_MSG_CHECK_SIZE = 16
def __init__(self, **kwargs):
self.prev_msgids = collections.deque([],
maxlen=self.DUP_MSG_CHECK_SIZE)
def check_duplicate_message(self, message_data):
"""AMQP consumers may read same message twice when exceptions occur
before ack is returned. This method prevents doing it.
"""
try:
msg_id = message_data.pop(UNIQUE_ID)
except KeyError:
return
if msg_id in self.prev_msgids:
raise rpc_common.DuplicateMessageError(msg_id=msg_id)
return msg_id
def add(self, msg_id):
if msg_id and msg_id not in self.prev_msgids:
self.prev_msgids.append(msg_id)
def _add_unique_id(msg):
"""Add unique_id for checking duplicate messages."""
unique_id = uuid.uuid4().hex
msg.update({UNIQUE_ID: unique_id})
LOG.debug(_('UNIQUE_ID is %s.') % (unique_id))
def get_control_exchange(conf):
return conf.control_exchange
| |
# Copyright 2013 OpenStack Foundation
# Copyright 2013 Rackspace Hosting
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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 collections import deque
from proboscis import test
from proboscis import asserts
from proboscis import after_class
from proboscis import before_class
from trove.tests.config import CONFIG
from trove.tests.api.instances import instance_info
from trove.tests.api.instances import VOLUME_SUPPORT
from trove.tests.util.users import Requirements
from trove.tests.util import assert_contains
from trove.tests.util import create_dbaas_client
from trove.common.utils import poll_until
@test(groups=["dbaas.api.mgmt.malformed_json"])
class MalformedJson(object):
@before_class
def setUp(self):
self.reqs = Requirements(is_admin=False)
self.user = CONFIG.users.find_user(self.reqs)
self.dbaas = create_dbaas_client(self.user)
volume = None
if VOLUME_SUPPORT:
volume = {"size": 1}
self.instance = self.dbaas.instances.create(
name="qe_instance",
flavor_id=instance_info.dbaas_flavor_href,
volume=volume,
databases=[{"name": "firstdb", "character_set": "latin2",
"collate": "latin2_general_ci"}])
@after_class
def tearDown(self):
self.dbaas.instances.delete(self.instance)
@test
def test_bad_instance_data(self):
databases = "foo"
users = "bar"
try:
self.dbaas.instances.create("bad_instance", 3, 3,
databases=databases, users=users)
except Exception as e:
resp, body = self.dbaas.client.last_response
httpCode = resp.status
asserts.assert_equal(httpCode, 400,
"Create instance failed with code %s,"
" exception %s" % (httpCode, e))
databases = "u'foo'"
users = "u'bar'"
assert_contains(
e.message,
["Validation error:",
"instance['databases'] %s is not of type 'array'" % databases,
"instance['users'] %s is not of type 'array'" % users,
"instance['volume'] 3 is not of type 'object'"])
@test
def test_bad_database_data(self):
_bad_db_data = "{foo}"
try:
self.dbaas.databases.create(self.instance.id, _bad_db_data)
except Exception as e:
resp, body = self.dbaas.client.last_response
httpCode = resp.status
asserts.assert_equal(httpCode, 400,
"Create database failed with code %s, "
"exception %s" % (httpCode, e))
_bad_db_data = "u'{foo}'"
asserts.assert_equal(e.message,
"Validation error: "
"databases %s is not of type 'array'" %
_bad_db_data)
@test
def test_bad_user_data(self):
def format_path(values):
values = list(values)
msg = "%s%s" % (values[0],
''.join(['[%r]' % i for i in values[1:]]))
return msg
_user = []
_user_name = "F343jasdf"
_user.append({"name12": _user_name,
"password12": "password"})
try:
self.dbaas.users.create(self.instance.id, _user)
except Exception as e:
resp, body = self.dbaas.client.last_response
httpCode = resp.status
asserts.assert_equal(httpCode, 400,
"Create user failed with code %s, "
"exception %s" % (httpCode, e))
err_1 = format_path(deque(('users', 0)))
assert_contains(
e.message,
["Validation error:",
"%(err_1)s 'name' is a required property" % {'err_1': err_1},
"%(err_1)s 'password' is a required property"
% {'err_1': err_1}])
@test
def test_bad_resize_instance_data(self):
def _check_instance_status():
inst = self.dbaas.instances.get(self.instance)
if inst.status == "ACTIVE":
return True
else:
return False
poll_until(_check_instance_status)
try:
self.dbaas.instances.resize_instance(self.instance.id, "")
except Exception as e:
resp, body = self.dbaas.client.last_response
httpCode = resp.status
asserts.assert_equal(httpCode, 400,
"Resize instance failed with code %s, "
"exception %s" % (httpCode, e))
@test
def test_bad_resize_vol_data(self):
def _check_instance_status():
inst = self.dbaas.instances.get(self.instance)
if inst.status == "ACTIVE":
return True
else:
return False
poll_until(_check_instance_status)
data = "bad data"
try:
self.dbaas.instances.resize_volume(self.instance.id, data)
except Exception as e:
resp, body = self.dbaas.client.last_response
httpCode = resp.status
asserts.assert_equal(httpCode, 400,
"Resize instance failed with code %s, "
"exception %s" % (httpCode, e))
data = "u'bad data'"
assert_contains(
e.message,
["Validation error:",
"resize['volume']['size'] %s is not valid under "
"any of the given schemas" % data,
"%s is not of type 'integer'" % data,
"%s does not match '^[0-9]+$'" % data])
@test
def test_bad_change_user_password(self):
password = ""
users = [{"name": password}]
def _check_instance_status():
inst = self.dbaas.instances.get(self.instance)
if inst.status == "ACTIVE":
return True
else:
return False
poll_until(_check_instance_status)
try:
self.dbaas.users.change_passwords(self.instance, users)
except Exception as e:
resp, body = self.dbaas.client.last_response
httpCode = resp.status
asserts.assert_equal(httpCode, 400,
"Change usr/passwd failed with code %s, "
"exception %s" % (httpCode, e))
password = "u''"
assert_contains(
e.message,
["Validation error: users[0] 'password' "
"is a required property",
"users[0]['name'] %s is too short" % password,
"users[0]['name'] %s does not match "
"'^.*[0-9a-zA-Z]+.*$'" % password])
@test
def test_bad_grant_user_access(self):
dbs = []
def _check_instance_status():
inst = self.dbaas.instances.get(self.instance)
if inst.status == "ACTIVE":
return True
else:
return False
poll_until(_check_instance_status)
try:
self.dbaas.users.grant(self.instance, self.user, dbs)
except Exception as e:
resp, body = self.dbaas.client.last_response
httpCode = resp.status
asserts.assert_equal(httpCode, 400,
"Grant user access failed with code %s, "
"exception %s" % (httpCode, e))
@test
def test_bad_revoke_user_access(self):
db = ""
def _check_instance_status():
inst = self.dbaas.instances.get(self.instance)
if inst.status == "ACTIVE":
return True
else:
return False
poll_until(_check_instance_status)
try:
self.dbaas.users.revoke(self.instance, self.user, db)
except Exception as e:
resp, body = self.dbaas.client.last_response
httpCode = resp.status
asserts.assert_equal(httpCode, 404,
"Revoke user access failed w/code %s, "
"exception %s" % (httpCode, e))
asserts.assert_equal(e.message, "The resource could not be found.")
@test
def test_bad_body_flavorid_create_instance(self):
flavorId = ["?"]
try:
self.dbaas.instances.create("test_instance",
flavorId,
2)
except Exception as e:
resp, body = self.dbaas.client.last_response
httpCode = resp.status
asserts.assert_equal(httpCode, 400,
"Create instance failed with code %s, "
"exception %s" % (httpCode, e))
flavorId = [u'?']
assert_contains(
e.message,
["Validation error:",
"instance['flavorRef'] %s is not valid "
"under any of the given schemas" % flavorId,
"%s is not of type 'string'" % flavorId,
"%s is not of type 'string'" % flavorId,
"%s is not of type 'integer'" % flavorId,
"instance['volume'] 2 is not of type 'object'"])
@test
def test_bad_body_datastore_create_instance(self):
datastore = "*"
datastore_version = "*"
try:
self.dbaas.instances.create("test_instance",
3, {"size": 2},
datastore=datastore,
datastore_version=datastore_version)
except Exception as e:
resp, body = self.dbaas.client.last_response
httpCode = resp.status
asserts.assert_equal(httpCode, 400,
"Create instance failed with code %s, "
"exception %s" % (httpCode, e))
assert_contains(
e.message,
["Validation error:",
"instance['datastore']['type']"
" u'%s' does not match"
" '^.*[0-9a-zA-Z]+.*$'" % datastore,
"instance['datastore']['version'] u'%s' "
"does not match '^.*[0-9a-zA-Z]+.*$'" % datastore_version])
@test
def test_bad_body_volsize_create_instance(self):
volsize = "h3ll0"
try:
self.dbaas.instances.create("test_instance",
"1",
volsize)
except Exception as e:
resp, body = self.dbaas.client.last_response
httpCode = resp.status
asserts.assert_equal(httpCode, 400,
"Create instance failed with code %s, "
"exception %s" % (httpCode, e))
volsize = "u'h3ll0'"
asserts.assert_equal(e.message,
"Validation error: "
"instance['volume'] %s is not of "
"type 'object'" % volsize)
| |
"""
byceps.blueprints.admin.shop.article.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from datetime import datetime
from decimal import Decimal
from flask import abort, request
from flask_babel import gettext
from .....permissions.shop import ShopArticlePermission
from .....services.brand import service as brand_service
from .....services.party import service as party_service
from .....services.party.transfer.models import Party
from .....services.shop.article import (
sequence_service as article_sequence_service,
service as article_service,
)
from .....services.shop.article.transfer.models import (
ArticleType,
get_article_type_label,
)
from .....services.shop.order import (
action_registry_service,
action_service,
ordered_articles_service,
service as order_service,
)
from .....services.shop.order.transfer.models import PaymentState
from .....services.shop.shop import service as shop_service
from .....services.ticketing import category_service as ticket_category_service
from .....services.ticketing.transfer.models import TicketCategory
from .....services.user import service as user_service
from .....services.user_badge import badge_service
from .....typing import BrandID
from .....util.framework.blueprint import create_blueprint
from .....util.framework.flash import flash_error, flash_success
from .....util.framework.templating import templated
from .....util.templatefilters import local_tz_to_utc, utc_to_local_tz
from .....util.views import permission_required, redirect_to, respond_no_content
from .forms import (
ArticleCreateForm,
ArticleUpdateForm,
ArticleAttachmentCreateForm,
ArticleNumberSequenceCreateForm,
RegisterBadgeAwardingActionForm,
RegisterTicketBundlesCreationActionForm,
RegisterTicketsCreationActionForm,
)
blueprint = create_blueprint('shop_article_admin', __name__)
TAX_RATE_DISPLAY_FACTOR = Decimal('100')
@blueprint.get('/for_shop/<shop_id>', defaults={'page': 1})
@blueprint.get('/for_shop/<shop_id>/pages/<int:page>')
@permission_required(ShopArticlePermission.view)
@templated
def index_for_shop(shop_id, page):
"""List articles for that shop."""
shop = _get_shop_or_404(shop_id)
brand = brand_service.get_brand(shop.brand_id)
per_page = request.args.get('per_page', type=int, default=15)
articles = article_service.get_articles_for_shop_paginated(
shop.id, page, per_page
)
return {
'shop': shop,
'brand': brand,
'articles': articles,
}
@blueprint.get('/<uuid:article_id>')
@permission_required(ShopArticlePermission.view)
@templated
def view(article_id):
"""Show a single article."""
article = article_service.find_article_with_details(article_id)
if article is None:
abort(404)
shop = shop_service.get_shop(article.shop_id)
brand = brand_service.get_brand(shop.brand_id)
type_label = get_article_type_label(article.type_)
totals = ordered_articles_service.count_ordered_articles(
article.item_number
)
actions = action_service.get_actions_for_article(article.item_number)
actions.sort(key=lambda a: a.payment_state.name, reverse=True)
return {
'article': article,
'shop': shop,
'brand': brand,
'type_label': type_label,
'totals': totals,
'PaymentState': PaymentState,
'actions': actions,
}
@blueprint.get('/<uuid:article_id>/ordered')
@permission_required(ShopArticlePermission.view)
@templated
def view_ordered(article_id):
"""List the people that have ordered this article, and the
corresponding quantities.
"""
article = _get_article_or_404(article_id)
shop = shop_service.get_shop(article.shop_id)
brand = brand_service.get_brand(shop.brand_id)
line_items = ordered_articles_service.get_line_items_for_article(
article.item_number
)
quantity_total = sum(item.quantity for item in line_items)
order_numbers = {item.order_number for item in line_items}
orders = order_service.find_orders_by_order_numbers(order_numbers)
orders_by_order_numbers = {order.order_number: order for order in orders}
user_ids = {order.placed_by_id for order in orders}
users = user_service.get_users(user_ids, include_avatars=True)
users_by_id = user_service.index_users_by_id(users)
def transform(line_item):
quantity = line_item.quantity
order = orders_by_order_numbers[line_item.order_number]
user = users_by_id[order.placed_by_id]
return quantity, order, user
quantities_orders_users = list(map(transform, line_items))
return {
'article': article,
'shop': shop,
'brand': brand,
'quantity_total': quantity_total,
'quantities_orders_users': quantities_orders_users,
'now': datetime.utcnow(),
}
# -------------------------------------------------------------------- #
# create
@blueprint.get('/for_shop/<shop_id>/create')
@permission_required(ShopArticlePermission.create)
@templated
def create_form(shop_id, erroneous_form=None):
"""Show form to create an article."""
shop = _get_shop_or_404(shop_id)
brand = brand_service.get_brand(shop.brand_id)
article_number_sequences = (
article_sequence_service.get_article_number_sequences_for_shop(shop.id)
)
article_number_sequence_available = bool(article_number_sequences)
form = (
erroneous_form
if erroneous_form
else ArticleCreateForm(price=Decimal('0.0'), tax_rate=Decimal('19.0'))
)
form.set_article_number_sequence_choices(article_number_sequences)
return {
'shop': shop,
'brand': brand,
'article_number_sequence_available': article_number_sequence_available,
'form': form,
}
@blueprint.post('/for_shop/<shop_id>')
@permission_required(ShopArticlePermission.create)
def create(shop_id):
"""Create an article."""
shop = _get_shop_or_404(shop_id)
form = ArticleCreateForm(request.form)
if not form.validate():
return create_form(shop_id, form)
article_number_sequences = (
article_sequence_service.get_article_number_sequences_for_shop(shop.id)
)
if not article_number_sequences:
flash_error(
gettext('No article number sequences are defined for this shop.')
)
return create_form(shop_id, form)
form.set_article_number_sequence_choices(article_number_sequences)
if not form.validate():
return create_form(shop_id, form)
article_number_sequence_id = form.article_number_sequence_id.data
if not article_number_sequence_id:
flash_error(gettext('No valid article number sequence was specified.'))
return create_form(shop_id, form)
article_number_sequence = (
article_sequence_service.get_article_number_sequence(
article_number_sequence_id
)
)
if article_number_sequence.shop_id != shop.id:
flash_error(gettext('No valid article number sequence was specified.'))
return create_form(shop_id, form)
try:
item_number = article_sequence_service.generate_article_number(
article_number_sequence.id
)
except article_sequence_service.ArticleNumberGenerationFailed as e:
abort(500, e.message)
type_ = ArticleType[form.type_.data]
description = form.description.data.strip()
price = form.price.data
tax_rate = form.tax_rate.data / TAX_RATE_DISPLAY_FACTOR
total_quantity = form.total_quantity.data
quantity = total_quantity
max_quantity_per_order = form.max_quantity_per_order.data
shipping_required = type_ == ArticleType.physical
article = article_service.create_article(
shop.id,
item_number,
type_,
description,
price,
tax_rate,
total_quantity,
max_quantity_per_order,
shipping_required,
)
flash_success(
gettext(
'Article "%(item_number)s" has been created.',
item_number=article.item_number,
)
)
return redirect_to('.view', article_id=article.id)
# -------------------------------------------------------------------- #
# update
@blueprint.get('/<uuid:article_id>/update')
@permission_required(ShopArticlePermission.update)
@templated
def update_form(article_id, erroneous_form=None):
"""Show form to update an article."""
article = _get_article_or_404(article_id)
shop = shop_service.get_shop(article.shop_id)
brand = brand_service.get_brand(shop.brand_id)
if article.available_from:
article.available_from = utc_to_local_tz(article.available_from)
if article.available_until:
article.available_until = utc_to_local_tz(article.available_until)
form = (
erroneous_form
if erroneous_form
else ArticleUpdateForm(
obj=article,
available_from_date=article.available_from.date()
if article.available_from
else None,
available_from_time=article.available_from.time()
if article.available_from
else None,
available_until_date=article.available_until.date()
if article.available_until
else None,
available_until_time=article.available_until.time()
if article.available_until
else None,
)
)
form.tax_rate.data = article.tax_rate * TAX_RATE_DISPLAY_FACTOR
return {
'article': article,
'shop': shop,
'brand': brand,
'form': form,
}
@blueprint.post('/<uuid:article_id>')
@permission_required(ShopArticlePermission.update)
def update(article_id):
"""Update an article."""
article = _get_article_or_404(article_id)
form = ArticleUpdateForm(request.form)
if not form.validate():
return update_form(article_id, form)
description = form.description.data.strip()
price = form.price.data
tax_rate = form.tax_rate.data / TAX_RATE_DISPLAY_FACTOR
if form.available_from_date.data and form.available_from_time.data:
available_from = local_tz_to_utc(
datetime.combine(
form.available_from_date.data, form.available_from_time.data
)
)
else:
available_from = None
if form.available_until_date.data and form.available_until_time.data:
available_until = local_tz_to_utc(
datetime.combine(
form.available_until_date.data, form.available_until_time.data
)
)
else:
available_until = None
total_quantity = form.total_quantity.data
max_quantity_per_order = form.max_quantity_per_order.data
not_directly_orderable = form.not_directly_orderable.data
separate_order_required = form.separate_order_required.data
article = article_service.update_article(
article.id,
description,
price,
tax_rate,
available_from,
available_until,
total_quantity,
max_quantity_per_order,
not_directly_orderable,
separate_order_required,
)
flash_success(
gettext(
'Article "%(description)s" has been updated.',
description=article.description,
)
)
return redirect_to('.view', article_id=article.id)
# -------------------------------------------------------------------- #
# article attachments
@blueprint.get('/<uuid:article_id>/attachments/create')
@permission_required(ShopArticlePermission.update)
@templated
def attachment_create_form(article_id, erroneous_form=None):
"""Show form to attach an article to another article."""
article = _get_article_or_404(article_id)
shop = shop_service.get_shop(article.shop_id)
brand = brand_service.get_brand(shop.brand_id)
attachable_articles = article_service.get_attachable_articles(article.id)
form = (
erroneous_form
if erroneous_form
else ArticleAttachmentCreateForm(quantity=0)
)
form.set_article_to_attach_choices(attachable_articles)
return {
'article': article,
'shop': shop,
'brand': brand,
'form': form,
}
@blueprint.post('/<uuid:article_id>/attachments')
@permission_required(ShopArticlePermission.update)
def attachment_create(article_id):
"""Attach an article to another article."""
article = _get_article_or_404(article_id)
attachable_articles = article_service.get_attachable_articles(article.id)
form = ArticleAttachmentCreateForm(request.form)
form.set_article_to_attach_choices(attachable_articles)
if not form.validate():
return attachment_create_form(article_id, form)
article_to_attach_id = form.article_to_attach_id.data
article_to_attach = article_service.get_article(article_to_attach_id)
quantity = form.quantity.data
article_service.attach_article(
article_to_attach.item_number, quantity, article.item_number
)
flash_success(
gettext(
'Article "%(article_to_attach_item_number)s" has been attached %(quantity)s times to article "%(article_item_number)s".',
article_to_attach_item_number=article_to_attach.item_number,
quantity=quantity,
article_item_number=article.item_number,
)
)
return redirect_to('.view', article_id=article.id)
@blueprint.delete('/attachments/<uuid:article_id>')
@permission_required(ShopArticlePermission.update)
@respond_no_content
def attachment_remove(article_id):
"""Remove the attachment link from one article to another."""
attached_article = article_service.find_attached_article(article_id)
if attached_article is None:
abort(404)
article = attached_article.article
attached_to_article = attached_article.attached_to_article
article_service.unattach_article(attached_article.id)
flash_success(
gettext(
'Article "%(article_item_number)s" is no longer attached to article "%(attached_to_article_item_number)s".',
article_item_number=article.item_number,
attached_to_article_item_number=attached_to_article.item_number,
)
)
# -------------------------------------------------------------------- #
# actions
@blueprint.get('/<uuid:article_id>/actions/badge_awarding/create')
@permission_required(ShopArticlePermission.update)
@templated
def action_create_form_for_badge_awarding(article_id, erroneous_form=None):
"""Show form to register a badge awarding action for the article."""
article = _get_article_or_404(article_id)
shop = shop_service.get_shop(article.shop_id)
brand = brand_service.get_brand(shop.brand_id)
badges = badge_service.get_all_badges()
form = (
erroneous_form if erroneous_form else RegisterBadgeAwardingActionForm()
)
form.set_badge_choices(badges)
return {
'article': article,
'shop': shop,
'brand': brand,
'form': form,
}
@blueprint.post('/<uuid:article_id>/actions/badge_awarding')
@permission_required(ShopArticlePermission.update)
def action_create_for_badge_awarding(article_id):
"""Register a badge awarding action for the article."""
article = _get_article_or_404(article_id)
badges = badge_service.get_all_badges()
form = RegisterBadgeAwardingActionForm(request.form)
form.set_badge_choices(badges)
if not form.validate():
return action_create_form_for_badge_awarding(article_id, form)
badge_id = form.badge_id.data
badge = badge_service.get_badge(badge_id)
action_registry_service.register_badge_awarding(
article.item_number, badge.id
)
flash_success(gettext('Action has been added.'))
return redirect_to('.view', article_id=article.id)
@blueprint.get('/<uuid:article_id>/actions/tickets_creation/create')
@permission_required(ShopArticlePermission.update)
@templated
def action_create_form_for_tickets_creation(article_id, erroneous_form=None):
"""Show form to register a tickets creation action for the article."""
article = _get_article_or_404(article_id)
shop = shop_service.get_shop(article.shop_id)
brand = brand_service.get_brand(shop.brand_id)
form = (
erroneous_form
if erroneous_form
else RegisterTicketsCreationActionForm()
)
form.set_category_choices(_get_categories_with_parties(brand.id))
return {
'article': article,
'shop': shop,
'brand': brand,
'form': form,
}
@blueprint.post('/<uuid:article_id>/actions/tickets_creation')
@permission_required(ShopArticlePermission.update)
def action_create_for_tickets_creation(article_id):
"""Register a tickets creation action for the article."""
article = _get_article_or_404(article_id)
shop = shop_service.get_shop(article.shop_id)
brand = brand_service.get_brand(shop.brand_id)
form = RegisterTicketsCreationActionForm(request.form)
form.set_category_choices(_get_categories_with_parties(brand.id))
if not form.validate():
return action_create_form_for_tickets_creation(article_id, form)
category_id = form.category_id.data
category = ticket_category_service.find_category(category_id)
if category is None:
raise ValueError(f'Unknown category ID "{category_id}"')
action_registry_service.register_tickets_creation(
article.item_number, category.id
)
flash_success(gettext('Action has been added.'))
return redirect_to('.view', article_id=article.id)
@blueprint.get('/<uuid:article_id>/actions/ticket_bundles_creation/create')
@permission_required(ShopArticlePermission.update)
@templated
def action_create_form_for_ticket_bundles_creation(
article_id, erroneous_form=None
):
"""Show form to register a ticket bundles creation action for the article."""
article = _get_article_or_404(article_id)
shop = shop_service.get_shop(article.shop_id)
brand = brand_service.get_brand(shop.brand_id)
form = (
erroneous_form
if erroneous_form
else RegisterTicketBundlesCreationActionForm()
)
form.set_category_choices(_get_categories_with_parties(brand.id))
return {
'article': article,
'shop': shop,
'brand': brand,
'form': form,
}
@blueprint.post('/<uuid:article_id>/actions/ticket_bundles_creation')
@permission_required(ShopArticlePermission.update)
def action_create_for_ticket_bundles_creation(article_id):
"""Register a ticket bundles creation action for the article."""
article = _get_article_or_404(article_id)
shop = shop_service.get_shop(article.shop_id)
brand = brand_service.get_brand(shop.brand_id)
form = RegisterTicketBundlesCreationActionForm(request.form)
form.set_category_choices(_get_categories_with_parties(brand.id))
if not form.validate():
return action_create_form_for_ticket_bundles_creation(article_id, form)
category_id = form.category_id.data
category = ticket_category_service.find_category(category_id)
if category is None:
raise ValueError(f'Unknown category ID "{category_id}"')
ticket_quantity = form.ticket_quantity.data
action_registry_service.register_ticket_bundles_creation(
article.item_number, category.id, ticket_quantity
)
flash_success(gettext('Action has been added.'))
return redirect_to('.view', article_id=article.id)
def _get_categories_with_parties(
brand_id: BrandID,
) -> set[tuple[TicketCategory, Party]]:
return {
(category, party)
for party in party_service.get_active_parties(brand_id)
for category in ticket_category_service.get_categories_for_party(
party.id
)
}
@blueprint.delete('/actions/<uuid:action_id>')
@permission_required(ShopArticlePermission.update)
@respond_no_content
def action_remove(action_id):
"""Remove the action from the article."""
action = action_service.find_action(action_id)
if action is None:
abort(404)
action_service.delete_action(action.id)
flash_success(gettext('Action has been removed.'))
# -------------------------------------------------------------------- #
# article number sequences
@blueprint.get('/number_sequences/for_shop/<shop_id>/create')
@permission_required(ShopArticlePermission.create)
@templated
def create_number_sequence_form(shop_id, erroneous_form=None):
"""Show form to create an article number sequence."""
shop = _get_shop_or_404(shop_id)
brand = brand_service.get_brand(shop.brand_id)
form = (
erroneous_form if erroneous_form else ArticleNumberSequenceCreateForm()
)
return {
'shop': shop,
'brand': brand,
'form': form,
}
@blueprint.post('/number_sequences/for_shop/<shop_id>')
@permission_required(ShopArticlePermission.create)
def create_number_sequence(shop_id):
"""Create an article number sequence."""
shop = _get_shop_or_404(shop_id)
form = ArticleNumberSequenceCreateForm(request.form)
if not form.validate():
return create_number_sequence_form(shop_id, form)
prefix = form.prefix.data.strip()
sequence_id = article_sequence_service.create_article_number_sequence(
shop.id, prefix
)
if sequence_id is None:
flash_error(
gettext(
'Article number sequence could not be created. '
'Is prefix "%(prefix)s" already defined?',
prefix=prefix,
)
)
return create_number_sequence_form(shop.id, form)
flash_success(
gettext(
'Article number sequence with prefix "%(prefix)s" has been created.',
prefix=prefix,
)
)
return redirect_to('.index_for_shop', shop_id=shop.id)
# -------------------------------------------------------------------- #
# helpers
def _get_shop_or_404(shop_id):
shop = shop_service.find_shop(shop_id)
if shop is None:
abort(404)
return shop
def _get_article_or_404(article_id):
article = article_service.find_db_article(article_id)
if article is None:
abort(404)
return article
| |
from urllib.parse import urljoin
from pyramid.httpexceptions import HTTPSeeOther
from pyramid.response import Response
from libweasyl import ratings
from libweasyl import staff
from libweasyl.text import markdown, slug_for
from weasyl import (
character, comment, define, folder, journal, macro, profile,
report, searchtag, shout, submission, orm)
from weasyl.config import config_read_bool
from weasyl.controllers.decorators import login_required, supports_json, token_checked
from weasyl.error import WeasylError
from weasyl.login import get_user_agent_id
# Content submission functions
@login_required
def submit_(request):
if not define.is_vouched_for(request.userid):
raise WeasylError("vouchRequired")
return Response(define.webpage(request.userid, "submit/submit.html", title="Submit Artwork"))
@login_required
def submit_visual_get_(request):
if not define.is_vouched_for(request.userid):
raise WeasylError("vouchRequired")
form = request.web_input(title='', tags=[], description='', imageURL='', baseURL='')
if form.baseURL:
form.imageURL = urljoin(form.baseURL, form.imageURL)
return Response(define.webpage(request.userid, "submit/visual.html", [
# Folders
folder.select_flat(request.userid),
# Subtypes
[i for i in macro.MACRO_SUBCAT_LIST if 1000 <= i[0] < 2000],
profile.get_user_ratings(request.userid),
form,
], title="Visual Artwork"))
@login_required
@token_checked
def submit_visual_post_(request):
form = request.web_input(submitfile="", thumbfile="", title="", folderid="",
subtype="", rating="", content="",
tags="", imageURL="")
tags = searchtag.parse_tags(form.tags)
if not config_read_bool("allow_submit"):
raise WeasylError("FeatureDisabled")
if not define.is_vouched_for(request.userid):
raise WeasylError("vouchRequired")
rating = ratings.CODE_MAP.get(define.get_int(form.rating))
if not rating:
raise WeasylError("ratingInvalid")
s = orm.Submission()
s.title = form.title
s.rating = rating
s.content = form.content
s.folderid = define.get_int(form.folderid) or None
s.subtype = define.get_int(form.subtype)
s.submitter_ip_address = request.client_addr
s.submitter_user_agent_id = get_user_agent_id(ua_string=request.user_agent)
submitid = submission.create_visual(
request.userid, s, friends_only='friends' in request.POST, tags=tags,
imageURL=form.imageURL, thumbfile=form.thumbfile, submitfile=form.submitfile,
critique='critique' in request.POST, create_notifications=('nonotification' not in form))
if 'customthumb' in form:
raise HTTPSeeOther(location="/manage/thumbnail?submitid=%i" % (submitid,))
else:
raise HTTPSeeOther(location="/submission/%i/%s" % (submitid, slug_for(form.title)))
@login_required
def submit_literary_get_(request):
if not define.is_vouched_for(request.userid):
raise WeasylError("vouchRequired")
return Response(define.webpage(request.userid, "submit/literary.html", [
# Folders
folder.select_flat(request.userid),
# Subtypes
[i for i in macro.MACRO_SUBCAT_LIST if 2000 <= i[0] < 3000],
profile.get_user_ratings(request.userid),
], title="Literary Artwork"))
@login_required
@token_checked
def submit_literary_post_(request):
form = request.web_input(submitfile="", coverfile="", thumbfile="", title="",
folderid="", subtype="", rating="",
content="", tags="", embedlink="")
tags = searchtag.parse_tags(form.tags)
if not config_read_bool("allow_submit"):
raise WeasylError("FeatureDisabled")
if not define.is_vouched_for(request.userid):
raise WeasylError("vouchRequired")
rating = ratings.CODE_MAP.get(define.get_int(form.rating))
if not rating:
raise WeasylError("ratingInvalid")
s = orm.Submission()
s.title = form.title
s.rating = rating
s.content = form.content
s.folderid = define.get_int(form.folderid) or None
s.subtype = define.get_int(form.subtype)
s.submitter_ip_address = request.client_addr
s.submitter_user_agent_id = get_user_agent_id(ua_string=request.user_agent)
submitid, thumb = submission.create_literary(
request.userid, s, embedlink=form.embedlink, friends_only='friends' in request.POST, tags=tags,
coverfile=form.coverfile, thumbfile=form.thumbfile, submitfile=form.submitfile,
critique='critique' in request.POST, create_notifications=('nonotification' not in form))
if thumb:
raise HTTPSeeOther(location="/manage/thumbnail?submitid=%i" % (submitid,))
else:
raise HTTPSeeOther(location="/submission/%i/%s" % (submitid, slug_for(form.title)))
@login_required
def submit_multimedia_get_(request):
if not define.is_vouched_for(request.userid):
raise WeasylError("vouchRequired")
return Response(define.webpage(request.userid, "submit/multimedia.html", [
# Folders
folder.select_flat(request.userid),
# Subtypes
[i for i in macro.MACRO_SUBCAT_LIST if 3000 <= i[0] < 4000],
profile.get_user_ratings(request.userid),
], title="Multimedia Artwork"))
@login_required
@token_checked
def submit_multimedia_post_(request):
form = request.web_input(submitfile="", coverfile="", thumbfile="", embedlink="",
title="", folderid="", subtype="", rating="",
content="", tags="")
tags = searchtag.parse_tags(form.tags)
if not config_read_bool("allow_submit"):
raise WeasylError("FeatureDisabled")
if not define.is_vouched_for(request.userid):
raise WeasylError("vouchRequired")
rating = ratings.CODE_MAP.get(define.get_int(form.rating))
if not rating:
raise WeasylError("ratingInvalid")
s = orm.Submission()
s.title = form.title
s.rating = rating
s.content = form.content
s.folderid = define.get_int(form.folderid) or None
s.subtype = define.get_int(form.subtype)
s.submitter_ip_address = request.client_addr
s.submitter_user_agent_id = get_user_agent_id(ua_string=request.user_agent)
autothumb = ('noautothumb' not in form)
submitid, thumb = submission.create_multimedia(
request.userid, s, embedlink=form.embedlink, friends_only='friends' in request.POST, tags=tags,
coverfile=form.coverfile, thumbfile=form.thumbfile, submitfile=form.submitfile,
critique='critique' in request.POST, create_notifications=('nonotification' not in form),
auto_thumb=autothumb)
if thumb and not autothumb:
raise HTTPSeeOther(location="/manage/thumbnail?submitid=%i" % (submitid,))
else:
raise HTTPSeeOther(location="/submission/%i/%s" % (submitid, slug_for(form.title)))
@login_required
def submit_character_get_(request):
if not define.is_vouched_for(request.userid):
raise WeasylError("vouchRequired")
return Response(define.webpage(request.userid, "submit/character.html", [
profile.get_user_ratings(request.userid),
], title="Character Profile"))
@login_required
@token_checked
def submit_character_post_(request):
form = request.web_input(submitfile="", thumbfile="", title="", age="", gender="",
height="", weight="", species="", rating="",
content="", tags="")
tags = searchtag.parse_tags(form.tags)
if not config_read_bool("allow_submit"):
raise WeasylError("FeatureDisabled")
if not define.is_vouched_for(request.userid):
raise WeasylError("vouchRequired")
rating = ratings.CODE_MAP.get(define.get_int(form.rating))
if not rating:
raise WeasylError("ratingInvalid")
c = orm.Character()
c.age = form.age
c.gender = form.gender
c.height = form.height
c.weight = form.weight
c.species = form.species
c.char_name = form.title
c.content = form.content
c.rating = rating
charid = character.create(request.userid, c, 'friends' in request.POST, tags,
form.thumbfile, form.submitfile)
raise HTTPSeeOther(location="/manage/thumbnail?charid=%i" % (charid,))
@login_required
def submit_journal_get_(request):
if not define.is_vouched_for(request.userid):
raise WeasylError("vouchRequired")
return Response(define.webpage(request.userid, "submit/journal.html",
[profile.get_user_ratings(request.userid)], title="Journal Entry"))
@login_required
@token_checked
def submit_journal_post_(request):
form = request.web_input(title="", rating="", members="", content="", tags="")
tags = searchtag.parse_tags(form.tags)
if not config_read_bool("allow_submit"):
raise WeasylError("FeatureDisabled")
if not define.is_vouched_for(request.userid):
raise WeasylError("vouchRequired")
rating = ratings.CODE_MAP.get(define.get_int(form.rating))
if not rating:
raise WeasylError("ratingInvalid")
j = orm.Journal()
j.title = form.title
j.rating = rating
j.content = form.content
j.submitter_ip_address = request.client_addr
j.submitter_user_agent_id = get_user_agent_id(ua_string=request.user_agent)
journalid = journal.create(request.userid, j, friends_only='friends' in request.POST,
tags=tags)
raise HTTPSeeOther(location="/journal/%i/%s" % (journalid, slug_for(form.title)))
@login_required
@token_checked
@supports_json
def submit_shout_(request):
form = request.web_input(userid="", parentid="", content="", staffnotes="", format="")
if form.staffnotes and request.userid not in staff.MODS:
raise WeasylError("InsufficientPermissions")
if not define.is_vouched_for(request.userid):
raise WeasylError("vouchRequired")
commentid = shout.insert(
request.userid,
target_user=define.get_int(form.userid or form.staffnotes),
parentid=define.get_int(form.parentid),
content=form.content,
staffnotes=bool(form.staffnotes),
)
if form.format == "json":
return {
"id": commentid,
"html": markdown(form.content),
}
if form.staffnotes:
raise HTTPSeeOther(location='/staffnotes?userid=%i#cid%i' % (define.get_int(form.staffnotes), commentid))
else:
raise HTTPSeeOther(location="/shouts?userid=%i#cid%i" % (define.get_int(form.userid), commentid))
@login_required
@token_checked
@supports_json
def submit_comment_(request):
if not define.is_vouched_for(request.userid):
raise WeasylError("vouchRequired")
form = request.web_input(submitid="", charid="", journalid="", updateid="", parentid="", content="", format="")
updateid = define.get_int(form.updateid)
commentid = comment.insert(request.userid, charid=define.get_int(form.charid),
parentid=define.get_int(form.parentid),
submitid=define.get_int(form.submitid),
journalid=define.get_int(form.journalid),
updateid=updateid,
content=form.content)
if form.format == "json":
return {
"id": commentid,
"html": markdown(form.content),
}
if define.get_int(form.submitid):
raise HTTPSeeOther(location="/submission/%i#cid%i" % (define.get_int(form.submitid), commentid))
elif define.get_int(form.charid):
raise HTTPSeeOther(location="/character/%i#cid%i" % (define.get_int(form.charid), commentid))
elif define.get_int(form.journalid):
raise HTTPSeeOther(location="/journal/%i#cid%i" % (define.get_int(form.journalid), commentid))
elif updateid:
raise HTTPSeeOther(location="/site-updates/%i#cid%i" % (updateid, commentid))
else:
raise WeasylError("Unexpected")
@login_required
@token_checked
def submit_report_(request):
form = request.web_input(submitid="", charid="", journalid="", reportid="", violation="", content="")
report.create(request.userid, form)
if form.reportid:
raise HTTPSeeOther(location="/modcontrol/report?reportid=%s" % (form.reportid,))
elif define.get_int(form.submitid):
raise HTTPSeeOther(location="/submission/%i" % (define.get_int(form.submitid),))
elif define.get_int(form.charid):
raise HTTPSeeOther(location="/character/%i" % (define.get_int(form.charid),))
else:
raise HTTPSeeOther(location="/journal/%i" % (define.get_int(form.journalid),))
@login_required
@token_checked
def submit_tags_(request):
if not define.is_vouched_for(request.userid):
raise WeasylError("vouchRequired")
form = request.web_input(submitid="", charid="", journalid="", preferred_tags_userid="", optout_tags_userid="", tags="")
tags = searchtag.parse_tags(form.tags)
submitid = define.get_int(form.submitid)
charid = define.get_int(form.charid)
journalid = define.get_int(form.journalid)
preferred_tags_userid = define.get_int(form.preferred_tags_userid)
optout_tags_userid = define.get_int(form.optout_tags_userid)
result = searchtag.associate(request.userid, tags, submitid, charid, journalid, preferred_tags_userid, optout_tags_userid)
if result:
failed_tag_message = ""
if result["add_failure_restricted_tags"] is not None:
failed_tag_message += "The following tags have been restricted from being added to this item by the content owner, or Weasyl staff: **" + result["add_failure_restricted_tags"] + "**. \n"
if result["remove_failure_owner_set_tags"] is not None:
failed_tag_message += "The following tags were not removed from this item as the tag was added by the owner: **" + result["remove_failure_owner_set_tags"] + "**.\n"
failed_tag_message += "Any other changes to this item's tags were completed."
if submitid:
location = "/submission/%i" % (submitid,)
if not result:
raise HTTPSeeOther(location=location)
else:
return Response(define.errorpage(request.userid, failed_tag_message,
[["Return to Content", location]]))
elif charid:
location = "/character/%i" % (charid,)
if not result:
raise HTTPSeeOther(location=location)
else:
return Response(define.errorpage(request.userid, failed_tag_message,
[["Return to Content", location]]))
elif journalid:
location = "/journal/%i" % (journalid,)
if not result:
raise HTTPSeeOther(location=location)
else:
return Response(define.errorpage(request.userid, failed_tag_message,
[["Return to Content", location]]))
else:
raise HTTPSeeOther(location="/control/editcommissionsettings")
@login_required
def reupload_submission_get_(request):
form = request.web_input(submitid="")
form.submitid = define.get_int(form.submitid)
if request.userid != define.get_ownerid(submitid=form.submitid):
raise WeasylError('InsufficientPermissions')
return Response(define.webpage(request.userid, "submit/reupload_submission.html", [
"submission",
# SubmitID
form.submitid,
], title="Reupload Submission"))
@login_required
@token_checked
def reupload_submission_post_(request):
form = request.web_input(targetid="", submitfile="")
form.targetid = define.get_int(form.targetid)
if request.userid != define.get_ownerid(submitid=form.targetid):
raise WeasylError('InsufficientPermissions')
submission.reupload(request.userid, form.targetid, form.submitfile)
raise HTTPSeeOther(location="/submission/%i" % (form.targetid,))
@login_required
def reupload_character_get_(request):
form = request.web_input(charid="")
form.charid = define.get_int(form.charid)
if request.userid != define.get_ownerid(charid=form.charid):
raise WeasylError('InsufficientPermissions')
return Response(define.webpage(request.userid, "submit/reupload_submission.html", [
"character",
# charid
form.charid,
], title="Reupload Character Image"))
@login_required
@token_checked
def reupload_character_post_(request):
form = request.web_input(targetid="", submitfile="")
form.targetid = define.get_int(form.targetid)
if request.userid != define.get_ownerid(charid=form.targetid):
raise WeasylError('InsufficientPermissions')
character.reupload(request.userid, form.targetid, form.submitfile)
raise HTTPSeeOther(location="/character/%i" % (form.targetid,))
@login_required
def reupload_cover_get_(request):
form = request.web_input(submitid="")
form.submitid = define.get_int(form.submitid)
if request.userid != define.get_ownerid(submitid=form.submitid):
raise WeasylError('InsufficientPermissions')
return Response(define.webpage(request.userid, "submit/reupload_cover.html", [form.submitid], title="Reupload Cover Artwork"))
@login_required
@token_checked
def reupload_cover_post_(request):
form = request.web_input(submitid="", coverfile="")
form.submitid = define.get_int(form.submitid)
submission.reupload_cover(request.userid, form.submitid, form.coverfile)
raise HTTPSeeOther(location="/submission/%i" % (form.submitid,))
# Content editing functions
@login_required
def edit_submission_get_(request):
form = request.web_input(submitid="", anyway="")
form.submitid = define.get_int(form.submitid)
detail = submission.select_view(request.userid, form.submitid, ratings.EXPLICIT.code, False, anyway=form.anyway)
if request.userid != detail['userid'] and request.userid not in staff.MODS:
raise WeasylError('InsufficientPermissions')
submission_category = detail['subtype'] // 1000 * 1000
return Response(define.webpage(request.userid, "edit/submission.html", [
# Submission detail
detail,
# Folders
folder.select_flat(detail['userid']),
# Subtypes
[i for i in macro.MACRO_SUBCAT_LIST
if submission_category <= i[0] < submission_category + 1000],
profile.get_user_ratings(detail['userid']),
], title="Edit Submission"))
@login_required
@token_checked
def edit_submission_post_(request):
form = request.web_input(submitid="", title="", folderid="", subtype="", rating="",
content="", embedlink="")
rating = ratings.CODE_MAP.get(define.get_int(form.rating))
if not rating:
raise WeasylError("ratingInvalid")
s = orm.Submission()
s.submitid = define.get_int(form.submitid)
s.title = form.title
s.rating = rating
s.content = form.content
s.folderid = define.get_int(form.folderid) or None
s.subtype = define.get_int(form.subtype)
submission.edit(request.userid, s, embedlink=form.embedlink,
friends_only='friends' in request.POST, critique='critique' in request.POST)
raise HTTPSeeOther(location="/submission/%i/%s%s" % (
define.get_int(form.submitid),
slug_for(form.title),
"?anyway=true" if request.userid in staff.MODS else ''
))
@login_required
def edit_character_get_(request):
form = request.web_input(charid="", anyway="")
form.charid = define.get_int(form.charid)
detail = character.select_view(request.userid, form.charid, ratings.EXPLICIT.code, False, anyway=form.anyway)
if request.userid != detail['userid'] and request.userid not in staff.MODS:
raise WeasylError('InsufficientPermissions')
return Response(define.webpage(request.userid, "edit/character.html", [
# Submission detail
detail,
profile.get_user_ratings(detail['userid']),
], title="Edit Character"))
@login_required
@token_checked
def edit_character_post_(request):
form = request.web_input(charid="", title="", age="", gender="", height="",
weight="", species="", rating="", content="")
rating = ratings.CODE_MAP.get(define.get_int(form.rating))
if not rating:
raise WeasylError("ratingInvalid")
c = orm.Character()
c.charid = define.get_int(form.charid)
c.age = form.age
c.gender = form.gender
c.height = form.height
c.weight = form.weight
c.species = form.species
c.char_name = form.title
c.content = form.content
c.rating = rating
character.edit(request.userid, c, friends_only='friends' in request.POST)
raise HTTPSeeOther(location="/character/%i/%s%s" % (
define.get_int(form.charid),
slug_for(form.title),
("?anyway=true" if request.userid in staff.MODS else '')
))
@login_required
def edit_journal_get_(request):
form = request.web_input(journalid="", anyway="")
form.journalid = define.get_int(form.journalid)
detail = journal.select_view(request.userid, ratings.EXPLICIT.code, form.journalid, False, anyway=form.anyway)
if request.userid != detail['userid'] and request.userid not in staff.MODS:
raise WeasylError('InsufficientPermissions')
return Response(define.webpage(request.userid, "edit/journal.html", [
# Journal detail
detail,
profile.get_user_ratings(detail['userid']),
], title="Edit Journal"))
@login_required
@token_checked
def edit_journal_post_(request):
form = request.web_input(journalid="", title="", rating="", content="")
rating = ratings.CODE_MAP.get(define.get_int(form.rating))
if not rating:
raise WeasylError("ratingInvalid")
j = orm.Journal()
j.journalid = define.get_int(form.journalid)
j.title = form.title
j.rating = rating
j.content = form.content
journal.edit(request.userid, j, friends_only='friends' in request.POST)
raise HTTPSeeOther(location="/journal/%i/%s%s" % (
define.get_int(form.journalid),
slug_for(form.title),
("?anyway=true" if request.userid in staff.MODS else '')
))
# Content removal functions
@login_required
@token_checked
def remove_submission_(request):
form = request.web_input(submitid="")
ownerid = submission.remove(request.userid, define.get_int(form.submitid))
if request.userid == ownerid:
raise HTTPSeeOther(location="/control") # todo
else:
raise HTTPSeeOther(location="/submissions?userid=%i" % (ownerid,))
@login_required
@token_checked
def remove_character_(request):
form = request.web_input(charid="")
ownerid = character.remove(request.userid, define.get_int(form.charid))
if request.userid == ownerid:
raise HTTPSeeOther(location="/control") # todo
else:
raise HTTPSeeOther(location="/characters?userid=%i" % (ownerid,))
@login_required
@token_checked
def remove_journal_(request):
form = request.web_input(journalid="")
ownerid = journal.remove(request.userid, define.get_int(form.journalid))
if request.userid == ownerid:
raise HTTPSeeOther(location="/control") # todo
else:
raise HTTPSeeOther(location="/journals?userid=%i" % (ownerid,))
@login_required
@token_checked
@supports_json
def remove_comment_(request):
form = request.web_input(commentid="", feature="", format="")
commentid = define.get_int(form.commentid)
if form.feature == "userid":
targetid = shout.remove(request.userid, commentid=commentid)
else:
targetid = comment.remove(request.userid, commentid=commentid, feature=form.feature)
if form.format == "json":
return {"success": True}
if form.feature == "userid":
raise HTTPSeeOther(location="/shouts?userid=%i" % (targetid,))
elif form.feature == "submit":
raise HTTPSeeOther(location="/submission/%i" % (targetid,))
elif form.feature == "char":
raise HTTPSeeOther(location="/character/%i" % (targetid,))
elif form.feature == "journal":
raise HTTPSeeOther(location="/journal/%i" % (targetid,))
| |
from __future__ import unicode_literals
import base64
import json
import datetime
import mock
from django.test import TestCase, RequestFactory
from django.core.urlresolvers import reverse
from django.utils import timezone
from ..compat import urlparse, parse_qs, urlencode, get_user_model
from ..models import get_application_model, Grant, AccessToken
from ..settings import oauth2_settings
from ..views import ProtectedResourceView
from .test_utils import TestCaseUtils
Application = get_application_model()
UserModel = get_user_model()
# mocking a protected resource view
class ResourceView(ProtectedResourceView):
def get(self, request, *args, **kwargs):
return "This is a protected resource"
class BaseTest(TestCaseUtils, TestCase):
def setUp(self):
self.factory = RequestFactory()
self.test_user = UserModel.objects.create_user("test_user", "test@user.com", "123456")
self.dev_user = UserModel.objects.create_user("dev_user", "dev@user.com", "123456")
oauth2_settings.ALLOWED_REDIRECT_URI_SCHEMES = ['http', 'custom-scheme']
self.application = Application(
name="Test Application",
redirect_uris="http://localhost http://example.com http://example.it custom-scheme://example.com",
user=self.dev_user,
client_type=Application.CLIENT_CONFIDENTIAL,
authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
)
self.application.save()
oauth2_settings._SCOPES = ['read', 'write']
def tearDown(self):
self.application.delete()
self.test_user.delete()
self.dev_user.delete()
class TestAuthorizationCodeView(BaseTest):
def test_skip_authorization_completely(self):
"""
If application.skip_authorization = True, should skip the authorization page.
"""
self.client.login(username="test_user", password="123456")
self.application.skip_authorization = True
self.application.save()
query_string = urlencode({
'client_id': self.application.client_id,
'response_type': 'code',
'state': 'random_state_string',
'scope': 'read write',
'redirect_uri': 'http://example.it',
})
url = "{url}?{qs}".format(url=reverse('oauth2_provider:authorize'), qs=query_string)
response = self.client.get(url)
self.assertEqual(response.status_code, 302)
def test_pre_auth_invalid_client(self):
"""
Test error for an invalid client_id with response_type: code
"""
self.client.login(username="test_user", password="123456")
query_string = urlencode({
'client_id': 'fakeclientid',
'response_type': 'code',
})
url = "{url}?{qs}".format(url=reverse('oauth2_provider:authorize'), qs=query_string)
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
def test_pre_auth_valid_client(self):
"""
Test response for a valid client_id with response_type: code
"""
self.client.login(username="test_user", password="123456")
query_string = urlencode({
'client_id': self.application.client_id,
'response_type': 'code',
'state': 'random_state_string',
'scope': 'read write',
'redirect_uri': 'http://example.it',
})
url = "{url}?{qs}".format(url=reverse('oauth2_provider:authorize'), qs=query_string)
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
# check form is in context and form params are valid
self.assertIn("form", response.context)
form = response.context["form"]
self.assertEqual(form['redirect_uri'].value(), "http://example.it")
self.assertEqual(form['state'].value(), "random_state_string")
self.assertEqual(form['scope'].value(), "read write")
self.assertEqual(form['client_id'].value(), self.application.client_id)
def test_pre_auth_valid_client_custom_redirect_uri_scheme(self):
"""
Test response for a valid client_id with response_type: code
using a non-standard, but allowed, redirect_uri scheme.
"""
self.client.login(username="test_user", password="123456")
query_string = urlencode({
'client_id': self.application.client_id,
'response_type': 'code',
'state': 'random_state_string',
'scope': 'read write',
'redirect_uri': 'custom-scheme://example.com',
})
url = "{url}?{qs}".format(url=reverse('oauth2_provider:authorize'), qs=query_string)
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
# check form is in context and form params are valid
self.assertIn("form", response.context)
form = response.context["form"]
self.assertEqual(form['redirect_uri'].value(), "custom-scheme://example.com")
self.assertEqual(form['state'].value(), "random_state_string")
self.assertEqual(form['scope'].value(), "read write")
self.assertEqual(form['client_id'].value(), self.application.client_id)
def test_pre_auth_approval_prompt(self):
"""
TODO
"""
tok = AccessToken.objects.create(user=self.test_user, token='1234567890',
application=self.application,
expires=timezone.now() + datetime.timedelta(days=1),
scope='read write')
self.client.login(username="test_user", password="123456")
query_string = urlencode({
'client_id': self.application.client_id,
'response_type': 'code',
'state': 'random_state_string',
'scope': 'read write',
'redirect_uri': 'http://example.it',
'approval_prompt': 'auto',
})
url = "{url}?{qs}".format(url=reverse('oauth2_provider:authorize'), qs=query_string)
response = self.client.get(url)
self.assertEqual(response.status_code, 302)
# user already authorized the application, but with different scopes: prompt them.
tok.scope = 'read'
tok.save()
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_pre_auth_approval_prompt_default(self):
"""
TODO
"""
self.assertEqual(oauth2_settings.REQUEST_APPROVAL_PROMPT, 'force')
AccessToken.objects.create(user=self.test_user, token='1234567890',
application=self.application,
expires=timezone.now() + datetime.timedelta(days=1),
scope='read write')
self.client.login(username="test_user", password="123456")
query_string = urlencode({
'client_id': self.application.client_id,
'response_type': 'code',
'state': 'random_state_string',
'scope': 'read write',
'redirect_uri': 'http://example.it',
})
url = "{url}?{qs}".format(url=reverse('oauth2_provider:authorize'), qs=query_string)
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_pre_auth_approval_prompt_default_override(self):
"""
TODO
"""
oauth2_settings.REQUEST_APPROVAL_PROMPT = 'auto'
AccessToken.objects.create(user=self.test_user, token='1234567890',
application=self.application,
expires=timezone.now() + datetime.timedelta(days=1),
scope='read write')
self.client.login(username="test_user", password="123456")
query_string = urlencode({
'client_id': self.application.client_id,
'response_type': 'code',
'state': 'random_state_string',
'scope': 'read write',
'redirect_uri': 'http://example.it',
})
url = "{url}?{qs}".format(url=reverse('oauth2_provider:authorize'), qs=query_string)
response = self.client.get(url)
self.assertEqual(response.status_code, 302)
def test_pre_auth_default_redirect(self):
"""
Test for default redirect uri if omitted from query string with response_type: code
"""
self.client.login(username="test_user", password="123456")
query_string = urlencode({
'client_id': self.application.client_id,
'response_type': 'code',
})
url = "{url}?{qs}".format(url=reverse('oauth2_provider:authorize'), qs=query_string)
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
form = response.context["form"]
self.assertEqual(form['redirect_uri'].value(), "http://localhost")
def test_pre_auth_forbibben_redirect(self):
"""
Test error when passing a forbidden redirect_uri in query string with response_type: code
"""
self.client.login(username="test_user", password="123456")
query_string = urlencode({
'client_id': self.application.client_id,
'response_type': 'code',
'redirect_uri': 'http://forbidden.it',
})
url = "{url}?{qs}".format(url=reverse('oauth2_provider:authorize'), qs=query_string)
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
def test_pre_auth_wrong_response_type(self):
"""
Test error when passing a wrong response_type in query string
"""
self.client.login(username="test_user", password="123456")
query_string = urlencode({
'client_id': self.application.client_id,
'response_type': 'WRONG',
})
url = "{url}?{qs}".format(url=reverse('oauth2_provider:authorize'), qs=query_string)
response = self.client.get(url)
self.assertEqual(response.status_code, 302)
self.assertIn("error=unauthorized_client", response['Location'])
def test_code_post_auth_allow(self):
"""
Test authorization code is given for an allowed request with response_type: code
"""
self.client.login(username="test_user", password="123456")
form_data = {
'client_id': self.application.client_id,
'state': 'random_state_string',
'scope': 'read write',
'redirect_uri': 'http://example.it',
'response_type': 'code',
'allow': True,
}
response = self.client.post(reverse('oauth2_provider:authorize'), data=form_data)
self.assertEqual(response.status_code, 302)
self.assertIn('http://example.it?', response['Location'])
self.assertIn('state=random_state_string', response['Location'])
self.assertIn('code=', response['Location'])
def test_code_post_auth_deny(self):
"""
Test error when resource owner deny access
"""
self.client.login(username="test_user", password="123456")
form_data = {
'client_id': self.application.client_id,
'state': 'random_state_string',
'scope': 'read write',
'redirect_uri': 'http://example.it',
'response_type': 'code',
'allow': False,
}
response = self.client.post(reverse('oauth2_provider:authorize'), data=form_data)
self.assertEqual(response.status_code, 302)
self.assertIn("error=access_denied", response['Location'])
def test_code_post_auth_bad_responsetype(self):
"""
Test authorization code is given for an allowed request with a response_type not supported
"""
self.client.login(username="test_user", password="123456")
form_data = {
'client_id': self.application.client_id,
'state': 'random_state_string',
'scope': 'read write',
'redirect_uri': 'http://example.it',
'response_type': 'UNKNOWN',
'allow': True,
}
response = self.client.post(reverse('oauth2_provider:authorize'), data=form_data)
self.assertEqual(response.status_code, 302)
self.assertIn('http://example.it?error', response['Location'])
def test_code_post_auth_forbidden_redirect_uri(self):
"""
Test authorization code is given for an allowed request with a forbidden redirect_uri
"""
self.client.login(username="test_user", password="123456")
form_data = {
'client_id': self.application.client_id,
'state': 'random_state_string',
'scope': 'read write',
'redirect_uri': 'http://forbidden.it',
'response_type': 'code',
'allow': True,
}
response = self.client.post(reverse('oauth2_provider:authorize'), data=form_data)
self.assertEqual(response.status_code, 400)
def test_code_post_auth_malicious_redirect_uri(self):
"""
Test validation of a malicious redirect_uri
"""
self.client.login(username="test_user", password="123456")
form_data = {
'client_id': self.application.client_id,
'state': 'random_state_string',
'scope': 'read write',
'redirect_uri': '/../',
'response_type': 'code',
'allow': True,
}
response = self.client.post(reverse('oauth2_provider:authorize'), data=form_data)
self.assertEqual(response.status_code, 400)
def test_code_post_auth_allow_custom_redirect_uri_scheme(self):
"""
Test authorization code is given for an allowed request with response_type: code
using a non-standard, but allowed, redirect_uri scheme.
"""
self.client.login(username="test_user", password="123456")
form_data = {
'client_id': self.application.client_id,
'state': 'random_state_string',
'scope': 'read write',
'redirect_uri': 'custom-scheme://example.com',
'response_type': 'code',
'allow': True,
}
response = self.client.post(reverse('oauth2_provider:authorize'), data=form_data)
self.assertEqual(response.status_code, 302)
self.assertIn('custom-scheme://example.com?', response['Location'])
self.assertIn('state=random_state_string', response['Location'])
self.assertIn('code=', response['Location'])
def test_code_post_auth_deny_custom_redirect_uri_scheme(self):
"""
Test error when resource owner deny access
using a non-standard, but allowed, redirect_uri scheme.
"""
self.client.login(username="test_user", password="123456")
form_data = {
'client_id': self.application.client_id,
'state': 'random_state_string',
'scope': 'read write',
'redirect_uri': 'custom-scheme://example.com',
'response_type': 'code',
'allow': False,
}
response = self.client.post(reverse('oauth2_provider:authorize'), data=form_data)
self.assertEqual(response.status_code, 302)
self.assertIn('custom-scheme://example.com?', response['Location'])
self.assertIn("error=access_denied", response['Location'])
def test_code_post_auth_redirection_uri_with_querystring(self):
"""
Tests that a redirection uri with query string is allowed
and query string is retained on redirection.
See http://tools.ietf.org/html/rfc6749#section-3.1.2
"""
self.client.login(username="test_user", password="123456")
form_data = {
'client_id': self.application.client_id,
'state': 'random_state_string',
'scope': 'read write',
'redirect_uri': 'http://example.com?foo=bar',
'response_type': 'code',
'allow': True,
}
response = self.client.post(reverse('oauth2_provider:authorize'), data=form_data)
self.assertEqual(response.status_code, 302)
self.assertIn("http://example.com?foo=bar", response['Location'])
self.assertIn("code=", response['Location'])
def test_code_post_auth_fails_when_redirect_uri_path_is_invalid(self):
"""
Tests that a redirection uri is matched using scheme + netloc + path
"""
self.client.login(username="test_user", password="123456")
form_data = {
'client_id': self.application.client_id,
'state': 'random_state_string',
'scope': 'read write',
'redirect_uri': 'http://example.com/a?foo=bar',
'response_type': 'code',
'allow': True,
}
response = self.client.post(reverse('oauth2_provider:authorize'), data=form_data)
self.assertEqual(response.status_code, 400)
class TestAuthorizationCodeTokenView(BaseTest):
def get_auth(self):
"""
Helper method to retrieve a valid authorization code
"""
authcode_data = {
'client_id': self.application.client_id,
'state': 'random_state_string',
'scope': 'read write',
'redirect_uri': 'http://example.it',
'response_type': 'code',
'allow': True,
}
response = self.client.post(reverse('oauth2_provider:authorize'), data=authcode_data)
query_dict = parse_qs(urlparse(response['Location']).query)
return query_dict['code'].pop()
def test_basic_auth(self):
"""
Request an access token using basic authentication for client authentication
"""
self.client.login(username="test_user", password="123456")
authorization_code = self.get_auth()
token_request_data = {
'grant_type': 'authorization_code',
'code': authorization_code,
'redirect_uri': 'http://example.it'
}
auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret)
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
self.assertEqual(response.status_code, 200)
content = json.loads(response.content.decode("utf-8"))
self.assertEqual(content['token_type'], "Bearer")
self.assertEqual(content['scope'], "read write")
self.assertEqual(content['expires_in'], oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS)
def test_refresh(self):
"""
Request an access token using a refresh token
"""
self.client.login(username="test_user", password="123456")
authorization_code = self.get_auth()
token_request_data = {
'grant_type': 'authorization_code',
'code': authorization_code,
'redirect_uri': 'http://example.it'
}
auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret)
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
content = json.loads(response.content.decode("utf-8"))
self.assertTrue('refresh_token' in content)
# make a second token request to be sure the previous refresh token remains valid, see #65
authorization_code = self.get_auth()
token_request_data = {
'grant_type': 'authorization_code',
'code': authorization_code,
'redirect_uri': 'http://example.it'
}
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
token_request_data = {
'grant_type': 'refresh_token',
'refresh_token': content['refresh_token'],
'scope': content['scope'],
}
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
self.assertEqual(response.status_code, 200)
content = json.loads(response.content.decode("utf-8"))
self.assertTrue('access_token' in content)
# check refresh token cannot be used twice
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
self.assertEqual(response.status_code, 401)
content = json.loads(response.content.decode("utf-8"))
self.assertTrue('invalid_grant' in content.values())
def test_refresh_no_scopes(self):
"""
Request an access token using a refresh token without passing any scope
"""
self.client.login(username="test_user", password="123456")
authorization_code = self.get_auth()
token_request_data = {
'grant_type': 'authorization_code',
'code': authorization_code,
'redirect_uri': 'http://example.it'
}
auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret)
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
content = json.loads(response.content.decode("utf-8"))
self.assertTrue('refresh_token' in content)
token_request_data = {
'grant_type': 'refresh_token',
'refresh_token': content['refresh_token'],
}
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
self.assertEqual(response.status_code, 200)
content = json.loads(response.content.decode("utf-8"))
self.assertTrue('access_token' in content)
def test_refresh_bad_scopes(self):
"""
Request an access token using a refresh token and wrong scopes
"""
self.client.login(username="test_user", password="123456")
authorization_code = self.get_auth()
token_request_data = {
'grant_type': 'authorization_code',
'code': authorization_code,
'redirect_uri': 'http://example.it'
}
auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret)
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
content = json.loads(response.content.decode("utf-8"))
self.assertTrue('refresh_token' in content)
token_request_data = {
'grant_type': 'refresh_token',
'refresh_token': content['refresh_token'],
'scope': 'read write nuke',
}
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
self.assertEqual(response.status_code, 401)
def test_refresh_fail_repeating_requests(self):
"""
Try refreshing an access token with the same refresh token more than once
"""
self.client.login(username="test_user", password="123456")
authorization_code = self.get_auth()
token_request_data = {
'grant_type': 'authorization_code',
'code': authorization_code,
'redirect_uri': 'http://example.it'
}
auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret)
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
content = json.loads(response.content.decode("utf-8"))
self.assertTrue('refresh_token' in content)
token_request_data = {
'grant_type': 'refresh_token',
'refresh_token': content['refresh_token'],
'scope': content['scope'],
}
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
self.assertEqual(response.status_code, 200)
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
self.assertEqual(response.status_code, 401)
def test_refresh_repeating_requests_non_rotating_tokens(self):
"""
Try refreshing an access token with the same refresh token more than once when not rotating tokens.
"""
self.client.login(username="test_user", password="123456")
authorization_code = self.get_auth()
token_request_data = {
'grant_type': 'authorization_code',
'code': authorization_code,
'redirect_uri': 'http://example.it'
}
auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret)
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
content = json.loads(response.content.decode("utf-8"))
self.assertTrue('refresh_token' in content)
token_request_data = {
'grant_type': 'refresh_token',
'refresh_token': content['refresh_token'],
'scope': content['scope'],
}
with mock.patch('oauthlib.oauth2.rfc6749.request_validator.RequestValidator.rotate_refresh_token',
return_value=False):
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
self.assertEqual(response.status_code, 200)
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
self.assertEqual(response.status_code, 200)
def test_basic_auth_bad_authcode(self):
"""
Request an access token using a bad authorization code
"""
self.client.login(username="test_user", password="123456")
token_request_data = {
'grant_type': 'authorization_code',
'code': 'BLAH',
'redirect_uri': 'http://example.it'
}
auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret)
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
self.assertEqual(response.status_code, 401)
def test_basic_auth_bad_granttype(self):
"""
Request an access token using a bad grant_type string
"""
self.client.login(username="test_user", password="123456")
token_request_data = {
'grant_type': 'UNKNOWN',
'code': 'BLAH',
'redirect_uri': 'http://example.it'
}
auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret)
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
self.assertEqual(response.status_code, 400)
def test_basic_auth_grant_expired(self):
"""
Request an access token using an expired grant token
"""
self.client.login(username="test_user", password="123456")
g = Grant(application=self.application, user=self.test_user, code='BLAH', expires=timezone.now(),
redirect_uri='', scope='')
g.save()
token_request_data = {
'grant_type': 'authorization_code',
'code': 'BLAH',
'redirect_uri': 'http://example.it'
}
auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret)
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
self.assertEqual(response.status_code, 401)
def test_basic_auth_bad_secret(self):
"""
Request an access token using basic authentication for client authentication
"""
self.client.login(username="test_user", password="123456")
authorization_code = self.get_auth()
token_request_data = {
'grant_type': 'authorization_code',
'code': authorization_code,
'redirect_uri': 'http://example.it'
}
auth_headers = self.get_basic_auth_header(self.application.client_id, 'BOOM!')
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
self.assertEqual(response.status_code, 401)
def test_basic_auth_wrong_auth_type(self):
"""
Request an access token using basic authentication for client authentication
"""
self.client.login(username="test_user", password="123456")
authorization_code = self.get_auth()
token_request_data = {
'grant_type': 'authorization_code',
'code': authorization_code,
'redirect_uri': 'http://example.it'
}
user_pass = '{0}:{1}'.format(self.application.client_id, self.application.client_secret)
auth_string = base64.b64encode(user_pass.encode('utf-8'))
auth_headers = {
'HTTP_AUTHORIZATION': 'Wrong ' + auth_string.decode("utf-8"),
}
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
self.assertEqual(response.status_code, 401)
def test_request_body_params(self):
"""
Request an access token using client_type: public
"""
self.client.login(username="test_user", password="123456")
authorization_code = self.get_auth()
token_request_data = {
'grant_type': 'authorization_code',
'code': authorization_code,
'redirect_uri': 'http://example.it',
'client_id': self.application.client_id,
'client_secret': self.application.client_secret,
}
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data)
self.assertEqual(response.status_code, 200)
content = json.loads(response.content.decode("utf-8"))
self.assertEqual(content['token_type'], "Bearer")
self.assertEqual(content['scope'], "read write")
self.assertEqual(content['expires_in'], oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS)
def test_public(self):
"""
Request an access token using client_type: public
"""
self.client.login(username="test_user", password="123456")
self.application.client_type = Application.CLIENT_PUBLIC
self.application.save()
authorization_code = self.get_auth()
token_request_data = {
'grant_type': 'authorization_code',
'code': authorization_code,
'redirect_uri': 'http://example.it',
'client_id': self.application.client_id
}
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data)
self.assertEqual(response.status_code, 200)
content = json.loads(response.content.decode("utf-8"))
self.assertEqual(content['token_type'], "Bearer")
self.assertEqual(content['scope'], "read write")
self.assertEqual(content['expires_in'], oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS)
def test_malicious_redirect_uri(self):
"""
Request an access token using client_type: public and ensure redirect_uri is
properly validated.
"""
self.client.login(username="test_user", password="123456")
self.application.client_type = Application.CLIENT_PUBLIC
self.application.save()
authorization_code = self.get_auth()
token_request_data = {
'grant_type': 'authorization_code',
'code': authorization_code,
'redirect_uri': '/../',
'client_id': self.application.client_id
}
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data)
self.assertEqual(response.status_code, 401)
def test_code_exchange_succeed_when_redirect_uri_match(self):
"""
Tests code exchange succeed when redirect uri matches the one used for code request
"""
self.client.login(username="test_user", password="123456")
# retrieve a valid authorization code
authcode_data = {
'client_id': self.application.client_id,
'state': 'random_state_string',
'scope': 'read write',
'redirect_uri': 'http://example.it?foo=bar',
'response_type': 'code',
'allow': True,
}
response = self.client.post(reverse('oauth2_provider:authorize'), data=authcode_data)
query_dict = parse_qs(urlparse(response['Location']).query)
authorization_code = query_dict['code'].pop()
# exchange authorization code for a valid access token
token_request_data = {
'grant_type': 'authorization_code',
'code': authorization_code,
'redirect_uri': 'http://example.it?foo=bar'
}
auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret)
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
self.assertEqual(response.status_code, 200)
content = json.loads(response.content.decode("utf-8"))
self.assertEqual(content['token_type'], "Bearer")
self.assertEqual(content['scope'], "read write")
self.assertEqual(content['expires_in'], oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS)
def test_code_exchange_fails_when_redirect_uri_does_not_match(self):
"""
Tests code exchange fails when redirect uri does not match the one used for code request
"""
self.client.login(username="test_user", password="123456")
# retrieve a valid authorization code
authcode_data = {
'client_id': self.application.client_id,
'state': 'random_state_string',
'scope': 'read write',
'redirect_uri': 'http://example.it?foo=bar',
'response_type': 'code',
'allow': True,
}
response = self.client.post(reverse('oauth2_provider:authorize'), data=authcode_data)
query_dict = parse_qs(urlparse(response['Location']).query)
authorization_code = query_dict['code'].pop()
# exchange authorization code for a valid access token
token_request_data = {
'grant_type': 'authorization_code',
'code': authorization_code,
'redirect_uri': 'http://example.it?foo=baraa'
}
auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret)
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
self.assertEqual(response.status_code, 401)
def test_code_exchange_succeed_when_redirect_uri_match_with_multiple_query_params(self):
"""
Tests code exchange succeed when redirect uri matches the one used for code request
"""
self.client.login(username="test_user", password="123456")
self.application.redirect_uris = "http://localhost http://example.com?foo=bar"
self.application.save()
# retrieve a valid authorization code
authcode_data = {
'client_id': self.application.client_id,
'state': 'random_state_string',
'scope': 'read write',
'redirect_uri': 'http://example.com?bar=baz&foo=bar',
'response_type': 'code',
'allow': True,
}
response = self.client.post(reverse('oauth2_provider:authorize'), data=authcode_data)
query_dict = parse_qs(urlparse(response['Location']).query)
authorization_code = query_dict['code'].pop()
# exchange authorization code for a valid access token
token_request_data = {
'grant_type': 'authorization_code',
'code': authorization_code,
'redirect_uri': 'http://example.com?bar=baz&foo=bar'
}
auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret)
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
self.assertEqual(response.status_code, 200)
content = json.loads(response.content.decode("utf-8"))
self.assertEqual(content['token_type'], "Bearer")
self.assertEqual(content['scope'], "read write")
self.assertEqual(content['expires_in'], oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS)
class TestAuthorizationCodeProtectedResource(BaseTest):
def test_resource_access_allowed(self):
self.client.login(username="test_user", password="123456")
# retrieve a valid authorization code
authcode_data = {
'client_id': self.application.client_id,
'state': 'random_state_string',
'scope': 'read write',
'redirect_uri': 'http://example.it',
'response_type': 'code',
'allow': True,
}
response = self.client.post(reverse('oauth2_provider:authorize'), data=authcode_data)
query_dict = parse_qs(urlparse(response['Location']).query)
authorization_code = query_dict['code'].pop()
# exchange authorization code for a valid access token
token_request_data = {
'grant_type': 'authorization_code',
'code': authorization_code,
'redirect_uri': 'http://example.it'
}
auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret)
response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
content = json.loads(response.content.decode("utf-8"))
access_token = content['access_token']
# use token to access the resource
auth_headers = {
'HTTP_AUTHORIZATION': 'Bearer ' + access_token,
}
request = self.factory.get("/fake-resource", **auth_headers)
request.user = self.test_user
view = ResourceView.as_view()
response = view(request)
self.assertEqual(response, "This is a protected resource")
def test_resource_access_deny(self):
auth_headers = {
'HTTP_AUTHORIZATION': 'Bearer ' + "faketoken",
}
request = self.factory.get("/fake-resource", **auth_headers)
request.user = self.test_user
view = ResourceView.as_view()
response = view(request)
self.assertEqual(response.status_code, 403)
| |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
__license__ = 'Public Domain'
import codecs
import io
import os
import random
import sys
from .options import (
parseOpts,
)
from .compat import (
compat_expanduser,
compat_getpass,
compat_shlex_split,
workaround_optparse_bug9161,
)
from .utils import (
DateRange,
decodeOption,
DEFAULT_OUTTMPL,
DownloadError,
match_filter_func,
MaxDownloadsReached,
preferredencoding,
read_batch_urls,
SameFileError,
setproctitle,
std_headers,
write_string,
)
from .update import update_self
from .downloader import (
FileDownloader,
)
from .extractor import gen_extractors, list_extractors
from .YoutubeDL import YoutubeDL
def _real_main(argv=None):
# Compatibility fixes for Windows
if sys.platform == 'win32':
# https://github.com/rg3/youtube-dl/issues/820
codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
workaround_optparse_bug9161()
setproctitle('youtube-dl')
parser, opts, args = parseOpts(argv)
# Set user agent
if opts.user_agent is not None:
std_headers['User-Agent'] = opts.user_agent
# Set referer
if opts.referer is not None:
std_headers['Referer'] = opts.referer
# Custom HTTP headers
if opts.headers is not None:
for h in opts.headers:
if ':' not in h:
parser.error('wrong header formatting, it should be key:value, not "%s"' % h)
key, value = h.split(':', 1)
if opts.verbose:
write_string('[debug] Adding header from command line option %s:%s\n' % (key, value))
std_headers[key] = value
# Dump user agent
if opts.dump_user_agent:
write_string(std_headers['User-Agent'] + '\n', out=sys.stdout)
sys.exit(0)
# Batch file verification
batch_urls = []
if opts.batchfile is not None:
try:
if opts.batchfile == '-':
batchfd = sys.stdin
else:
batchfd = io.open(
compat_expanduser(opts.batchfile),
'r', encoding='utf-8', errors='ignore')
batch_urls = read_batch_urls(batchfd)
if opts.verbose:
write_string('[debug] Batch file urls: ' + repr(batch_urls) + '\n')
except IOError:
sys.exit('ERROR: batch file could not be read')
all_urls = batch_urls + args
all_urls = [url.strip() for url in all_urls]
_enc = preferredencoding()
all_urls = [url.decode(_enc, 'ignore') if isinstance(url, bytes) else url for url in all_urls]
if opts.list_extractors:
for ie in list_extractors(opts.age_limit):
write_string(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else '') + '\n', out=sys.stdout)
matchedUrls = [url for url in all_urls if ie.suitable(url)]
for mu in matchedUrls:
write_string(' ' + mu + '\n', out=sys.stdout)
sys.exit(0)
if opts.list_extractor_descriptions:
for ie in list_extractors(opts.age_limit):
if not ie._WORKING:
continue
desc = getattr(ie, 'IE_DESC', ie.IE_NAME)
if desc is False:
continue
if hasattr(ie, 'SEARCH_KEY'):
_SEARCHES = ('cute kittens', 'slithering pythons', 'falling cat', 'angry poodle', 'purple fish', 'running tortoise', 'sleeping bunny', 'burping cow')
_COUNTS = ('', '5', '10', 'all')
desc += ' (Example: "%s%s:%s" )' % (ie.SEARCH_KEY, random.choice(_COUNTS), random.choice(_SEARCHES))
write_string(desc + '\n', out=sys.stdout)
sys.exit(0)
# Conflicting, missing and erroneous options
if opts.usenetrc and (opts.username is not None or opts.password is not None):
parser.error('using .netrc conflicts with giving username/password')
if opts.password is not None and opts.username is None:
parser.error('account username missing\n')
if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
parser.error('using output template conflicts with using title, video ID or auto number')
if opts.usetitle and opts.useid:
parser.error('using title conflicts with using video ID')
if opts.username is not None and opts.password is None:
opts.password = compat_getpass('Type account password and press [Return]: ')
if opts.ratelimit is not None:
numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
if numeric_limit is None:
parser.error('invalid rate limit specified')
opts.ratelimit = numeric_limit
if opts.min_filesize is not None:
numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
if numeric_limit is None:
parser.error('invalid min_filesize specified')
opts.min_filesize = numeric_limit
if opts.max_filesize is not None:
numeric_limit = FileDownloader.parse_bytes(opts.max_filesize)
if numeric_limit is None:
parser.error('invalid max_filesize specified')
opts.max_filesize = numeric_limit
if opts.sleep_interval is not None:
if opts.sleep_interval < 0:
parser.error('sleep interval must be positive or 0')
if opts.max_sleep_interval is not None:
if opts.max_sleep_interval < 0:
parser.error('max sleep interval must be positive or 0')
if opts.max_sleep_interval < opts.sleep_interval:
parser.error('max sleep interval must be greater than or equal to min sleep interval')
else:
opts.max_sleep_interval = opts.sleep_interval
def parse_retries(retries):
if retries in ('inf', 'infinite'):
parsed_retries = float('inf')
else:
try:
parsed_retries = int(retries)
except (TypeError, ValueError):
parser.error('invalid retry count specified')
return parsed_retries
if opts.retries is not None:
opts.retries = parse_retries(opts.retries)
if opts.fragment_retries is not None:
opts.fragment_retries = parse_retries(opts.fragment_retries)
if opts.buffersize is not None:
numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
if numeric_buffersize is None:
parser.error('invalid buffer size specified')
opts.buffersize = numeric_buffersize
if opts.playliststart <= 0:
raise ValueError('Playlist start must be positive')
if opts.playlistend not in (-1, None) and opts.playlistend < opts.playliststart:
raise ValueError('Playlist end must be greater than playlist start')
if opts.extractaudio:
if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
parser.error('invalid audio format specified')
if opts.audioquality:
opts.audioquality = opts.audioquality.strip('k').strip('K')
if not opts.audioquality.isdigit():
parser.error('invalid audio quality specified')
if opts.recodevideo is not None:
if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg', 'mkv', 'avi']:
parser.error('invalid video recode format specified')
if opts.convertsubtitles is not None:
if opts.convertsubtitles not in ['srt', 'vtt', 'ass']:
parser.error('invalid subtitle format specified')
if opts.date is not None:
date = DateRange.day(opts.date)
else:
date = DateRange(opts.dateafter, opts.datebefore)
# Do not download videos when there are audio-only formats
if opts.extractaudio and not opts.keepvideo and opts.format is None:
opts.format = 'bestaudio/best'
# --all-sub automatically sets --write-sub if --write-auto-sub is not given
# this was the old behaviour if only --all-sub was given.
if opts.allsubtitles and not opts.writeautomaticsub:
opts.writesubtitles = True
outtmpl = ((opts.outtmpl is not None and opts.outtmpl) or
(opts.format == '-1' and opts.usetitle and '%(title)s-%(id)s-%(format)s.%(ext)s') or
(opts.format == '-1' and '%(id)s-%(format)s.%(ext)s') or
(opts.usetitle and opts.autonumber and '%(autonumber)s-%(title)s-%(id)s.%(ext)s') or
(opts.usetitle and '%(title)s-%(id)s.%(ext)s') or
(opts.useid and '%(id)s.%(ext)s') or
(opts.autonumber and '%(autonumber)s-%(id)s.%(ext)s') or
DEFAULT_OUTTMPL)
if not os.path.splitext(outtmpl)[1] and opts.extractaudio:
parser.error('Cannot download a video and extract audio into the same'
' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
' template'.format(outtmpl))
any_getting = opts.geturl or opts.gettitle or opts.getid or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat or opts.getduration or opts.dumpjson or opts.dump_single_json
any_printing = opts.print_json
download_archive_fn = compat_expanduser(opts.download_archive) if opts.download_archive is not None else opts.download_archive
# PostProcessors
postprocessors = []
# Add the metadata pp first, the other pps will copy it
if opts.metafromtitle:
postprocessors.append({
'key': 'MetadataFromTitle',
'titleformat': opts.metafromtitle
})
if opts.addmetadata:
postprocessors.append({'key': 'FFmpegMetadata'})
if opts.extractaudio:
postprocessors.append({
'key': 'FFmpegExtractAudio',
'preferredcodec': opts.audioformat,
'preferredquality': opts.audioquality,
'nopostoverwrites': opts.nopostoverwrites,
})
if opts.recodevideo:
postprocessors.append({
'key': 'FFmpegVideoConvertor',
'preferedformat': opts.recodevideo,
})
if opts.convertsubtitles:
postprocessors.append({
'key': 'FFmpegSubtitlesConvertor',
'format': opts.convertsubtitles,
})
if opts.embedsubtitles:
postprocessors.append({
'key': 'FFmpegEmbedSubtitle',
})
if opts.xattrs:
postprocessors.append({'key': 'XAttrMetadata'})
if opts.embedthumbnail:
already_have_thumbnail = opts.writethumbnail or opts.write_all_thumbnails
postprocessors.append({
'key': 'EmbedThumbnail',
'already_have_thumbnail': already_have_thumbnail
})
if not already_have_thumbnail:
opts.writethumbnail = True
# Please keep ExecAfterDownload towards the bottom as it allows the user to modify the final file in any way.
# So if the user is able to remove the file before your postprocessor runs it might cause a few problems.
if opts.exec_cmd:
postprocessors.append({
'key': 'ExecAfterDownload',
'exec_cmd': opts.exec_cmd,
})
if opts.xattr_set_filesize:
try:
import xattr
xattr # Confuse flake8
except ImportError:
parser.error('setting filesize xattr requested but python-xattr is not available')
external_downloader_args = None
if opts.external_downloader_args:
external_downloader_args = compat_shlex_split(opts.external_downloader_args)
postprocessor_args = None
if opts.postprocessor_args:
postprocessor_args = compat_shlex_split(opts.postprocessor_args)
match_filter = (
None if opts.match_filter is None
else match_filter_func(opts.match_filter))
ydl_opts = {
'usenetrc': opts.usenetrc,
'username': opts.username,
'password': opts.password,
'twofactor': opts.twofactor,
'videopassword': opts.videopassword,
'quiet': (opts.quiet or any_getting or any_printing),
'no_warnings': opts.no_warnings,
'forceurl': opts.geturl,
'forcetitle': opts.gettitle,
'forceid': opts.getid,
'forcethumbnail': opts.getthumbnail,
'forcedescription': opts.getdescription,
'forceduration': opts.getduration,
'forcefilename': opts.getfilename,
'forceformat': opts.getformat,
'forcejson': opts.dumpjson or opts.print_json,
'dump_single_json': opts.dump_single_json,
'simulate': opts.simulate or any_getting,
'skip_download': opts.skip_download,
'format': opts.format,
'listformats': opts.listformats,
'outtmpl': outtmpl,
'autonumber_size': opts.autonumber_size,
'restrictfilenames': opts.restrictfilenames,
'ignoreerrors': opts.ignoreerrors,
'force_generic_extractor': opts.force_generic_extractor,
'ratelimit': opts.ratelimit,
'nooverwrites': opts.nooverwrites,
'retries': opts.retries,
'fragment_retries': opts.fragment_retries,
'buffersize': opts.buffersize,
'noresizebuffer': opts.noresizebuffer,
'continuedl': opts.continue_dl,
'noprogress': opts.noprogress,
'progress_with_newline': opts.progress_with_newline,
'playliststart': opts.playliststart,
'playlistend': opts.playlistend,
'playlistreverse': opts.playlist_reverse,
'noplaylist': opts.noplaylist,
'logtostderr': opts.outtmpl == '-',
'consoletitle': opts.consoletitle,
'nopart': opts.nopart,
'updatetime': opts.updatetime,
'writedescription': opts.writedescription,
'writeannotations': opts.writeannotations,
'writeinfojson': opts.writeinfojson,
'writethumbnail': opts.writethumbnail,
'write_all_thumbnails': opts.write_all_thumbnails,
'writesubtitles': opts.writesubtitles,
'writeautomaticsub': opts.writeautomaticsub,
'allsubtitles': opts.allsubtitles,
'listsubtitles': opts.listsubtitles,
'subtitlesformat': opts.subtitlesformat,
'subtitleslangs': opts.subtitleslangs,
'matchtitle': decodeOption(opts.matchtitle),
'rejecttitle': decodeOption(opts.rejecttitle),
'max_downloads': opts.max_downloads,
'prefer_free_formats': opts.prefer_free_formats,
'verbose': opts.verbose,
'dump_intermediate_pages': opts.dump_intermediate_pages,
'write_pages': opts.write_pages,
'test': opts.test,
'keepvideo': opts.keepvideo,
'min_filesize': opts.min_filesize,
'max_filesize': opts.max_filesize,
'min_views': opts.min_views,
'max_views': opts.max_views,
'daterange': date,
'cachedir': opts.cachedir,
'youtube_print_sig_code': opts.youtube_print_sig_code,
'age_limit': opts.age_limit,
'download_archive': download_archive_fn,
'cookiefile': opts.cookiefile,
'nocheckcertificate': opts.no_check_certificate,
'prefer_insecure': opts.prefer_insecure,
'proxy': opts.proxy,
'socket_timeout': opts.socket_timeout,
'bidi_workaround': opts.bidi_workaround,
'debug_printtraffic': opts.debug_printtraffic,
'prefer_ffmpeg': opts.prefer_ffmpeg,
'include_ads': opts.include_ads,
'default_search': opts.default_search,
'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
'encoding': opts.encoding,
'extract_flat': opts.extract_flat,
'mark_watched': opts.mark_watched,
'merge_output_format': opts.merge_output_format,
'postprocessors': postprocessors,
'fixup': opts.fixup,
'source_address': opts.source_address,
'call_home': opts.call_home,
'sleep_interval': opts.sleep_interval,
'max_sleep_interval': opts.max_sleep_interval,
'external_downloader': opts.external_downloader,
'list_thumbnails': opts.list_thumbnails,
'playlist_items': opts.playlist_items,
'xattr_set_filesize': opts.xattr_set_filesize,
'match_filter': match_filter,
'no_color': opts.no_color,
'ffmpeg_location': opts.ffmpeg_location,
'hls_prefer_native': opts.hls_prefer_native,
'hls_use_mpegts': opts.hls_use_mpegts,
'external_downloader_args': external_downloader_args,
'postprocessor_args': postprocessor_args,
'cn_verification_proxy': opts.cn_verification_proxy,
'geo_verification_proxy': opts.geo_verification_proxy,
}
with YoutubeDL(ydl_opts) as ydl:
# Update version
if opts.update_self:
update_self(ydl.to_screen, opts.verbose, ydl._opener)
# Remove cache dir
if opts.rm_cachedir:
ydl.cache.remove()
# Maybe do nothing
if (len(all_urls) < 1) and (opts.load_info_filename is None):
if opts.update_self or opts.rm_cachedir:
sys.exit()
ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
parser.error(
'You must provide at least one URL.\n'
'Type youtube-dl --help to see a list of all options.')
try:
if opts.load_info_filename is not None:
retcode = ydl.download_with_info_file(compat_expanduser(opts.load_info_filename))
else:
retcode = ydl.download(all_urls)
except MaxDownloadsReached:
ydl.to_screen('--max-download limit reached, aborting.')
retcode = 101
sys.exit(retcode)
def main(argv=None):
try:
_real_main(argv)
except DownloadError:
sys.exit(1)
except SameFileError:
sys.exit('ERROR: fixed output name but more than one file to download')
except KeyboardInterrupt:
sys.exit('\nERROR: Interrupted by user')
__all__ = ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']
| |
# Buy in the evening and then sell next day in the morning
#
# Buy again the next day
# repeat
# The idea
# we should buy in 10% increments (tunable) towards the end of the day if the price is going up
# every buy should be around 10 mins apart (tunable)
# Thus we have 10 sales, by eod
# Sell each tranche when they generate 1% profit the next day morning
# How the algo performsa
#
import time
from pytz import timezone
import datetime
import pytz
import pandas as pd
import numpy as np
# Put any initialization logic here. The context object will be passed to
# the other methods in your algorithm.
def initialize(context):
# context.stock = sid(3951) # add some specific securities
stocks = [sid(21724), sid(22257), sid(18522), sid(351), sid(6295), sid(20914)]
context.stocks = stocks
context.no_of_stocks = 6
context.max = 30000
context.min = 0
context.profit = 0.01
set_commission(commission.PerShare(cost=0.005))
set_slippage(slippage.FixedSlippage(spread=0.00))
context.last_sold_date = 0
context.last_bought_date = 0
# This defines when we actually want to buy the stock
context.buy_time_hour = 10
context.buy_time_minute = 10
context.sell_time_hour = 12
context.sell_time_minute = 10
context.increment_to_buy = 0.1
context.time_diff_between_buys = 10 # minutes
context.buy = [0]*context.no_of_stocks
context.buy_price = [0]*context.no_of_stocks
# context.all_sids = [sid(21724), sid(3951), sid(6295), sid(23709), sid(12959)] # add some specific securities
context.buy_and_hold_number = [0]*context.no_of_stocks
context.run_once = 1
context.last_bought_date = [0]*context.no_of_stocks
context.last_sold_date = [0]*context.no_of_stocks
context.last_bought_price = [0]*context.no_of_stocks
set_commission(commission.PerShare(cost=0.005))
set_slippage(slippage.FixedSlippage(spread=0.00))
########### HANDLE_DATA() IS RUN ONCE PER MINUTE #######################
def handle_data(context, data):
# If the stock has not yet started trading, exit it
for stock in context.stocks :
if stock not in data:
log.info(stock)
continue
# Get the current exchange time, in local timezone:
exchange_time = pd.Timestamp(get_datetime()).tz_convert('US/Eastern')
today = exchange_time.day + exchange_time.month*30 + exchange_time.year*365
# This is to compare against the buy and hold strategy
# So buy the first time when the algo runs, and then never sell
if context.run_once == 1:
i = 0
for stock in context.stocks :
context.buy_and_hold_number[i] = (context.max/context.no_of_stocks)/data[stock].price
log.info(stock)
log.info(context.buy_and_hold_number[i])
context.run_once = 0
i = i + 1
i = 0
total_buy_and_hold = 0
for stock in context.stocks :
# This is the graph of what would happen if we had just bought and kept
total_buy_and_hold = total_buy_and_hold + context.buy_and_hold_number[i] * data[stock].price
i = i + 1
# This is the graph of what would happen if we had just bought and kept
record(BuyAndHold=total_buy_and_hold)
# All the records
i = 0
for stock in context.stocks :
# This is the Price of the stock today
record(PRICE=data[stock].price)
# This is the value of the portfolio including current value of stock + cash we have
record(PortfolioValue=context.portfolio.positions_value \
+ int(context.portfolio.cash))
# this is the max of capital, to compare against the buy and hold value and portfolio values
#record(InitialCapital=context.max)
i = i + 1
if exchange_time.hour < context.buy_time_hour :
return
# First buy
if exchange_time.hour == context.buy_time_hour and \
exchange_time.minute == context.buy_time_minute:
i = -1
for stock in context.stocks :
i = i + 1
# # do all the buying here
# if (context.portfolio.positions[stock].amount == 0) :
# amount_to_buy = min(context.portfolio.cash, (context.max/context.no_of_stocks))
# else :
# amount_to_buy = min(context.portfolio.cash, \
# (context.max/context.no_of_stocks) - context.portfolio.positions[stock].amount*data[stock].price)
# context.order_id = order_value(stock, 0.19*(amount_to_buy))
# # Check the order to make sure that it has bought. Right now the filled below returns zero
# stock_order = get_order(context.order_id)
# # The check below shows if the object exists. Only if it exists, should you
# # refer to it. Otherwise you will get a runtime error
# if stock_order:
# message = ',buy,stock={stock},amount to buy={amount_to_buy},price={price},amount={amount}'
# message = message.format(stock=stock,amount=stock_order.amount, price=data[stock].price,amount_to_buy=amount_to_buy)
# log.info(message)
# record(BUY=data[stock].price)
context.last_bought_price[i] = data[stock].price
# continue
continue
# Second buy
i = -1
for stock in context.stocks :
i = i + 1
if exchange_time.hour == context.buy_time_hour and \
exchange_time.minute == context.buy_time_minute + 10 and \
data[stock].price > context.last_bought_price[i] :
# do all the buying here
if (context.portfolio.positions[stock].amount == 0) :
amount_to_buy = min(context.portfolio.cash, (context.max/context.no_of_stocks))
else :
amount_to_buy = min(context.portfolio.cash, \
(context.max/context.no_of_stocks) - context.portfolio.positions[stock].amount*data[stock].price)
context.order_id = order_value(stock, 0.39*(amount_to_buy))
# Check the order to make sure that it has bought. Right now the filled below returns zero
stock_order = get_order(context.order_id)
# The check below shows if the object exists. Only if it exists, should you
# refer to it. Otherwise you will get a runtime error
if stock_order:
message = ',buy,stock={stock},amount to buy={amount_to_buy},price={price},amount={amount}'
message = message.format(stock=stock,amount=stock_order.amount, price=data[stock].price,amount_to_buy=amount_to_buy)
log.info(message)
record(BUY=data[stock].price)
context.last_bought_price[i] = data[stock].price
continue
continue
# Third buy
i = -1
for stock in context.stocks :
i = i + 1
if exchange_time.hour == context.buy_time_hour and \
exchange_time.minute == context.buy_time_minute + 20 and \
data[stock].price > context.last_bought_price[i] :
# do all the buying here
if (context.portfolio.positions[stock].amount == 0) :
amount_to_buy = min(context.portfolio.cash, (context.max/context.no_of_stocks))
else :
amount_to_buy = min(context.portfolio.cash, \
(context.max/context.no_of_stocks) - context.portfolio.positions[stock].amount*data[stock].price)
context.order_id = order_value(stock, 0.59*(amount_to_buy))
# Check the order to make sure that it has bought. Right now the filled below returns zero
stock_order = get_order(context.order_id)
# The check below shows if the object exists. Only if it exists, should you
# refer to it. Otherwise you will get a runtime error
if stock_order:
message = ',buy,stock={stock},amount to buy={amount_to_buy},price={price},amount={amount}'
message = message.format(stock=stock,amount=stock_order.amount, price=data[stock].price,amount_to_buy=amount_to_buy)
log.info(message)
record(BUY=data[stock].price)
context.last_bought_price[i] = data[stock].price
continue
continue
# Fourth buy
i = -1
for stock in context.stocks :
i = i + 1
if exchange_time.hour == context.buy_time_hour and \
exchange_time.minute == context.buy_time_minute + 30 and \
data[stock].price > context.last_bought_price[i] :
# do all the buying here
if (context.portfolio.positions[stock].amount == 0) :
amount_to_buy = min(context.portfolio.cash, (context.max/context.no_of_stocks))
else :
amount_to_buy = min(context.portfolio.cash, \
(context.max/context.no_of_stocks) - context.portfolio.positions[stock].amount*data[stock].price)
context.order_id = order_value(stock, 0.79*(amount_to_buy))
# Check the order to make sure that it has bought. Right now the filled below returns zero
stock_order = get_order(context.order_id)
# The check below shows if the object exists. Only if it exists, should you
# refer to it. Otherwise you will get a runtime error
if stock_order:
message = ',buy,stock={stock},amount to buy={amount_to_buy},price={price},amount={amount}'
message = message.format(stock=stock,amount=stock_order.amount, price=data[stock].price,amount_to_buy=amount_to_buy)
log.info(message)
record(BUY=data[stock].price)
context.last_bought_price[i] = data[stock].price
continue
continue
# Fifth buy
i = -1
for stock in context.stocks :
i = i + 1
if exchange_time.hour == context.buy_time_hour and \
exchange_time.minute == context.buy_time_minute + 40 and \
data[stock].price > context.last_bought_price[i] :
# do all the buying here
if (context.portfolio.positions[stock].amount == 0) :
amount_to_buy = min(context.portfolio.cash, (context.max/context.no_of_stocks))
else :
amount_to_buy = min(context.portfolio.cash, \
(context.max/context.no_of_stocks) - context.portfolio.positions[stock].amount*data[stock].price)
context.order_id = order_value(stock, 0.94*(amount_to_buy))
# Check the order to make sure that it has bought. Right now the filled below returns zero
stock_order = get_order(context.order_id)
# The check below shows if the object exists. Only if it exists, should you
# refer to it. Otherwise you will get a runtime error
if stock_order:
message = ',buy,stock={stock},amount to buy={amount_to_buy},price={price},amount={amount}'
message = message.format(stock=stock,amount=stock_order.amount, price=data[stock].price,amount_to_buy=amount_to_buy)
log.info(message)
record(BUY=data[stock].price)
context.last_bought_price[i] = data[stock].price
continue
continue
if exchange_time.hour == context.sell_time_hour and \
exchange_time.minute == context.sell_time_minute:
i = 0
for stock in context.stocks :
context.order_id = order(stock, -context.portfolio.positions[stock].amount)
stock_order = get_order(context.order_id)
# The check below shows if the object exists. Only if it exists, should you
# refer to it. Otherwise you will get a runtime error
if stock_order:
# log the order amount and the amount that is filled
message = ',sell,stock={stock},amount to sell={amount_to_sell},price={price},amount={amount}'
message = message.format(stock=stock,amount=stock_order.amount, price=data[stock].price,amount_to_sell=stock_order.amount*data[stock].price)
log.info(message)
record(SELL=data[stock].price)
i = i + 1
| |
#!/usr/bin/env python
# encoding: utf-8
import logging
import inspect
import os
import tempfile
import threading
import time
from hashlib import md5
from itertools import izip
import cPickle as pickle
from functools import wraps
import errno
def generate_cache_key(namespace, f, *args, **kwargs):
"""Generates a string key, based on a given function
as well as arguments to the returned function itself.
"""
argspec = inspect.getargspec(f)
has_self = bool(argspec[0]) and argspec[0][0] in ('self', 'cls')
if has_self:
args = args[1:]
if not isinstance(f, basestring):
key_name = f.__name__
else:
key_name = f
if not namespace:
namespace = u'%s' % key_name
else:
namespace = u'%s|%s' % (namespace, key_name)
kwargs = kwargs.items()
if kwargs:
kwargs = map(lambda x: ','.join(x),
map(lambda x: map(unicode, x),
sorted(kwargs,
key=lambda x: x[0])))
return u':'.join([namespace] + map(unicode, args) + kwargs).encode('utf-8')
def _items(mappingorseq):
"""Wrapper for efficient iteration over mappings represented by dicts
or sequences::
>>> for k, v in _items((i, i*i) for i in xrange(5)):
... assert k*k == v
>>> for k, v in _items(dict((i, i*i) for i in xrange(5))):
... assert k*k == v
"""
return mappingorseq.iteritems() if hasattr(mappingorseq, 'iteritems') \
else mappingorseq
class BaseCache(object):
"""Baseclass for the cache systems. All the cache systems implement this
API or a superset of it.
:param default_timeout: the default timeout that is used if no timeout is
specified on :meth:`set`.
"""
def __init__(self, default_timeout=300):
self.default_timeout = default_timeout
def get(self, key):
"""Looks up key in the cache and returns the value for it.
If the key does not exist `None` is returned instead.
:param key: the key to be looked up.
"""
return None
def delete(self, key):
"""Deletes `key` from the cache. If it does not exist in the cache
nothing happens.
:param key: the key to delete.
"""
pass
def get_many(self, *keys):
"""Returns a list of values for the given keys.
For each key a item in the list is created. Example::
foo, bar = cache.get_many("foo", "bar")
If a key can't be looked up `None` is returned for that key
instead.
:param keys: The function accepts multiple keys as positional
arguments.
"""
return map(self.get, keys)
def get_dict(self, *keys):
"""Works like :meth:`get_many` but returns a dict::
d = cache.get_dict("foo", "bar")
foo = d["foo"]
bar = d["bar"]
:param keys: The function accepts multiple keys as positional
arguments.
"""
if not keys:
return {}
return dict(izip(keys, self.get_many(*keys)))
def set(self, key, value, timeout=None):
"""Adds a new key/value to the cache (overwrites value, if key already
exists in the cache).
:param key: the key to set
:param value: the value for the key
:param timeout: the cache timeout for the key (if not specified,
it uses the default timeout).
"""
pass
def add(self, key, value, timeout=None):
"""Works like :meth:`set` but does not overwrite the values of already
existing keys.
:param key: the key to set
:param value: the value for the key
:param timeout: the cache timeout for the key or the default
timeout if not specified.
"""
pass
def set_many(self, mapping, timeout=None):
"""Sets multiple keys and values from a mapping.
:param mapping: a mapping with the keys/values to set.
:param timeout: the cache timeout for the key (if not specified,
it uses the default timeout).
"""
for key, value in _items(mapping):
self.set(key, value, timeout)
def delete_many(self, *keys):
"""Deletes multiple keys at once.
:param keys: The function accepts multiple keys as positional
arguments.
"""
for key in keys:
self.delete(key)
def clear(self):
"""Clears the cache. Keep in mind that not all caches support
completely clearing the cache.
"""
pass
def inc(self, key, delta=1):
"""Increments the value of a key by `delta`. If the key does
not yet exist it is initialized with `delta`.
For supporting caches this is an atomic operation.
:param key: the key to increment.
:param delta: the delta to add.
"""
self.set(key, (self.get(key) or 0) + delta)
def dec(self, key, delta=1):
"""Decrements the value of a key by `delta`. If the key does
not yet exist it is initialized with `-delta`.
For supporting caches this is an atomic operation.
:param key: the key to increment.
:param delta: the delta to subtract.
"""
self.set(key, (self.get(key) or 0) - delta)
def cache(self, namespace=None, timeout=None):
def wrapper(f):
@wraps(f)
def call(*args, **kwargs):
cache_key = generate_cache_key(namespace, f, *args, **kwargs)
rv = self.get(cache_key)
if rv is None:
rv = f(*args, **kwargs)
self.add(cache_key, rv, timeout=timeout)
return rv
return call
return wrapper
class FileSystemCache(BaseCache):
"""A cache that stores the items on the file system. This cache depends
on being the only user of the `cache_dir`. Make absolutely sure that
nobody but this cache stores files there or otherwise the cache will
randomly delete files therein.
:param cache_dir: the directory where cache files are stored.
:param threshold: the maximum number of items the cache stores before
it starts deleting some.
:param default_timeout: the default timeout that is used if no timeout is
specified on :meth:`~BaseCache.set`. A timeout of
0 indicates that the cache never expires.
:param mode: the file mode wanted for the cache files, default 0600
"""
#: used for temporary files by the FileSystemCache
_fs_transaction_suffix = '.__wz_cache'
def __init__(self, cache_dir, threshold=500, default_timeout=300,
mode=0o600):
BaseCache.__init__(self, default_timeout)
self._path = cache_dir
self._threshold = threshold
self._mode = mode
self.lock = threading.Lock()
try:
os.makedirs(self._path)
except OSError as ex:
if ex.errno != errno.EEXIST:
raise
def _list_dir(self):
"""return a list of (fully qualified) cache filenames
"""
return [os.path.join(self._path, fn) for fn in os.listdir(self._path)
if not fn.endswith(self._fs_transaction_suffix)]
def _prune(self):
entries = self._list_dir()
if len(entries) > self._threshold:
now = time.time()
try:
for idx, fname in enumerate(entries):
with open(fname, 'rb') as f:
expires = pickle.load(f)
remove = (expires != 0 and expires <= now) or idx % 3 == 0
if remove:
os.remove(fname)
except (IOError, OSError):
pass
def clear(self):
with self.lock:
for fname in self._list_dir():
try:
os.remove(fname)
except (IOError, OSError):
return False
return True
def _get_filename(self, key):
if isinstance(key, unicode):
key = key.encode('utf-8') # XXX unicode review
_hash = md5(key).hexdigest()
return os.path.join(self._path, _hash)
def get(self, key):
filename = self._get_filename(key)
try:
with open(filename, 'rb') as f:
pickle_time = pickle.load(f)
if pickle_time == 0 or pickle_time >= time.time():
return pickle.load(f)
else:
os.remove(filename)
return None
except (IOError, OSError, pickle.PickleError):
return None
def add(self, key, value, timeout=None):
filename = self._get_filename(key)
if not os.path.exists(filename):
return self.set(key, value, timeout)
return False
def set(self, key, value, timeout=None):
if timeout is None:
timeout = int(time.time() + self.default_timeout)
elif timeout != 0:
timeout = int(time.time() + timeout)
filename = self._get_filename(key)
with self.lock:
self._prune()
try:
fd, tmp = tempfile.mkstemp(suffix=self._fs_transaction_suffix,
dir=self._path)
try:
with os.fdopen(fd, 'wb') as f:
pickle.dump(timeout, f, 1)
pickle.dump(value, f, pickle.HIGHEST_PROTOCOL)
except Exception as e:
try:
logging.error("fdopen error: %s", e)
os.close(fd)
except:
pass
os.rename(tmp, filename)
os.chmod(filename, self._mode)
except (IOError, OSError):
return False
else:
return True
def delete(self, key):
with self.lock:
try:
os.remove(self._get_filename(key))
except (IOError, OSError):
return False
else:
return True
def has(self, key):
filename = self._get_filename(key)
try:
with open(filename, 'rb') as f:
pickle_time = pickle.load(f)
if pickle_time == 0 or pickle_time >= time.time():
return True
else:
os.remove(filename)
return False
except (IOError, OSError, pickle.PickleError):
return False
class SimpleCache(BaseCache):
"""Simple memory cache for single process environments. This class exists
mainly for the development server and is not 100% thread safe. It tries
to use as many atomic operations as possible and no locks for simplicity
but it could happen under heavy load that keys are added multiple times.
:param threshold: the maximum number of items the cache stores before
it starts deleting some.
:param default_timeout: the default timeout that is used if no timeout is
specified on :meth:`~BaseCache.set`. A timeout of
0 indicates that the cache never expires.
"""
def __init__(self, threshold=500, default_timeout=300):
BaseCache.__init__(self, default_timeout)
self._cache = {}
self.clear = self._cache.clear
self._threshold = threshold
def _prune(self):
if len(self._cache) > self._threshold:
now = time.time()
toremove = []
for idx, (key, (expires, _)) in enumerate(self._cache.items()):
if (expires != 0 and expires <= now) or idx % 3 == 0:
toremove.append(key)
for key in toremove:
self._cache.pop(key, None)
def _get_expiration(self, timeout):
if timeout is None:
timeout = self.default_timeout
if timeout > 0:
timeout = time.time() + timeout
return timeout
def get(self, key):
try:
expires, value = self._cache[key]
if expires == 0 or expires > time.time():
return pickle.loads(value)
except (KeyError, pickle.PickleError):
return None
def set(self, key, value, timeout=None):
expires = self._get_expiration(timeout)
self._prune()
self._cache[key] = (expires, pickle.dumps(value,
pickle.HIGHEST_PROTOCOL))
return True
def add(self, key, value, timeout=None):
expires = self._get_expiration(timeout)
self._prune()
item = (expires, pickle.dumps(value,
pickle.HIGHEST_PROTOCOL))
if key in self._cache:
return False
self._cache.setdefault(key, item)
return True
def delete(self, key):
return self._cache.pop(key, None) is not None
def has(self, key):
try:
expires, value = self._cache[key]
return expires == 0 or expires > time.time()
except KeyError:
return False
| |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pprint
import sys
import textwrap
import pytest
from _pytest.main import _in_venv
from _pytest.main import EXIT_NOTESTSCOLLECTED
from _pytest.main import Session
class TestCollector(object):
def test_collect_versus_item(self):
from pytest import Collector, Item
assert not issubclass(Collector, Item)
assert not issubclass(Item, Collector)
def test_compat_attributes(self, testdir, recwarn):
modcol = testdir.getmodulecol(
"""
def test_pass(): pass
def test_fail(): assert 0
"""
)
recwarn.clear()
assert modcol.Module == pytest.Module
assert modcol.Class == pytest.Class
assert modcol.Item == pytest.Item
assert modcol.File == pytest.File
assert modcol.Function == pytest.Function
def test_check_equality(self, testdir):
modcol = testdir.getmodulecol(
"""
def test_pass(): pass
def test_fail(): assert 0
"""
)
fn1 = testdir.collect_by_name(modcol, "test_pass")
assert isinstance(fn1, pytest.Function)
fn2 = testdir.collect_by_name(modcol, "test_pass")
assert isinstance(fn2, pytest.Function)
assert fn1 == fn2
assert fn1 != modcol
if sys.version_info < (3, 0):
assert cmp(fn1, fn2) == 0 # NOQA
assert hash(fn1) == hash(fn2)
fn3 = testdir.collect_by_name(modcol, "test_fail")
assert isinstance(fn3, pytest.Function)
assert not (fn1 == fn3)
assert fn1 != fn3
for fn in fn1, fn2, fn3:
assert fn != 3
assert fn != modcol
assert fn != [1, 2, 3]
assert [1, 2, 3] != fn
assert modcol != fn
def test_getparent(self, testdir):
modcol = testdir.getmodulecol(
"""
class TestClass(object):
def test_foo():
pass
"""
)
cls = testdir.collect_by_name(modcol, "TestClass")
fn = testdir.collect_by_name(testdir.collect_by_name(cls, "()"), "test_foo")
parent = fn.getparent(pytest.Module)
assert parent is modcol
parent = fn.getparent(pytest.Function)
assert parent is fn
parent = fn.getparent(pytest.Class)
assert parent is cls
def test_getcustomfile_roundtrip(self, testdir):
hello = testdir.makefile(".xxx", hello="world")
testdir.makepyfile(
conftest="""
import pytest
class CustomFile(pytest.File):
pass
def pytest_collect_file(path, parent):
if path.ext == ".xxx":
return CustomFile(path, parent=parent)
"""
)
node = testdir.getpathnode(hello)
assert isinstance(node, pytest.File)
assert node.name == "hello.xxx"
nodes = node.session.perform_collect([node.nodeid], genitems=False)
assert len(nodes) == 1
assert isinstance(nodes[0], pytest.File)
def test_can_skip_class_with_test_attr(self, testdir):
"""Assure test class is skipped when using `__test__=False` (See #2007)."""
testdir.makepyfile(
"""
class TestFoo(object):
__test__ = False
def __init__(self):
pass
def test_foo():
assert True
"""
)
result = testdir.runpytest()
result.stdout.fnmatch_lines(["collected 0 items", "*no tests ran in*"])
class TestCollectFS(object):
def test_ignored_certain_directories(self, testdir):
tmpdir = testdir.tmpdir
tmpdir.ensure("build", "test_notfound.py")
tmpdir.ensure("dist", "test_notfound.py")
tmpdir.ensure("_darcs", "test_notfound.py")
tmpdir.ensure("CVS", "test_notfound.py")
tmpdir.ensure("{arch}", "test_notfound.py")
tmpdir.ensure(".whatever", "test_notfound.py")
tmpdir.ensure(".bzr", "test_notfound.py")
tmpdir.ensure("normal", "test_found.py")
for x in tmpdir.visit("test_*.py"):
x.write("def test_hello(): pass")
result = testdir.runpytest("--collect-only")
s = result.stdout.str()
assert "test_notfound" not in s
assert "test_found" in s
@pytest.mark.parametrize(
"fname",
(
"activate",
"activate.csh",
"activate.fish",
"Activate",
"Activate.bat",
"Activate.ps1",
),
)
def test_ignored_virtualenvs(self, testdir, fname):
bindir = "Scripts" if sys.platform.startswith("win") else "bin"
testdir.tmpdir.ensure("virtual", bindir, fname)
testfile = testdir.tmpdir.ensure("virtual", "test_invenv.py")
testfile.write("def test_hello(): pass")
# by default, ignore tests inside a virtualenv
result = testdir.runpytest()
assert "test_invenv" not in result.stdout.str()
# allow test collection if user insists
result = testdir.runpytest("--collect-in-virtualenv")
assert "test_invenv" in result.stdout.str()
# allow test collection if user directly passes in the directory
result = testdir.runpytest("virtual")
assert "test_invenv" in result.stdout.str()
@pytest.mark.parametrize(
"fname",
(
"activate",
"activate.csh",
"activate.fish",
"Activate",
"Activate.bat",
"Activate.ps1",
),
)
def test_ignored_virtualenvs_norecursedirs_precedence(self, testdir, fname):
bindir = "Scripts" if sys.platform.startswith("win") else "bin"
# norecursedirs takes priority
testdir.tmpdir.ensure(".virtual", bindir, fname)
testfile = testdir.tmpdir.ensure(".virtual", "test_invenv.py")
testfile.write("def test_hello(): pass")
result = testdir.runpytest("--collect-in-virtualenv")
assert "test_invenv" not in result.stdout.str()
# ...unless the virtualenv is explicitly given on the CLI
result = testdir.runpytest("--collect-in-virtualenv", ".virtual")
assert "test_invenv" in result.stdout.str()
@pytest.mark.parametrize(
"fname",
(
"activate",
"activate.csh",
"activate.fish",
"Activate",
"Activate.bat",
"Activate.ps1",
),
)
def test__in_venv(self, testdir, fname):
"""Directly test the virtual env detection function"""
bindir = "Scripts" if sys.platform.startswith("win") else "bin"
# no bin/activate, not a virtualenv
base_path = testdir.tmpdir.mkdir("venv")
assert _in_venv(base_path) is False
# with bin/activate, totally a virtualenv
base_path.ensure(bindir, fname)
assert _in_venv(base_path) is True
def test_custom_norecursedirs(self, testdir):
testdir.makeini(
"""
[pytest]
norecursedirs = mydir xyz*
"""
)
tmpdir = testdir.tmpdir
tmpdir.ensure("mydir", "test_hello.py").write("def test_1(): pass")
tmpdir.ensure("xyz123", "test_2.py").write("def test_2(): 0/0")
tmpdir.ensure("xy", "test_ok.py").write("def test_3(): pass")
rec = testdir.inline_run()
rec.assertoutcome(passed=1)
rec = testdir.inline_run("xyz123/test_2.py")
rec.assertoutcome(failed=1)
def test_testpaths_ini(self, testdir, monkeypatch):
testdir.makeini(
"""
[pytest]
testpaths = gui uts
"""
)
tmpdir = testdir.tmpdir
tmpdir.ensure("env", "test_1.py").write("def test_env(): pass")
tmpdir.ensure("gui", "test_2.py").write("def test_gui(): pass")
tmpdir.ensure("uts", "test_3.py").write("def test_uts(): pass")
# executing from rootdir only tests from `testpaths` directories
# are collected
items, reprec = testdir.inline_genitems("-v")
assert [x.name for x in items] == ["test_gui", "test_uts"]
# check that explicitly passing directories in the command-line
# collects the tests
for dirname in ("env", "gui", "uts"):
items, reprec = testdir.inline_genitems(tmpdir.join(dirname))
assert [x.name for x in items] == ["test_%s" % dirname]
# changing cwd to each subdirectory and running pytest without
# arguments collects the tests in that directory normally
for dirname in ("env", "gui", "uts"):
monkeypatch.chdir(testdir.tmpdir.join(dirname))
items, reprec = testdir.inline_genitems()
assert [x.name for x in items] == ["test_%s" % dirname]
class TestCollectPluginHookRelay(object):
def test_pytest_collect_file(self, testdir):
wascalled = []
class Plugin(object):
def pytest_collect_file(self, path, parent):
if not path.basename.startswith("."):
# Ignore hidden files, e.g. .testmondata.
wascalled.append(path)
testdir.makefile(".abc", "xyz")
pytest.main([testdir.tmpdir], plugins=[Plugin()])
assert len(wascalled) == 1
assert wascalled[0].ext == ".abc"
def test_pytest_collect_directory(self, testdir):
wascalled = []
class Plugin(object):
def pytest_collect_directory(self, path, parent):
wascalled.append(path.basename)
testdir.mkdir("hello")
testdir.mkdir("world")
pytest.main(testdir.tmpdir, plugins=[Plugin()])
assert "hello" in wascalled
assert "world" in wascalled
class TestPrunetraceback(object):
def test_custom_repr_failure(self, testdir):
p = testdir.makepyfile(
"""
import not_exists
"""
)
testdir.makeconftest(
"""
import pytest
def pytest_collect_file(path, parent):
return MyFile(path, parent)
class MyError(Exception):
pass
class MyFile(pytest.File):
def collect(self):
raise MyError()
def repr_failure(self, excinfo):
if excinfo.errisinstance(MyError):
return "hello world"
return pytest.File.repr_failure(self, excinfo)
"""
)
result = testdir.runpytest(p)
result.stdout.fnmatch_lines(["*ERROR collecting*", "*hello world*"])
@pytest.mark.xfail(reason="other mechanism for adding to reporting needed")
def test_collect_report_postprocessing(self, testdir):
p = testdir.makepyfile(
"""
import not_exists
"""
)
testdir.makeconftest(
"""
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_make_collect_report():
outcome = yield
rep = outcome.get_result()
rep.headerlines += ["header1"]
outcome.force_result(rep)
"""
)
result = testdir.runpytest(p)
result.stdout.fnmatch_lines(["*ERROR collecting*", "*header1*"])
class TestCustomConftests(object):
def test_ignore_collect_path(self, testdir):
testdir.makeconftest(
"""
def pytest_ignore_collect(path, config):
return path.basename.startswith("x") or \
path.basename == "test_one.py"
"""
)
sub = testdir.mkdir("xy123")
sub.ensure("test_hello.py").write("syntax error")
sub.join("conftest.py").write("syntax error")
testdir.makepyfile("def test_hello(): pass")
testdir.makepyfile(test_one="syntax error")
result = testdir.runpytest("--fulltrace")
assert result.ret == 0
result.stdout.fnmatch_lines(["*1 passed*"])
def test_ignore_collect_not_called_on_argument(self, testdir):
testdir.makeconftest(
"""
def pytest_ignore_collect(path, config):
return True
"""
)
p = testdir.makepyfile("def test_hello(): pass")
result = testdir.runpytest(p)
assert result.ret == 0
result.stdout.fnmatch_lines("*1 passed*")
result = testdir.runpytest()
assert result.ret == EXIT_NOTESTSCOLLECTED
result.stdout.fnmatch_lines("*collected 0 items*")
def test_collectignore_exclude_on_option(self, testdir):
testdir.makeconftest(
"""
collect_ignore = ['hello', 'test_world.py']
def pytest_addoption(parser):
parser.addoption("--XX", action="store_true", default=False)
def pytest_configure(config):
if config.getvalue("XX"):
collect_ignore[:] = []
"""
)
testdir.mkdir("hello")
testdir.makepyfile(test_world="def test_hello(): pass")
result = testdir.runpytest()
assert result.ret == EXIT_NOTESTSCOLLECTED
assert "passed" not in result.stdout.str()
result = testdir.runpytest("--XX")
assert result.ret == 0
assert "passed" in result.stdout.str()
def test_pytest_fs_collect_hooks_are_seen(self, testdir):
testdir.makeconftest(
"""
import pytest
class MyModule(pytest.Module):
pass
def pytest_collect_file(path, parent):
if path.ext == ".py":
return MyModule(path, parent)
"""
)
testdir.mkdir("sub")
testdir.makepyfile("def test_x(): pass")
result = testdir.runpytest("--collect-only")
result.stdout.fnmatch_lines(["*MyModule*", "*test_x*"])
def test_pytest_collect_file_from_sister_dir(self, testdir):
sub1 = testdir.mkpydir("sub1")
sub2 = testdir.mkpydir("sub2")
conf1 = testdir.makeconftest(
"""
import pytest
class MyModule1(pytest.Module):
pass
def pytest_collect_file(path, parent):
if path.ext == ".py":
return MyModule1(path, parent)
"""
)
conf1.move(sub1.join(conf1.basename))
conf2 = testdir.makeconftest(
"""
import pytest
class MyModule2(pytest.Module):
pass
def pytest_collect_file(path, parent):
if path.ext == ".py":
return MyModule2(path, parent)
"""
)
conf2.move(sub2.join(conf2.basename))
p = testdir.makepyfile("def test_x(): pass")
p.copy(sub1.join(p.basename))
p.copy(sub2.join(p.basename))
result = testdir.runpytest("--collect-only")
result.stdout.fnmatch_lines(["*MyModule1*", "*MyModule2*", "*test_x*"])
class TestSession(object):
def test_parsearg(self, testdir):
p = testdir.makepyfile("def test_func(): pass")
subdir = testdir.mkdir("sub")
subdir.ensure("__init__.py")
target = subdir.join(p.basename)
p.move(target)
subdir.chdir()
config = testdir.parseconfig(p.basename)
rcol = Session(config=config)
assert rcol.fspath == subdir
parts = rcol._parsearg(p.basename)
assert parts[0] == target
assert len(parts) == 1
parts = rcol._parsearg(p.basename + "::test_func")
assert parts[0] == target
assert parts[1] == "test_func"
assert len(parts) == 2
def test_collect_topdir(self, testdir):
p = testdir.makepyfile("def test_func(): pass")
id = "::".join([p.basename, "test_func"])
# XXX migrate to collectonly? (see below)
config = testdir.parseconfig(id)
topdir = testdir.tmpdir
rcol = Session(config)
assert topdir == rcol.fspath
# rootid = rcol.nodeid
# root2 = rcol.perform_collect([rcol.nodeid], genitems=False)[0]
# assert root2 == rcol, rootid
colitems = rcol.perform_collect([rcol.nodeid], genitems=False)
assert len(colitems) == 1
assert colitems[0].fspath == p
def get_reported_items(self, hookrec):
"""Return pytest.Item instances reported by the pytest_collectreport hook"""
calls = hookrec.getcalls("pytest_collectreport")
return [
x
for call in calls
for x in call.report.result
if isinstance(x, pytest.Item)
]
def test_collect_protocol_single_function(self, testdir):
p = testdir.makepyfile("def test_func(): pass")
id = "::".join([p.basename, "test_func"])
items, hookrec = testdir.inline_genitems(id)
item, = items
assert item.name == "test_func"
newid = item.nodeid
assert newid == id
pprint.pprint(hookrec.calls)
topdir = testdir.tmpdir # noqa
hookrec.assert_contains(
[
("pytest_collectstart", "collector.fspath == topdir"),
("pytest_make_collect_report", "collector.fspath == topdir"),
("pytest_collectstart", "collector.fspath == p"),
("pytest_make_collect_report", "collector.fspath == p"),
("pytest_pycollect_makeitem", "name == 'test_func'"),
("pytest_collectreport", "report.result[0].name == 'test_func'"),
]
)
# ensure we are reporting the collection of the single test item (#2464)
assert [x.name for x in self.get_reported_items(hookrec)] == ["test_func"]
def test_collect_protocol_method(self, testdir):
p = testdir.makepyfile(
"""
class TestClass(object):
def test_method(self):
pass
"""
)
normid = p.basename + "::TestClass::()::test_method"
for id in [
p.basename,
p.basename + "::TestClass",
p.basename + "::TestClass::()",
normid,
]:
items, hookrec = testdir.inline_genitems(id)
assert len(items) == 1
assert items[0].name == "test_method"
newid = items[0].nodeid
assert newid == normid
# ensure we are reporting the collection of the single test item (#2464)
assert [x.name for x in self.get_reported_items(hookrec)] == ["test_method"]
def test_collect_custom_nodes_multi_id(self, testdir):
p = testdir.makepyfile("def test_func(): pass")
testdir.makeconftest(
"""
import pytest
class SpecialItem(pytest.Item):
def runtest(self):
return # ok
class SpecialFile(pytest.File):
def collect(self):
return [SpecialItem(name="check", parent=self)]
def pytest_collect_file(path, parent):
if path.basename == %r:
return SpecialFile(fspath=path, parent=parent)
"""
% p.basename
)
id = p.basename
items, hookrec = testdir.inline_genitems(id)
pprint.pprint(hookrec.calls)
assert len(items) == 2
hookrec.assert_contains(
[
("pytest_collectstart", "collector.fspath == collector.session.fspath"),
(
"pytest_collectstart",
"collector.__class__.__name__ == 'SpecialFile'",
),
("pytest_collectstart", "collector.__class__.__name__ == 'Module'"),
("pytest_pycollect_makeitem", "name == 'test_func'"),
("pytest_collectreport", "report.nodeid.startswith(p.basename)"),
]
)
assert len(self.get_reported_items(hookrec)) == 2
def test_collect_subdir_event_ordering(self, testdir):
p = testdir.makepyfile("def test_func(): pass")
aaa = testdir.mkpydir("aaa")
test_aaa = aaa.join("test_aaa.py")
p.move(test_aaa)
items, hookrec = testdir.inline_genitems()
assert len(items) == 1
pprint.pprint(hookrec.calls)
hookrec.assert_contains(
[
("pytest_collectstart", "collector.fspath == test_aaa"),
("pytest_pycollect_makeitem", "name == 'test_func'"),
("pytest_collectreport", "report.nodeid.startswith('aaa/test_aaa.py')"),
]
)
def test_collect_two_commandline_args(self, testdir):
p = testdir.makepyfile("def test_func(): pass")
aaa = testdir.mkpydir("aaa")
bbb = testdir.mkpydir("bbb")
test_aaa = aaa.join("test_aaa.py")
p.copy(test_aaa)
test_bbb = bbb.join("test_bbb.py")
p.move(test_bbb)
id = "."
items, hookrec = testdir.inline_genitems(id)
assert len(items) == 2
pprint.pprint(hookrec.calls)
hookrec.assert_contains(
[
("pytest_collectstart", "collector.fspath == test_aaa"),
("pytest_pycollect_makeitem", "name == 'test_func'"),
("pytest_collectreport", "report.nodeid == 'aaa/test_aaa.py'"),
("pytest_collectstart", "collector.fspath == test_bbb"),
("pytest_pycollect_makeitem", "name == 'test_func'"),
("pytest_collectreport", "report.nodeid == 'bbb/test_bbb.py'"),
]
)
def test_serialization_byid(self, testdir):
testdir.makepyfile("def test_func(): pass")
items, hookrec = testdir.inline_genitems()
assert len(items) == 1
item, = items
items2, hookrec = testdir.inline_genitems(item.nodeid)
item2, = items2
assert item2.name == item.name
assert item2.fspath == item.fspath
def test_find_byid_without_instance_parents(self, testdir):
p = testdir.makepyfile(
"""
class TestClass(object):
def test_method(self):
pass
"""
)
arg = p.basename + "::TestClass::test_method"
items, hookrec = testdir.inline_genitems(arg)
assert len(items) == 1
item, = items
assert item.nodeid.endswith("TestClass::()::test_method")
# ensure we are reporting the collection of the single test item (#2464)
assert [x.name for x in self.get_reported_items(hookrec)] == ["test_method"]
class Test_getinitialnodes(object):
def test_global_file(self, testdir, tmpdir):
x = tmpdir.ensure("x.py")
with tmpdir.as_cwd():
config = testdir.parseconfigure(x)
col = testdir.getnode(config, x)
assert isinstance(col, pytest.Module)
assert col.name == "x.py"
assert col.parent.parent is None
for col in col.listchain():
assert col.config is config
def test_pkgfile(self, testdir):
"""Verify nesting when a module is within a package.
The parent chain should match: Module<x.py> -> Package<subdir> -> Session.
Session's parent should always be None.
"""
tmpdir = testdir.tmpdir
subdir = tmpdir.join("subdir")
x = subdir.ensure("x.py")
subdir.ensure("__init__.py")
with subdir.as_cwd():
config = testdir.parseconfigure(x)
col = testdir.getnode(config, x)
assert col.name == "x.py"
assert isinstance(col, pytest.Module)
assert isinstance(col.parent, pytest.Package)
assert isinstance(col.parent.parent, pytest.Session)
# session is batman (has no parents)
assert col.parent.parent.parent is None
for col in col.listchain():
assert col.config is config
class Test_genitems(object):
def test_check_collect_hashes(self, testdir):
p = testdir.makepyfile(
"""
def test_1():
pass
def test_2():
pass
"""
)
p.copy(p.dirpath(p.purebasename + "2" + ".py"))
items, reprec = testdir.inline_genitems(p.dirpath())
assert len(items) == 4
for numi, i in enumerate(items):
for numj, j in enumerate(items):
if numj != numi:
assert hash(i) != hash(j)
assert i != j
def test_example_items1(self, testdir):
p = testdir.makepyfile(
"""
def testone():
pass
class TestX(object):
def testmethod_one(self):
pass
class TestY(TestX):
pass
"""
)
items, reprec = testdir.inline_genitems(p)
assert len(items) == 3
assert items[0].name == "testone"
assert items[1].name == "testmethod_one"
assert items[2].name == "testmethod_one"
# let's also test getmodpath here
assert items[0].getmodpath() == "testone"
assert items[1].getmodpath() == "TestX.testmethod_one"
assert items[2].getmodpath() == "TestY.testmethod_one"
s = items[0].getmodpath(stopatmodule=False)
assert s.endswith("test_example_items1.testone")
print(s)
def test_class_and_functions_discovery_using_glob(self, testdir):
"""
tests that python_classes and python_functions config options work
as prefixes and glob-like patterns (issue #600).
"""
testdir.makeini(
"""
[pytest]
python_classes = *Suite Test
python_functions = *_test test
"""
)
p = testdir.makepyfile(
"""
class MyTestSuite(object):
def x_test(self):
pass
class TestCase(object):
def test_y(self):
pass
"""
)
items, reprec = testdir.inline_genitems(p)
ids = [x.getmodpath() for x in items]
assert ids == ["MyTestSuite.x_test", "TestCase.test_y"]
def test_matchnodes_two_collections_same_file(testdir):
testdir.makeconftest(
"""
import pytest
def pytest_configure(config):
config.pluginmanager.register(Plugin2())
class Plugin2(object):
def pytest_collect_file(self, path, parent):
if path.ext == ".abc":
return MyFile2(path, parent)
def pytest_collect_file(path, parent):
if path.ext == ".abc":
return MyFile1(path, parent)
class MyFile1(pytest.Item, pytest.File):
def runtest(self):
pass
class MyFile2(pytest.File):
def collect(self):
return [Item2("hello", parent=self)]
class Item2(pytest.Item):
def runtest(self):
pass
"""
)
p = testdir.makefile(".abc", "")
result = testdir.runpytest()
assert result.ret == 0
result.stdout.fnmatch_lines(["*2 passed*"])
res = testdir.runpytest("%s::hello" % p.basename)
res.stdout.fnmatch_lines(["*1 passed*"])
class TestNodekeywords(object):
def test_no_under(self, testdir):
modcol = testdir.getmodulecol(
"""
def test_pass(): pass
def test_fail(): assert 0
"""
)
values = list(modcol.keywords)
assert modcol.name in values
for x in values:
assert not x.startswith("_")
assert modcol.name in repr(modcol.keywords)
def test_issue345(self, testdir):
testdir.makepyfile(
"""
def test_should_not_be_selected():
assert False, 'I should not have been selected to run'
def test___repr__():
pass
"""
)
reprec = testdir.inline_run("-k repr")
reprec.assertoutcome(passed=1, failed=0)
COLLECTION_ERROR_PY_FILES = dict(
test_01_failure="""
def test_1():
assert False
""",
test_02_import_error="""
import asdfasdfasdf
def test_2():
assert True
""",
test_03_import_error="""
import asdfasdfasdf
def test_3():
assert True
""",
test_04_success="""
def test_4():
assert True
""",
)
def test_exit_on_collection_error(testdir):
"""Verify that all collection errors are collected and no tests executed"""
testdir.makepyfile(**COLLECTION_ERROR_PY_FILES)
res = testdir.runpytest()
assert res.ret == 2
res.stdout.fnmatch_lines(
[
"collected 2 items / 2 errors",
"*ERROR collecting test_02_import_error.py*",
"*No module named *asdfa*",
"*ERROR collecting test_03_import_error.py*",
"*No module named *asdfa*",
]
)
def test_exit_on_collection_with_maxfail_smaller_than_n_errors(testdir):
"""
Verify collection is aborted once maxfail errors are encountered ignoring
further modules which would cause more collection errors.
"""
testdir.makepyfile(**COLLECTION_ERROR_PY_FILES)
res = testdir.runpytest("--maxfail=1")
assert res.ret == 1
res.stdout.fnmatch_lines(
["*ERROR collecting test_02_import_error.py*", "*No module named *asdfa*"]
)
assert "test_03" not in res.stdout.str()
def test_exit_on_collection_with_maxfail_bigger_than_n_errors(testdir):
"""
Verify the test run aborts due to collection errors even if maxfail count of
errors was not reached.
"""
testdir.makepyfile(**COLLECTION_ERROR_PY_FILES)
res = testdir.runpytest("--maxfail=4")
assert res.ret == 2
res.stdout.fnmatch_lines(
[
"collected 2 items / 2 errors",
"*ERROR collecting test_02_import_error.py*",
"*No module named *asdfa*",
"*ERROR collecting test_03_import_error.py*",
"*No module named *asdfa*",
]
)
def test_continue_on_collection_errors(testdir):
"""
Verify tests are executed even when collection errors occur when the
--continue-on-collection-errors flag is set
"""
testdir.makepyfile(**COLLECTION_ERROR_PY_FILES)
res = testdir.runpytest("--continue-on-collection-errors")
assert res.ret == 1
res.stdout.fnmatch_lines(
["collected 2 items / 2 errors", "*1 failed, 1 passed, 2 error*"]
)
def test_continue_on_collection_errors_maxfail(testdir):
"""
Verify tests are executed even when collection errors occur and that maxfail
is honoured (including the collection error count).
4 tests: 2 collection errors + 1 failure + 1 success
test_4 is never executed because the test run is with --maxfail=3 which
means it is interrupted after the 2 collection errors + 1 failure.
"""
testdir.makepyfile(**COLLECTION_ERROR_PY_FILES)
res = testdir.runpytest("--continue-on-collection-errors", "--maxfail=3")
assert res.ret == 1
res.stdout.fnmatch_lines(["collected 2 items / 2 errors", "*1 failed, 2 error*"])
def test_fixture_scope_sibling_conftests(testdir):
"""Regression test case for https://github.com/pytest-dev/pytest/issues/2836"""
foo_path = testdir.mkdir("foo")
foo_path.join("conftest.py").write(
textwrap.dedent(
"""\
import pytest
@pytest.fixture
def fix():
return 1
"""
)
)
foo_path.join("test_foo.py").write("def test_foo(fix): assert fix == 1")
# Tests in `food/` should not see the conftest fixture from `foo/`
food_path = testdir.mkpydir("food")
food_path.join("test_food.py").write("def test_food(fix): assert fix == 1")
res = testdir.runpytest()
assert res.ret == 1
res.stdout.fnmatch_lines(
[
"*ERROR at setup of test_food*",
"E*fixture 'fix' not found",
"*1 passed, 1 error*",
]
)
def test_collect_init_tests(testdir):
"""Check that we collect files from __init__.py files when they patch the 'python_files' (#3773)"""
p = testdir.copy_example("collect/collect_init_tests")
result = testdir.runpytest(p, "--collect-only")
result.stdout.fnmatch_lines(
[
"*<Module '__init__.py'>",
"*<Function 'test_init'>",
"*<Module 'test_foo.py'>",
"*<Function 'test_foo'>",
]
)
def test_collect_invalid_signature_message(testdir):
"""Check that we issue a proper message when we can't determine the signature of a test
function (#4026).
"""
testdir.makepyfile(
"""
import pytest
class TestCase:
@pytest.fixture
def fix():
pass
"""
)
result = testdir.runpytest()
result.stdout.fnmatch_lines(
["Could not determine arguments of *.fix *: invalid method signature"]
)
| |
# Copyright 2022 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from django.test import TestCase
from django.conf import settings
from django.test.client import Client, encode_multipart
from django.core.files.uploadedfile import SimpleUploadedFile
from spotseeker_server.models import Spot, SpotImage
from os.path import abspath, dirname
import os
import random
import tempfile
import shutil
from django.test.utils import override_settings
from mock import patch
from spotseeker_server import models
TEST_ROOT = abspath(dirname(__file__))
@override_settings(SPOTSEEKER_AUTH_MODULE="spotseeker_server.auth.all_ok")
@override_settings(SPOTSEEKER_AUTH_ADMINS=("demo_user",))
class SpotImagePUTTest(TestCase):
"""Tests updating a SpotImage by PUTting to
/api/v1/spot/<spot id>/image/<image_id>.
"""
def setUp(self):
self.TEMP_DIR = tempfile.mkdtemp()
with self.settings(MEDIA_ROOT=self.TEMP_DIR):
spot = Spot.objects.create(
name="This is to test PUTtingimages", capacity=1
)
spot.save()
self.spot = spot
self.url = "/api/v1/spot/{0}".format(self.spot.pk)
self.url = self.url
# GIF
gif = self.spot.spotimage_set.create(
description="This is the GIF test",
image=SimpleUploadedFile(
"test_gif.gif",
open(
"%s/../resources/test_gif.gif" % TEST_ROOT, "rb"
).read(),
"image/gif",
),
)
self.gif = gif
self.gif_url = "%s/image/%s" % (self.url, self.gif.pk)
# JPEG
jpeg = self.spot.spotimage_set.create(
description="This is the JPEG test",
image=SimpleUploadedFile(
"test_jpeg.jpg",
open(
"%s/../resources/test_jpeg.jpg" % TEST_ROOT, "rb"
).read(),
"image/jpeg",
),
)
self.jpeg = jpeg
self.jpeg_url = "%s/image/%s" % (self.url, self.jpeg.pk)
# PNG
png = self.spot.spotimage_set.create(
description="This is the PNG test",
image=SimpleUploadedFile(
"test_png.png",
open(
"%s/../resources/test_png.png" % TEST_ROOT, "rb"
).read(),
"image/png",
),
)
self.png = png
self.png_url = "%s/image/%s" % (self.url, self.png.pk)
def test_bad_url(self):
with self.settings(MEDIA_ROOT=self.TEMP_DIR):
c = Client()
spot = Spot.objects.create(name="This is the wrong spot")
url = "/api/v1/spot/{0}/image/{1}".format(spot.pk, self.jpeg.pk)
response = c.put(url, "{}", content_type="application/json")
self.assertEquals(response.status_code, 404)
def test_invalid_url(self):
with self.settings(MEDIA_ROOT=self.TEMP_DIR):
c = Client()
bad_url = "%s/image/aa" % self.url
response = c.put(bad_url, "{}", content_type="application/json")
self.assertEquals(response.status_code, 404)
def test_invalid_id_too_high(self):
with self.settings(MEDIA_ROOT=self.TEMP_DIR):
c = Client()
test_id = self.gif.pk + 10000
test_url = "%s/image/%s" % (self.url, test_id)
response = c.put(test_url, "{}", content_type="application/json")
self.assertEquals(response.status_code, 404)
def test_valid_same_type_with_etag(self):
with self.settings(MEDIA_ROOT=self.TEMP_DIR):
c = Client()
response = c.get(self.jpeg_url)
try:
etag = unicode(response["etag"])
except NameError:
etag = response["etag"]
new_jpeg_name = "testing PUT name: {0}".format(random.random())
response = c.put(
self.jpeg_url,
files={
"description": new_jpeg_name,
"image": SimpleUploadedFile(
"test_jpeg2.jpg",
open(
"%s/../resources/test_jpeg2.jpg" % TEST_ROOT, "rb"
).read(),
"image/jpeg",
),
},
If_Match=etag,
)
f = open("%s/../resources/test_jpeg2.jpg" % TEST_ROOT, "rb")
f2 = open("%s/../resources/test_jpeg.jpg" % TEST_ROOT, "rb")
self.assertEquals(response.status_code, 200)
self.assertEquals(int(response["content-length"]), len(f.read()))
self.assertNotEqual(
int(response["content-length"]), len(f2.read())
)
self.assertEquals(response["content-type"], "image/jpeg")
def test_valid_different_image_type_valid_etag(self):
with self.settings(MEDIA_ROOT=self.TEMP_DIR):
c = Client()
response = c.get(self.gif_url)
try:
etag = unicode(response["etag"])
except NameError:
etag = response["etag"]
new_name = "testing PUT name: {0}".format(random.random())
response = c.put(
self.gif_url,
files={
"description": new_name,
"image": SimpleUploadedFile(
new_name,
open(
"%s/../resources/test_png.png" % TEST_ROOT, "rb"
).read(),
"image/png",
),
},
content_type="multipart/form-data; boundary=--aklsjf--",
If_Match=etag,
)
self.assertEquals(response.status_code, 200)
f = open("%s/../resources/test_png.png" % TEST_ROOT, "rb")
f2 = open("%s/../resources/test_gif.gif" % TEST_ROOT, "rb")
# Just to be sure
response = c.get(self.gif_url)
self.assertEquals(response["content-type"], "image/png")
self.assertEquals(int(response["content-length"]), len(f.read()))
self.assertNotEqual(
int(response["content-length"]), len(f2.read())
)
def test_invalid_image_type_valid_etag(self):
with self.settings(MEDIA_ROOT=self.TEMP_DIR):
c = Client()
response = c.get(self.gif_url)
etag = response["etag"]
f = open("%s/../resources/test_png.png" % TEST_ROOT, "rb")
f2 = open("%s/../resources/test_gif.gif" % TEST_ROOT, "rb")
new_name = "testing PUT name: {0}".format(random.random())
c = Client()
f = open("%s/../resources/fake_jpeg.jpg" % TEST_ROOT, "rb")
response = c.put(
self.gif_url,
files={"description": "This is a text file", "image": f},
If_Match=etag,
)
f.close()
self.assertEquals(response.status_code, 400)
# Want this to be one of the first tests to run
def test_a_valid_image_no_etag(self):
with self.settings(MEDIA_ROOT=self.TEMP_DIR):
c = Client()
# GIF
f = open("%s/../resources/test_gif2.gif" % TEST_ROOT, "rb")
new_gif_name = "testing PUT name: {0}".format(random.random())
response = c.put(
self.gif_url,
files={"description": new_gif_name, "image": f},
content_type="image/gif",
)
self.assertEquals(response.status_code, 400)
updated_img = SpotImage.objects.get(pk=self.gif.pk)
self.assertEquals(updated_img.image, self.gif.image)
# JPEG
f = open("%s/../resources/test_jpeg2.jpg" % TEST_ROOT, "rb")
new_jpeg_name = "testing PUT name: {0}".format(random.random())
response = c.put(
self.gif_url,
files={"description": new_jpeg_name, "image": f},
content_type="image/jpeg",
)
self.assertEquals(response.status_code, 400)
updated_img = SpotImage.objects.get(pk=self.jpeg.pk)
self.assertEquals(updated_img.description, self.jpeg.description)
# PNG
f = open("%s/../resources/test_png2.png" % TEST_ROOT, "rb")
new_png_name = "testing PUT name: {0}".format(random.random())
response = c.put(
self.gif_url,
files={"description": new_png_name, "image": f},
content_type="image/png",
)
self.assertEquals(response.status_code, 400)
updated_img = SpotImage.objects.get(pk=self.png.pk)
self.assertEquals(updated_img.description, self.png.description)
response = c.get(self.gif_url)
content_length = response["content-length"]
self.assertNotEqual(
os.fstat(f.fileno()).st_size, int(content_length)
)
f = open("%s/../resources/test_gif.gif" % TEST_ROOT, "rb")
self.assertEquals(
os.fstat(f.fileno()).st_size, int(content_length)
)
def tearDown(self):
shutil.rmtree(self.TEMP_DIR)
| |
#!/usr/bin/env python
# http://stackoverflow.com/questions/23046809/filtering-based-on-key-value-in-all-objects-in-array-in-rethinkdb
import rethinkdb as r
from optparse import OptionParser
import json
import sys
def string_or_number(s):
try:
val = int(s)
return val
except ValueError:
try:
val = float(s)
return val
except ValueError:
return s
class PropertyPath(object):
def __init__(self, path):
self.path = path
def path_match(self, prop_hash):
"""Match against a list of path element, prop_hash
is the hash we want to descend through in out list
of path elements making sure they all match.
Returns 'True, value' if there was a match, and
'False,""' otherwise.
"""
in_path = prop_hash
for path_element in self.path:
if path_element in in_path:
in_path = in_path[path_element]
else:
return False, ""
return True, in_path
class SingleAttrQuery(PropertyPath):
def __init__(self, value, _type, *path):
PropertyPath.__init__(self, path)
self.value = string_or_number(value)
self._type = _type
def match(self, attr):
matched, value = self.path_match(attr)
if matched and self._match(value):
return True
elif not matched and self._type == "UNK":
return True
else:
return False
def _match(self, value):
if self._type == "LT":
return value < self.value
elif self._type == "LTE":
return value <= self.value
elif self._type == "GT":
return value > self.value
elif self._type == "GTE":
return value >= self.value
elif self._type == "EQ":
return self.value == value
elif self._type == "KN":
# if we got here then there is a value
return True
else:
return False
class RangeQuery(PropertyPath):
def __init__(self, left_value, left_type, right_value, right_type, *path):
PropertyPath.__init__(self, path)
self.left_value = string_or_number(left_value)
self.left_type = left_type
self.right_value = string_or_number(right_value)
self.right_type = right_type
self.path = path
def match(self, attr):
matched, value = self.path_match(attr)
if matched:
lower_bound = self._match(self.left_type, self.left_value, value)
upper_bound = self._match(self.right_type, value, self.right_value)
return lower_bound and upper_bound
else:
return False
def _match(self, _type, value_left, value_right):
if _type == "LT":
return value_left < value_right
elif _type == "LTE":
return value_left <= value_right
elif _type == "GT":
return value_right < value_left
elif _type == "GTE":
return value_right <= value_left
else:
return False
class Query(object):
def __init__(self, _type, *sub_queries):
self._type = _type
self.sub_queries = sub_queries
def match_query(samples, *queries):
matching_samples = []
for sample in samples:
matched_attrs = []
for attr in sample["attributes"]:
for query in queries:
if query.match(attr):
matched_attrs.append(True)
if len(matched_attrs) == len(queries):
matching_samples.append(sample)
return matching_samples
def search(conn, queries):
value = list(r.table("samples")
.eq_join("id", r.table("sample2attribute_set"),
index="sample_id")
.zip()
.merge(lambda aset: {
"attributes": r.table("attribute_set2attribute")
.get_all(aset["attribute_set_id"],
index="attribute_set_id")
.eq_join("attribute_id", r.table("attributes"))
.zip()
.merge(lambda attr: {
"best_measure": r.table("measurements")
.get(attr["best_measure_id"])
})
.coerce_to("array"),
"processes": r.table("process2sample")
.get_all(aset["sample_id"], index="sample_id")
.eq_join("process_id", r.table("processes"))
.zip()
.merge(lambda proc: {
"settings": r.table("process2setting")
.get_all(proc['id'], index="process_id")
.eq_join("setting_id", r.table("settings"))
.zip()
.coerce_to("array")
})
.coerce_to("array")
})
.run(conn, time_format="raw"))
ms = match_query(value, *queries)
print json.dumps(ms)
def construct_single_queries(query_list):
queries = []
for query in query_list:
pieces = query.split(":")
# 0 is path
# 1 is operator
# 2 is value
path = pieces[0].split(",")
q = SingleAttrQuery(pieces[2], pieces[1], *path)
queries.append(q)
return queries
def construct_range_queries(rquery_list):
queries = []
for rquery in rquery_list:
pieces = rquery.split(":")
# 0 is path
# 1 is operator
# 2 is value
# 3 is operator
# 4 is value
path = pieces[0].split(",")
q = RangeQuery(pieces[2], pieces[1], pieces[4], pieces[3], *path)
queries.append(q)
return queries
def construct_queries(query_list, rquery_list):
all_queries = construct_single_queries(query_list)
rqueries = construct_range_queries(rquery_list)
all_queries.extend(rqueries)
return all_queries
if __name__ == "__main__":
parser = OptionParser()
parser.add_option("-P", "--port", dest="port", type="int",
help="rethinkdb port", default=30815)
parser.add_option("-q", "--query", dest="queries", action="append",
help="queries to run (path:operator:value) where " +
"path is comma separated", default=[])
parser.add_option("-r", "--rquery", dest="rqueries", action="append",
help="range queries to run " +
"(path:operator:value:operator:value)", default=[])
(options, args) = parser.parse_args()
if not options.queries and not options.rqueries:
print "You must specify a query"
sys.exit(1)
queries = construct_queries(options.queries, options.rqueries)
conn = r.connect("localhost", options.port, db="samplesdb")
search(conn, queries)
# sys.exit(0)
# range_query = RangeQuery(4, "LT", 5, "LT", "ignore")
# print range_query.match(4.5)
# print range_query.match(6)
# print range_query.match(3)
# print "======================"
# range_query = RangeQuery(4, "LTE", 6, "LT", "ignore")
# print range_query.match(4)
# print range_query.match(6)
# print range_query.match(7)
# print range_query.match(3)
# print range_query.match(5)
| |
#!/usr/bin/env python
# Copyright 2017 The Kubernetes 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.
# Need to figure out why this only fails on travis
# pylint: disable=bad-continuation
"""Runs kubernetes e2e test with specified config"""
import argparse
import os
import random
import signal
import string
import subprocess
import sys
import tempfile
ORIG_CWD = os.getcwd() # Checkout changes cwd
ROLE_CONFIG = """\
[profile jenkins-assumed-role]
role_arn = {role_arn}
source_profile = {source_profile}
"""
def test_infra(*paths):
"""Return path relative to root of test-infra repo."""
return os.path.join(ORIG_CWD, os.path.dirname(__file__), '..', *paths)
def check(*cmd):
"""Log and run the command, raising on errors."""
print >>sys.stderr, 'Run:', cmd
subprocess.check_call(cmd)
def setup_signal_handlers(container):
"""Establish a signal handler to kill 'container'."""
def sig_handler(_signo, _frame):
"""Stops container upon receive signal.SIGTERM and signal.SIGINT."""
print >>sys.stderr, 'signo = %s, frame = %s' % (_signo, _frame)
check('docker', 'stop', container)
signal.signal(signal.SIGTERM, sig_handler)
signal.signal(signal.SIGINT, sig_handler)
def kubekins(tag):
"""Return full path to kubekins-e2e:tag."""
return 'gcr.io/k8s-testimages/kubekins-e2e:%s' % tag
def main(args):
"""Set up env, start kops-runner, handle termination. """
# pylint: disable=too-many-locals,too-many-branches
job_name = (os.environ.get('JOB_NAME') or
os.environ.get('USER') or
'kops-aws-test')
build_number = (os.environ.get('BUILD_NUMBER') or
''.join(
random.choice(string.ascii_lowercase + string.digits)
for _ in range(8)))
container = '%s-%s' % (job_name, build_number)
# dockerized-e2e-runner goodies setup
workspace = os.environ.get('WORKSPACE', os.getcwd())
artifacts = '%s/_artifacts' % workspace
if not os.path.isdir(artifacts):
os.makedirs(artifacts)
for path in [args.aws_ssh, args.aws_pub, args.aws_cred]:
if not os.path.isfile(os.path.expandvars(path)):
raise IOError(path, os.path.expandvars(path))
try: # Pull a newer version if one exists
check('docker', 'pull', kubekins(args.tag))
except subprocess.CalledProcessError:
pass
print 'Starting %s...' % container
cmd = [
'docker', 'run', '--rm',
'--name=%s' % container,
'-v', '%s/_artifacts:/workspace/_artifacts' % workspace,
'-v', '/etc/localtime:/etc/localtime:ro',
'--entrypoint=/workspace/kops-e2e-runner.sh'
]
# Rules for env var priority here in docker:
# -e FOO=a -e FOO=b -> FOO=b
# --env-file FOO=a --env-file FOO=b -> FOO=b
# -e FOO=a --env-file FOO=b -> FOO=a(!!!!)
# --env-file FOO=a -e FOO=b -> FOO=b
#
# So if you overwrite FOO=c for a local run it will take precedence.
#
if args.env_file:
for env in args.env_file:
cmd.extend(['--env-file', test_infra(env)])
# Enforce to be always present
aws_ssh = '/workspace/.ssh/kube_aws_rsa'
aws_pub = '%s.pub' % aws_ssh
aws_cred = '/workspace/.aws/credentials'
aws_config = '/workspace/.aws/config'
cmd.extend([
'-v', '%s:%s:ro' % (args.aws_ssh, aws_ssh),
'-v', '%s:%s:ro' % (args.aws_pub, aws_pub),
'-v', '%s:%s:ro' % (args.aws_cred, aws_cred),
])
if args.service_account:
service = '/service-account.json'
cmd.extend(['-v', '%s:%s:ro' % (args.service_account, service),
'-e', 'GOOGLE_APPLICATION_CREDENTIALS=%s' % service])
profile = args.aws_profile
if args.aws_role_arn:
with tempfile.NamedTemporaryFile(
prefix='aws-config', delete=False) as cfg:
cfg.write(ROLE_CONFIG.format(
role_arn=args.aws_role_arn,
source_profile=profile))
cmd.extend([
'-v', '%s:%s:ro' % (cfg.name, aws_config),
'-e', 'AWS_SDK_LOAD_CONFIG=true',
])
profile = 'jenkins-assumed-role' # From ROLE_CONFIG
cmd.extend([
'-e', 'AWS_PROFILE=%s' % profile,
'-e', 'AWS_DEFAULT_PROFILE=%s' % profile,
])
zones = args.zones
if not zones:
zones = random.choice([
'us-west-1a',
'us-west-1c',
'us-west-2a',
'us-west-2b',
'us-east-1a',
'us-east-1d',
#'us-east-2a',
#'us-east-2b',
])
regions = ','.join([zone[:-1] for zone in zones.split(',')])
e2e_opt = ('--kops-cluster %s --kops-zones %s '
'--kops-state %s --kops-nodes=%s --kops-ssh-key=%s' %
(args.cluster, zones, args.state, args.nodes, aws_ssh))
if args.image:
e2e_opt += ' --kops-image=%s' % args.image
cmd.extend([
# Boilerplate envs
# Jenkins required variables
'-e', 'JOB_NAME=%s' % job_name,
'-e', 'BUILD_NUMBER=%s' % build_number,
# KOPS_REGIONS is needed by log dump hook in kops-e2e-runner.sh
'-e', 'KOPS_REGIONS=%s' % regions,
# E2E
'-e', 'E2E_UP=%s' % args.up,
'-e', 'E2E_TEST=%s' % args.test,
'-e', 'E2E_DOWN=%s' % args.down,
# Kops
'-e', 'E2E_OPT=%s' % e2e_opt,
])
# env blacklist.
# TODO(krzyzacy) change this to a whitelist
docker_env_ignore = [
'GOOGLE_APPLICATION_CREDENTIALS',
'GOROOT',
'HOME',
'PATH',
'PWD',
'WORKSPACE'
]
for key, value in os.environ.items():
if key not in docker_env_ignore:
cmd.extend(['-e', '%s=%s' % (key, value)])
cmd.append(kubekins(args.tag))
if args.kops_args:
cmd.append('--kops-args=%s' % args.kops_args)
setup_signal_handlers(container)
check(*cmd)
if __name__ == '__main__':
PARSER = argparse.ArgumentParser()
PARSER.add_argument(
'--env-file', action="append", help='Job specific environment file')
PARSER.add_argument(
'--aws-ssh',
default=os.environ.get('JENKINS_AWS_SSH_PRIVATE_KEY_FILE'),
help='Path to private aws ssh keys')
PARSER.add_argument(
'--aws-pub',
default=os.environ.get('JENKINS_AWS_SSH_PUBLIC_KEY_FILE'),
help='Path to pub aws ssh key')
PARSER.add_argument(
'--aws-cred',
default=os.environ.get('JENKINS_AWS_CREDENTIALS_FILE'),
help='Path to aws credential file')
PARSER.add_argument(
'--aws-profile',
default=(os.environ.get('AWS_PROFILE') or
os.environ.get('AWS_DEFAULT_PROFILE') or
'default'),
help='Profile within --aws-cred to use')
PARSER.add_argument(
'--aws-role-arn',
default=os.environ.get('KOPS_E2E_ROLE_ARN'),
help='If set, use the --aws-profile profile credentials '
'and run as --aws-role-arn')
PARSER.add_argument(
'--service-account',
default=os.environ.get('GOOGLE_APPLICATION_CREDENTIALS'),
help='Path to service-account.json')
# Assume we're upping, testing, and downing a cluster by default
PARSER.add_argument(
'--cluster', help='Name of the aws cluster (required)')
PARSER.add_argument(
'--down', default='true', help='If we need to set --down in e2e.go')
PARSER.add_argument(
'--nodes', default=4, type=int, help='Number of nodes to start')
PARSER.add_argument(
'--state', default='s3://k8s-kops-jenkins/',
help='Name of the aws state storage')
PARSER.add_argument(
'--tag', default='v20170314-bb0669b0',
help='Use a specific kubekins-e2e tag if set')
PARSER.add_argument(
'--test', default='true', help='If we need to set --test in e2e.go')
PARSER.add_argument(
'--up', default='true', help='If we need to set --up in e2e.go')
PARSER.add_argument(
'--zones', default=None,
help='Availability zones to start the cluster in. '
'Defaults to a random zone.')
PARSER.add_argument(
'--image', default='',
help='Image (AMI) for nodes to use. Defaults to kops default.')
PARSER.add_argument(
'--kops-args', default='',
help='Additional space-separated args to pass unvalidated to \'kops '
'create cluster\', e.g. \'--kops-args="--dns private --node-size '
't2.micro"\'')
ARGS = PARSER.parse_args()
if not ARGS.cluster:
raise ValueError('--cluster must be provided')
# If aws keys are missing, try to fetch from HOME dir
if not (ARGS.aws_ssh or ARGS.aws_pub or ARGS.aws_cred):
HOME = os.environ.get('HOME')
if not HOME:
raise ValueError('HOME dir not set!')
if not ARGS.aws_ssh:
ARGS.aws_ssh = '%s/.ssh/kube_aws_rsa' % HOME
print >>sys.stderr, 'AWS ssh key not found. Try to fetch from %s' % ARGS.aws_ssh
if not ARGS.aws_pub:
ARGS.aws_pub = '%s/.ssh/kube_aws_rsa.pub' % HOME
print >>sys.stderr, 'AWS pub key not found. Try to fetch from %s' % ARGS.aws_pub
if not ARGS.aws_cred:
ARGS.aws_cred = '%s/.aws/credentials' % HOME
print >>sys.stderr, 'AWS cred not found. Try to fetch from %s' % ARGS.aws_cred
main(ARGS)
| |
# Copyright (c) 2015-2019 Volodymyr Shymanskyy. See the file LICENSE for copying permission.
__version__ = "1.0.0"
import struct
import time
import sys
import os
try:
import machine
gettime = lambda: time.ticks_ms()
SOCK_TIMEOUT = 0
except ImportError:
const = lambda x: x
gettime = lambda: int(time.time() * 1000)
SOCK_TIMEOUT = 0.05
def dummy(*args):
pass
MSG_RSP = const(0)
MSG_LOGIN = const(2)
MSG_PING = const(6)
MSG_TWEET = const(12)
MSG_NOTIFY = const(14)
MSG_BRIDGE = const(15)
MSG_HW_SYNC = const(16)
MSG_INTERNAL = const(17)
MSG_PROPERTY = const(19)
MSG_HW = const(20)
MSG_HW_LOGIN = const(29)
MSG_EVENT_LOG = const(64)
MSG_REDIRECT = const(41) # TODO: not implemented
MSG_DBG_PRINT = const(55) # TODO: not implemented
STA_SUCCESS = const(200)
STA_INVALID_TOKEN = const(9)
DISCONNECTED = const(0)
CONNECTING = const(1)
CONNECTED = const(2)
print("""
___ __ __
/ _ )/ /_ _____ / /__
/ _ / / // / _ \\/ '_/
/____/_/\\_, /_//_/_/\\_\\
/___/ for Python v""" + __version__ + " (" + sys.platform + ")\n")
class EventEmitter:
def __init__(self):
self._cbks = {}
def on(self, evt, f=None):
if f:
self._cbks[evt] = f
else:
def D(f):
self._cbks[evt] = f
return f
return D
def emit(self, evt, *a, **kv):
if evt in self._cbks:
self._cbks[evt](*a, **kv)
class BlynkProtocol(EventEmitter):
def __init__(self, auth, tmpl_id=None, fw_ver=None, heartbeat=50, buffin=1024, log=None):
EventEmitter.__init__(self)
self.heartbeat = heartbeat*1000
self.buffin = buffin
self.log = log or dummy
self.auth = auth
self.tmpl_id = tmpl_id
self.fw_ver = fw_ver
self.state = DISCONNECTED
self.connect()
def virtual_write(self, pin, *val):
self._send(MSG_HW, 'vw', pin, *val)
def send_internal(self, pin, *val):
self._send(MSG_INTERNAL, pin, *val)
def set_property(self, pin, prop, *val):
self._send(MSG_PROPERTY, pin, prop, *val)
def sync_virtual(self, *pins):
self._send(MSG_HW_SYNC, 'vr', *pins)
def log_event(self, *val):
self._send(MSG_EVENT_LOG, *val)
def _send(self, cmd, *args, **kwargs):
if 'id' in kwargs:
id = kwargs.get('id')
else:
id = self.msg_id
self.msg_id += 1
if self.msg_id > 0xFFFF:
self.msg_id = 1
if cmd == MSG_RSP:
data = b''
dlen = args[0]
else:
data = ('\0'.join(map(str, args))).encode('utf8')
dlen = len(data)
self.log('<', cmd, id, '|', *args)
msg = struct.pack("!BHH", cmd, id, dlen) + data
self.lastSend = gettime()
self._write(msg)
def connect(self):
if self.state != DISCONNECTED: return
self.msg_id = 1
(self.lastRecv, self.lastSend, self.lastPing) = (gettime(), 0, 0)
self.bin = b""
self.state = CONNECTING
self._send(MSG_HW_LOGIN, self.auth)
def disconnect(self):
if self.state == DISCONNECTED: return
self.bin = b""
self.state = DISCONNECTED
self.emit('disconnected')
def process(self, data=None):
if not (self.state == CONNECTING or self.state == CONNECTED): return
now = gettime()
if now - self.lastRecv > self.heartbeat+(self.heartbeat//2):
return self.disconnect()
if (now - self.lastPing > self.heartbeat//10 and
(now - self.lastSend > self.heartbeat or
now - self.lastRecv > self.heartbeat)):
self._send(MSG_PING)
self.lastPing = now
if data != None and len(data):
self.bin += data
while True:
if len(self.bin) < 5:
break
cmd, i, dlen = struct.unpack("!BHH", self.bin[:5])
if i == 0: return self.disconnect()
self.lastRecv = now
if cmd == MSG_RSP:
self.bin = self.bin[5:]
self.log('>', cmd, i, '|', dlen)
if self.state == CONNECTING and i == 1:
if dlen == STA_SUCCESS:
self.state = CONNECTED
dt = now - self.lastSend
info = ['ver', __version__, 'h-beat', self.heartbeat//1000, 'buff-in', self.buffin, 'dev', sys.platform+'-py']
if self.tmpl_id:
info.extend(['tmpl', self.tmpl_id])
info.extend(['fw-type', self.tmpl_id])
if self.fw_ver:
info.extend(['fw', self.fw_ver])
self._send(MSG_INTERNAL, *info)
try:
self.emit('connected', ping=dt)
except TypeError:
self.emit('connected')
else:
if dlen == STA_INVALID_TOKEN:
self.emit("invalid_auth")
print("Invalid auth token")
return self.disconnect()
else:
if dlen >= self.buffin:
print("Cmd too big: ", dlen)
return self.disconnect()
if len(self.bin) < 5+dlen:
break
data = self.bin[5:5+dlen]
self.bin = self.bin[5+dlen:]
args = list(map(lambda x: x.decode('utf8'), data.split(b'\0')))
self.log('>', cmd, i, '|', ','.join(args))
if cmd == MSG_PING:
self._send(MSG_RSP, STA_SUCCESS, id=i)
elif cmd == MSG_HW or cmd == MSG_BRIDGE:
if args[0] == 'vw':
self.emit("V"+args[1], args[2:])
self.emit("V*", args[1], args[2:])
elif cmd == MSG_INTERNAL:
self.emit("internal:"+args[0], args[1:])
elif cmd == MSG_REDIRECT:
self.emit("redirect", args[0], int(args[1]))
else:
print("Unexpected command: ", cmd)
return self.disconnect()
import socket
class Blynk(BlynkProtocol):
def __init__(self, auth, **kwargs):
self.insecure = kwargs.pop('insecure', False)
self.server = kwargs.pop('server', 'blynk.cloud')
self.port = kwargs.pop('port', 80 if self.insecure else 443)
BlynkProtocol.__init__(self, auth, **kwargs)
self.on('redirect', self.redirect)
def redirect(self, server, port):
self.server = server
self.port = port
self.disconnect()
self.connect()
def connect(self):
print('Connecting to %s:%d...' % (self.server, self.port))
s = socket.socket()
s.connect(socket.getaddrinfo(self.server, self.port)[0][-1])
try:
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
except:
pass
if self.insecure:
self.conn = s
else:
try:
import ussl
ssl_context = ussl
except ImportError:
import ssl
ssl_context = ssl.create_default_context()
self.conn = ssl_context.wrap_socket(s, server_hostname=self.server)
try:
self.conn.settimeout(SOCK_TIMEOUT)
except:
s.settimeout(SOCK_TIMEOUT)
BlynkProtocol.connect(self)
def _write(self, data):
#print('<', data)
self.conn.write(data)
# TODO: handle disconnect
def run(self):
data = b''
try:
data = self.conn.read(self.buffin)
#print('>', data)
except KeyboardInterrupt:
raise
except: # TODO: handle disconnect
return
self.process(data)
| |
# 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.
# ==============================================================================
"""Functional tests for XLA TensorArray Ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.compiler.tests import xla_test
from tensorflow.python.compiler.xla import xla
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_util
from tensorflow.python.ops import gen_data_flow_ops
from tensorflow.python.ops import gradients_impl
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import tensor_array_grad # pylint: disable=unused-import
from tensorflow.python.ops import tensor_array_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
def _make_converter(dtype):
def _converter(x):
return np.asarray(x).astype(dtype.as_numpy_dtype)
return _converter
# This lets me define `fn` repeatedly to pass to xla.compile.
#
# pylint: disable=function-redefined
@test_util.with_control_flow_v2
class TensorArrayTest(xla_test.XLATestCase):
@test_util.disable_control_flow_v2("Tries to evaluate flow")
def testTensorArrayWriteRead(self):
with self.session() as session, self.test_scope():
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, tensor_array_name="foo", size=3)
w0 = ta.write(0, [[4.0, 5.0]])
w1 = w0.write(1, [[1.0, 3.0]])
w2 = w1.write(2, [[7.0, -8.5]])
r0 = w2.read(0)
r1 = w2.read(1)
r2 = w2.read(2)
flow = w2.flow
return [r0, r1, r2, flow]
d0, d1, d2, flow_val = self.evaluate(xla.compile(fn))
self.assertAllEqual([[4.0, 5.0]], d0)
self.assertAllEqual([[1.0, 3.0]], d1)
self.assertAllEqual([[7.0, -8.5]], d2)
self.assertAllEqual([], flow_val.shape)
def _testTensorArrayWritePack(self, tf_dtype):
with self.session(), self.test_scope():
convert = _make_converter(tf_dtype)
def fn():
ta = tensor_array_ops.TensorArray(
dtype=tf_dtype, tensor_array_name="foo", size=3)
w0 = ta.write(0, convert([[4.0, 5.0]]))
w1 = w0.write(1, convert([[6.0, 7.0]]))
w2 = w1.write(2, convert([[8.0, 9.0]]))
return w2.stack()
self.assertAllEqual(
convert([[[4.0, 5.0]], [[6.0, 7.0]], [[8.0, 9.0]]]),
self.evaluate(xla.compile(fn)[0]))
def testTensorArrayWritePack(self):
for dtype in self.numeric_tf_types:
self._testTensorArrayWritePack(dtype)
def testEmptyTensorArrayPack(self):
with self.session(), self.test_scope():
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, tensor_array_name="foo", size=3)
empty_element = np.zeros((0, 1), dtype=np.float32)
w0 = ta.write(0, empty_element)
w1 = w0.write(1, empty_element)
w2 = w1.write(2, empty_element)
return w2.stack()
self.assertAllEqual([3, 0, 1], self.evaluate(xla.compile(fn)[0]).shape)
def _testTensorArrayWriteConcat(self, tf_dtype):
with self.session(), self.test_scope():
convert = _make_converter(tf_dtype)
def fn():
ta = tensor_array_ops.TensorArray(
dtype=tf_dtype, tensor_array_name="foo", size=3)
w0 = ta.write(0, convert([[4.0, 5.0], [104.0, 105.0]]))
w1 = w0.write(1, convert([[6.0, 7.0], [106.0, 107.0]]))
w2 = w1.write(2, convert([[8.0, 9.0], [204.0, 205.0]]))
return w2.concat()
self.assertAllEqual(
convert([[4.0, 5.0], [104.0, 105.0], [6.0, 7.0], [106.0, 107.0],
[8.0, 9.0], [204.0, 205.0]]),
self.evaluate(xla.compile(fn)[0]))
@test_util.disable_control_flow_v2("b/122315751 (concat)")
def testTensorArrayWriteConcat(self):
for dtype in self.numeric_tf_types:
self._testTensorArrayWriteConcat(dtype)
def _testTensorArrayUnpackRead(self, tf_dtype):
with self.session() as session, self.test_scope():
convert = _make_converter(tf_dtype)
def fn():
ta = tensor_array_ops.TensorArray(
dtype=tf_dtype, tensor_array_name="foo", size=3)
# Unpack a vector into scalars
w0 = ta.unstack(convert([1.0, 2.0, 3.0]))
r0 = w0.read(0)
r1 = w0.read(1)
r2 = w0.read(2)
return [r0, r1, r2]
d0, d1, d2 = self.evaluate(xla.compile(fn))
self.assertAllEqual(convert(1.0), d0)
self.assertAllEqual(convert(2.0), d1)
self.assertAllEqual(convert(3.0), d2)
def fn():
ta = tensor_array_ops.TensorArray(
dtype=tf_dtype, tensor_array_name="foo", size=3)
# Unpack a matrix into vectors.
w1 = ta.unstack(convert([[1.0, 1.1], [2.0, 2.1], [3.0, 3.1]]))
r0 = w1.read(0)
r1 = w1.read(1)
r2 = w1.read(2)
return [r0, r1, r2]
d0, d1, d2 = self.evaluate(xla.compile(fn))
self.assertAllEqual(convert([1.0, 1.1]), d0)
self.assertAllEqual(convert([2.0, 2.1]), d1)
self.assertAllEqual(convert([3.0, 3.1]), d2)
def fn():
# Reset ta because we're going to change the shape, else shape
# inference will throw an error.
ta = tensor_array_ops.TensorArray(
dtype=tf_dtype, tensor_array_name="foo", size=3)
# Try unpacking an empty matrix, which should not cause an error.
w2 = ta.unstack(convert([[], [], []]))
r0 = w2.read(0)
r1 = w2.read(1)
r2 = w2.read(2)
return [r0, r1, r2]
d0, d1, d2 = self.evaluate(xla.compile(fn))
self.assertAllEqual(convert([]), d0)
self.assertAllEqual(convert([]), d1)
self.assertAllEqual(convert([]), d2)
def _testTensorArrayUnpackReadMaybeLegacy(self):
for dtype in self.numeric_tf_types:
self._testTensorArrayUnpackRead(dtype)
def testTensorArrayUnpackRead(self):
self._testTensorArrayUnpackReadMaybeLegacy()
def _testTensorArraySplitRead(self, tf_dtype):
with self.session() as session, self.test_scope():
convert = _make_converter(tf_dtype)
def fn():
ta = tensor_array_ops.TensorArray(
dtype=tf_dtype, tensor_array_name="foo", size=3)
# Split an empty vector.
lengths = constant_op.constant([0, 0, 0])
w0 = ta.split(convert([]), lengths=lengths)
r0 = w0.read(0)
r1 = w0.read(1)
r2 = w0.read(2)
return [r0, r1, r2]
d0, d1, d2 = self.evaluate(xla.compile(fn))
self.assertAllEqual(convert([]), d0)
self.assertAllEqual(convert([]), d1)
self.assertAllEqual(convert([]), d2)
def fn():
# Split a vector.
ta = tensor_array_ops.TensorArray(
dtype=tf_dtype, tensor_array_name="foo", size=3)
lengths = constant_op.constant([1, 1, 1])
w0 = ta.split(convert([1.0, 2.0, 3.0]), lengths=lengths)
r0 = w0.read(0)
r1 = w0.read(1)
r2 = w0.read(2)
return [r0, r1, r2]
d0, d1, d2 = self.evaluate(xla.compile(fn))
self.assertAllEqual(convert([1.0]), d0)
self.assertAllEqual(convert([2.0]), d1)
self.assertAllEqual(convert([3.0]), d2)
def fn():
# Split a matrix.
ta = tensor_array_ops.TensorArray(
dtype=tf_dtype, tensor_array_name="foo", size=3)
lengths = constant_op.constant([1, 1, 1])
w0 = ta.split(
convert([[1.0, 101.0], [2.0, 201.0], [3.0, 301.0]]),
lengths=lengths)
r0 = w0.read(0)
r1 = w0.read(1)
r2 = w0.read(2)
return [r0, r1, r2]
d0, d1, d2 = self.evaluate(xla.compile(fn))
self.assertAllEqual(convert([[1.0, 101.0]]), d0)
self.assertAllEqual(convert([[2.0, 201.0]]), d1)
self.assertAllEqual(convert([[3.0, 301.0]]), d2)
@test_util.disable_control_flow_v2("b/122315872 (split)")
def testTensorArraySplitRead(self):
for dtype in self.numeric_tf_types:
self._testTensorArraySplitRead(dtype)
@test_util.disable_control_flow_v2("TensorArray.grad is not supported in v2")
def testTensorGradArrayWriteRead(self):
with self.session() as session, self.test_scope():
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, tensor_array_name="foo", size=3)
w0 = ta.write(0, [[4.0]])
w1 = w0.write(1, [[1.0]])
w2 = w1.write(2, [[-3.0]])
g_ta = w2.grad("grad")
g_w0 = g_ta.write(0, [[5.0]])
g_w1 = g_w0.write(1, [[2.0]])
g_w2 = g_w1.write(2, [[-2.0]])
r0 = w2.read(0)
r1 = w2.read(1)
r2 = w2.read(2)
g_r0 = g_w2.read(0)
g_r1 = g_w2.read(1)
g_r2 = g_w2.read(2)
return [r0, r1, r2, g_r0, g_r1, g_r2]
d0, d1, d2, g_d0, g_d1, g_d2 = self.evaluate(xla.compile(fn))
self.assertAllEqual([[4.0]], d0)
self.assertAllEqual([[1.0]], d1)
self.assertAllEqual([[-3.0]], d2)
self.assertAllEqual([[5.0]], g_d0)
self.assertAllEqual([[2.0]], g_d1)
self.assertAllEqual([[-2.0]], g_d2)
@test_util.disable_control_flow_v2("TensorArray.grad is not supported in v2")
def testTensorGradArrayDynamicWriteRead(self):
with self.session() as session, self.test_scope():
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, tensor_array_name="foo", size=3)
w0 = ta.write(0, [[4.0]])
w1 = w0.write(1, [[1.0]])
w2 = w1.write(2, [[-3.0]])
g_ta = w2.grad("grad") # Get gradient array here so we know the shape
s = w2.size()
g_s = g_ta.size()
g_w0 = g_ta.write(0, [[5.0]])
g_w1 = g_w0.write(1, [[2.0]])
g_w2 = g_w1.write(2, [[-2.0]])
r0 = w2.read(0)
r1 = w2.read(1)
r2 = w2.read(2)
g_r0 = g_w2.read(0)
g_r1 = g_w2.read(1)
g_r2 = g_w2.read(2)
return [r0, r1, r2, g_r0, g_r1, g_r2, s, g_s]
d0, d1, d2, g_d0, g_d1, g_d2, vs, g_vs = self.evaluate(xla.compile(fn))
self.assertAllEqual([[4.0]], d0)
self.assertAllEqual([[1.0]], d1)
self.assertAllEqual([[-3.0]], d2)
self.assertAllEqual([[5.0]], g_d0)
self.assertAllEqual([[2.0]], g_d1)
self.assertAllEqual([[-2.0]], g_d2)
self.assertAllEqual(3, vs)
self.assertAllEqual(3, g_vs)
@test_util.disable_control_flow_v2("TensorArray.grad is not supported in v2")
def testTensorGradAccessTwiceReceiveSameObject(self):
with self.session() as session, self.test_scope():
ta_out = {}
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32,
tensor_array_name="foo",
size=3,
element_shape=[1, 2])
g_ta_0 = ta.grad("grad")
g_ta_1 = ta.grad("grad")
ta_out[0] = g_ta_0.handle
ta_out[1] = g_ta_1.handle
with ops.control_dependencies([g_ta_0.write(0, [[4.0, 5.0]]).flow]):
# Write with one gradient handle, read with another copy of it
r1_0 = g_ta_1.read(0)
with ops.control_dependencies([g_ta_0.handle.op, g_ta_1.handle.op]):
return [r1_0]
[d_r1_0] = self.evaluate(xla.compile(fn))
self.assertAllEqual([[4.0, 5.0]], d_r1_0)
# Can't assert this because adding a side output like we have here fails
# as follows:
#
# ValueError: Operation u'TensorArrayGrad/TensorArrayGradV3' has been
# marked as not fetchable.
#
# On the other hand, legitimately returning the handle from the
# xla.compile function fails because we don't support DT_RESOURCE outputs
# from XLA clusters.
#
# self.assertAllEqual(ta_out[0], ta_out[1])
@test_util.disable_control_flow_v2("b/124334470")
def testTensorArrayWriteWrongIndexOrDataTypeFails(self):
with self.session(), self.test_scope():
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, tensor_array_name="foo", size=3)
return ta.write(-1, constant_op.constant(7)).flow
# Test writing the wrong datatype.
# TODO(b/129870929): Remove InvalidArgumentError/second regexp after all
# callers provide proper init dtype.
with self.assertRaisesRegexp(
(ValueError, errors.InvalidArgumentError),
r"("
r"conversion requested dtype float32 for Tensor with dtype int32"
r"|"
r"TensorArray dtype is float but op has dtype int32"
r")"):
xla.compile(fn)[0].eval()
@test_util.disable_control_flow_v2("b/124334096 verify dtype")
def testTensorArrayReadWrongIndexOrDataTypeFails(self):
# Find two different floating point types, create an array of
# the first type, but try to read the other type.
if len(self.float_types) > 1:
dtype1, dtype2 = list(self.float_types)[:2]
with self.session(), self.test_scope():
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtype1, tensor_array_name="foo", size=3)
w0 = ta.write(0, math_ops.cast([[4.0, 5.0]], dtype1))
# Test reading wrong datatype.
return gen_data_flow_ops.tensor_array_read_v3(
handle=w0.handle, index=0, dtype=dtype2, flow_in=w0.flow)
with self.assertRaisesOpError("TensorArray dtype is "):
self.evaluate(xla.compile(fn))
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtype1, tensor_array_name="foo", size=3)
w0 = ta.write(0, math_ops.cast([[4.0, 5.0]], dtype1))
# Test reading from a different index than the one we wrote to
with ops.control_dependencies([w0.read(1)]):
return 1.0
xla.compile(fn)[0].eval()
@test_util.disable_control_flow_v2("b/122315872 (split)")
def testTensorArraySplitIncompatibleShapesFails(self):
with self.session(), self.test_scope():
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32,
tensor_array_name="foo",
size=3,
infer_shape=False)
return ta.split([1.0, 2.0, 3.0], 1).flow
with self.assertRaisesWithPredicateMatch(
ValueError, r"Shape must be rank 1 but is rank 0"):
xla.compile(fn)[0].eval()
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32,
tensor_array_name="foo",
size=3,
infer_shape=False)
return ta.split([1.0, 2.0, 3.0], [1, 2, 3]).flow
with self.assertRaisesOpError(
r"lengths must be equal: 1 vs. 2"):
xla.compile(fn)[0].eval()
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32,
tensor_array_name="foo",
size=3,
infer_shape=False)
return ta.split(1.0, [1]).flow
with self.assertRaisesOpError(
r"value must have rank >= 1"):
xla.compile(fn)[0].eval()
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32,
tensor_array_name="foo",
size=2,
infer_shape=False)
return ta.split([1.0], [1]).flow
with self.assertRaisesOpError(
r"TensorArray's size is not equal to the size of lengths "
r"\(1 vs. 2\)"):
xla.compile(fn)[0].eval()
def _testTensorArrayWriteGradientAddMultipleAdds(self, dtype):
with self.session(), self.test_scope():
c = lambda x: np.asarray(x, dtype=dtype.as_numpy_dtype)
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtype, tensor_array_name="foo", size=3, infer_shape=False)
w0 = ta.write(2, c(3.0))
w1 = w0.write(2, c(4.0))
ta_grad = w1.grad("grad")
w0_grad = ta_grad.write(2, c(3.0))
w1_grad = w0_grad.write(2, c(4.0))
w2_grad = w1_grad.write(2, c(5.0))
return w2_grad.read(2)
# Assert that aggregation works correctly
self.assertAllEqual(c(12.00), xla.compile(fn)[0].eval())
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtype, tensor_array_name="foo", size=3, infer_shape=False)
w0 = ta.write(2, c(3.0))
w1 = w0.write(2, c(4.0))
ta_grad = w1.grad("grad")
# Using differing shapes causes an exception
wb0_grad = ta_grad.write(1, c(1.0))
wb1_grad = wb0_grad.write(1, c([1.0]))
return wb1_grad.flow
with self.assertRaisesOpError(
r"Mismatched TensorArray sizes"):
xla.compile(fn)[0].eval()
@test_util.disable_control_flow_v2("TensorArray.grad is not supported in v2")
def testTensorArrayWriteGradientAddMultipleAdds(self):
for dtype in self.numeric_tf_types:
self._testTensorArrayWriteGradientAddMultipleAdds(dtype)
def testMultiTensorArray(self):
with self.session(), self.test_scope():
def fn():
h1 = tensor_array_ops.TensorArray(
size=1, dtype=dtypes.float32, tensor_array_name="foo")
w1 = h1.write(0, 4.0)
r1 = w1.read(0)
h2 = tensor_array_ops.TensorArray(
size=1, dtype=dtypes.float32, tensor_array_name="bar")
w2 = h2.write(0, 5.0)
r2 = w2.read(0)
return r1 + r2
self.assertAllClose(9.0, self.evaluate(xla.compile(fn)[0]))
def _testTensorArrayGradientWriteReadType(self, dtype):
with self.session() as session, self.test_scope():
c = lambda x: np.array(x, dtype=dtype)
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.as_dtype(dtype),
tensor_array_name="foo",
size=3,
infer_shape=False)
value_0 = constant_op.constant(c([[4.0, 5.0]]))
value_1 = constant_op.constant(c([[3.0, 3.5]]))
w0 = ta.write(0, value_0)
w1 = w0.write(1, value_1)
r0 = w1.read(0)
r1 = w1.read(1)
r0_2 = w1.read(0)
# Test individual components' gradients
grad_just_r0 = gradients_impl.gradients(
ys=[r0], xs=[value_0], grad_ys=[c([[2.0, 3.0]])])
grad_r0_r0_2 = gradients_impl.gradients(
ys=[r0, r0_2],
xs=[value_0],
grad_ys=[c([[2.0, 3.0]]), c([[1.0, -1.0]])])
grad_just_r1 = gradients_impl.gradients(
ys=[r1], xs=[value_1], grad_ys=[c([[-2.0, -4.0]])])
# Test combined gradients
grad = gradients_impl.gradients(
ys=[r0, r0_2, r1],
xs=[value_0, value_1],
grad_ys=[c([[2.0, 3.0]]),
c([[1.0, -1.0]]),
c([[-2.0, -10.0]])])
return [grad_just_r0, grad_r0_r0_2, grad_just_r1, grad]
[grad_just_r0_vals, grad_r0_r0_2_vals, grad_just_r1_vals,
grad_vals] = self.evaluate(xla.compile(fn))
self.assertAllEqual(c([[2.0, 3.0]]), grad_just_r0_vals[0])
self.assertAllEqual(c([[3.0, 2.0]]), grad_r0_r0_2_vals[0])
self.assertAllEqual(c([[-2.0, -4.0]]), grad_just_r1_vals[0])
self.assertEqual(len(grad_vals), 2)
self.assertAllEqual(c([[3.0, 2.0]]), grad_vals[0])
self.assertAllEqual(c([[-2.0, -10.0]]), grad_vals[1])
def testTensorArrayGradientWriteRead(self):
for dtype in self.float_types:
self._testTensorArrayGradientWriteReadType(dtype)
for dtype in self.complex_types:
self._testTensorArrayGradientWriteReadType(dtype)
def _testTensorArrayGradientWritePackConcatAndRead(self):
with self.session() as sess, self.test_scope():
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32,
tensor_array_name="foo",
size=2,
clear_after_read=False)
value_0 = constant_op.constant([-1.0, 1.0])
value_1 = constant_op.constant([-10.0, 10.0])
w0 = ta.write(0, value_0)
w1 = w0.write(1, value_1)
p0 = w1.stack()
r0 = w1.read(0)
s0 = w1.concat()
# Test gradient accumulation between read(0), pack(), and concat().
with ops.control_dependencies([p0, r0, s0]):
return gradients_impl.gradients(
ys=[p0, r0, s0],
xs=[value_0, value_1],
grad_ys=[
[[2.0, 3.0], [4.0, 5.0]], # stack gradient
[-0.5, 1.5], # read(0) gradient
[20.0, 30.0, 40.0, 50.0], # concat gradient
])
grad_vals = self.evaluate(xla.compile(fn)) # 2 + 2 entries
self.assertAllClose([2.0 - 0.5 + 20.0, 3.0 + 1.5 + 30.0], grad_vals[0])
self.assertAllEqual([4.0 + 40.0, 5.0 + 50.0], grad_vals[1])
@test_util.disable_control_flow_v2("b/122315751 (concat)")
def testTensorArrayGradientWritePackConcatAndRead(self):
self._testTensorArrayGradientWritePackConcatAndRead()
def testTensorArrayReadTwice(self):
with self.session(), self.test_scope():
def fn():
value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]])
ta_readtwice = tensor_array_ops.TensorArray(
dtype=dtypes.float32,
tensor_array_name="foo",
size=2,
clear_after_read=False)
w_readtwice = ta_readtwice.unstack(value)
r0_readtwice = w_readtwice.read(0)
with ops.control_dependencies([r0_readtwice]):
r1_readtwice = w_readtwice.read(0)
return [r0_readtwice, r1_readtwice]
self.assertAllEqual([1.0, -1.0], self.evaluate(xla.compile(fn))[0])
def _testTensorArrayGradientUnpackRead(self):
with self.session() as session, self.test_scope():
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32,
tensor_array_name="foo",
size=2,
clear_after_read=False)
value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]])
w = ta.unstack(value)
r0 = w.read(0)
r0_1 = w.read(0)
r1 = w.read(1)
# Test combined gradients + aggregation of read(0).
return gradients_impl.gradients(
ys=[r0, r0_1, r1],
xs=[value],
grad_ys=[[2.0, 3.0], [-1.5, 1.5], [4.0, 5.0]])
grad_vals = self.evaluate(xla.compile(fn))
self.assertEqual(len(grad_vals), 1)
self.assertAllEqual([[2.0 - 1.5, 3.0 + 1.5], [4.0, 5.0]], grad_vals[0])
def testTensorArrayGradientUnpackRead(self):
self._testTensorArrayGradientUnpackRead()
@test_util.disable_control_flow_v2("b/122315751(concat), b/122315872(split)")
def testTensorArrayGradientSplitConcat(self):
with self.session() as session, self.test_scope():
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, tensor_array_name="foo", size=2)
value = constant_op.constant([[1.0, -1.0], [10.0, -10.0],
[100.0, -100.0], [1000.0, -1000.0]])
w = ta.split(value, [2, 2])
r = w.concat()
# Test combined gradients
return gradients_impl.gradients(
ys=[r],
xs=[value],
grad_ys=[[[2.0, -2.0], [20.0, -20.0], [200.0, -200.0],
[2000.0, -2000.0]]])
grad_vals = self.evaluate(xla.compile(fn))
self.assertEqual(len(grad_vals), 1)
self.assertAllEqual([[2.0, -2.0], [20.0, -20.0], [200.0, -200.0],
[2000.0, -2000.0]],
grad_vals[0])
def testCloseTensorArray(self):
with self.session() as session, self.test_scope():
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, tensor_array_name="foo", size=3)
with ops.control_dependencies([ta.close()]):
return 1.0
self.evaluate(xla.compile(fn)[0])
def testSizeTensorArray(self):
with self.session(), self.test_scope():
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, tensor_array_name="foo", size=3)
return ta.size()
self.assertAllEqual(3, self.evaluate(xla.compile(fn))[0])
def testWriteCloseTensorArray(self):
with self.session(), self.test_scope():
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32,
tensor_array_name="foo",
size=3,
infer_shape=False)
w0 = ta.write(0, [[4.0, 5.0]])
w1 = w0.write(1, [[3.0, 1.0]])
with ops.control_dependencies([w1.close()]):
return 1.0
self.evaluate(xla.compile(fn))
# TODO(phawkins): implement while loops.
# def _testWhileLoopWritePackGradients(self, dynamic_size, dtype):
# np_dtype = dtype.as_numpy_dtype
# with self.session() as session, self.test_scope():
# v0 = array_ops.identity(np.arange(3 * 5, dtype=np_dtype).reshape(3, 5))
# var = variables.Variable(np.arange(100, 105, dtype=np_dtype))
# state0 = array_ops.identity(np.array([1] * 5, dtype=np_dtype))
# ta = tensor_array_ops.TensorArray(
# dtype=dtype,
# tensor_array_name="foo",
# size=0 if dynamic_size else 3,
# dynamic_size=dynamic_size)
# time_0 = array_ops.identity(0)
# def body(time, ta_t, state):
# sliced = array_ops.slice(
# v0, begin=array_ops.stack([time, 0]), size=[1, -1])
# sliced = array_ops.squeeze(sliced)
# out = sliced + var + state
# state += sliced
# ta_t = ta_t.write(time, out)
# return (time + 1, ta_t, state)
# (unused_0, h_final, unused_2) = control_flow_ops.while_loop(
# cond=lambda time, unused_1, unused_2: time < 3,
# body=body,
# loop_vars=(time_0, ta, state0),
# shape_invariants=(time_0.get_shape(), tensor_shape.unknown_shape(),
# tensor_shape.unknown_shape()),
# parallel_iterations=3)
# vout = h_final.stack()
# grad_val = -np.arange(3 * 5, dtype=np_dtype).reshape(3, 5)
# v0_grad = gradients_impl.gradients([vout], [v0], [grad_val])[0]
# state0_grad = gradients_impl.gradients([vout], [state0], [grad_val])[0]
# var_grad = gradients_impl.gradients([vout], [var], [grad_val])[0]
# variables.global_variables_initializer().run()
# state0_t, var_t, v0_t, vout_t, v0_grad_t, var_grad_t, state0_grad_t = (
# self.evaluate([state0, var, v0, vout, v0_grad, var_grad, state0_grad])
# )
# just_v0_grad_t, = self.evaluate([v0_grad])
# # state = [ state0 | state0 + v0[0] | state0 + v0[0] + v0[1] ]
# # vout = [ v0[0] + var + state[0] |
# # v0[1] + var + state[1] |
# # v0[2] + var + state[2] ]
# # = [ v0[0] + var + state0 |
# # v0[1] + var + state0 + v0[0] |
# # v0[2] + var + state0 + v0[0] + v0[1] ]
# #
# # d(vout[0])/d(v0) = [1 | 0 | 0 ]
# # d(vout[1])/d(v0) = [1 | 1 | 0 ]
# # d(vout[2])/d(v0) = [1 | 1 | 1 ]
# # d(vout)/d(var) = [1 | 1 | 1]
# # d(vout)/d(state0) = [ 1 | 1 | 1 ]
# state_per_time = np.array(
# [state0_t, state0_t + v0_t[0, :],
# state0_t + v0_t[0, :] + v0_t[1, :]])
# # Compare forward prop
# self.assertAllClose(v0_t + var_t + state_per_time, vout_t)
# # Compare backward prop
# expected_v0_grad_t = np.array([
# grad_val[0, :] + grad_val[1, :] + grad_val[2, :],
# grad_val[1, :] + grad_val[2, :], grad_val[2, :]
# ])
# self.assertAllEqual(expected_v0_grad_t, v0_grad_t)
# self.assertAllEqual(expected_v0_grad_t, just_v0_grad_t)
# self.assertAllClose(grad_val.sum(axis=0), var_grad_t)
# self.assertAllClose(grad_val.sum(axis=0), state0_grad_t)
# def testWhileLoopWritePackGradients(self):
# self._testWhileLoopWritePackGradients(
# dynamic_size=False, dtype=dtypes.float32)
# # TODO(ebrevdo): re-enable when While supports non-float32 gradients.
# # self._testWhileLoopWritePackGradients(
# # dynamic_size=False, dtype=tf.int64)
# def testWhileLoopDynamicWritePackGradients(self):
# self._testWhileLoopWritePackGradients(
# dynamic_size=True, dtype=dtypes.float32)
# def testGradSerialTwoLoops(self):
# with self.session(), self.test_scope():
# num_steps = 100
# acc = tensor_array_ops.TensorArray(
# dtype=dtypes.float32,
# size=num_steps,
# clear_after_read=False,
# element_shape=tensor_shape.scalar())
# i = constant_op.constant(0, name="i")
# x = constant_op.constant(2.0, name="x")
# c = lambda i, acc: i < 5
# def b(i, acc):
# x1 = control_flow_ops.cond(
# math_ops.equal(i, 0), lambda: x,
# lambda: math_ops.multiply(acc.read(i - 1), 2.0))
# return i + 1, acc.write(i, x1)
# i1, acc1 = control_flow_ops.while_loop(c, b, [i, acc])
# z = constant_op.constant(0.0)
# def fn(i, acc):
# return i + 1, acc.write(i, z)
# _, acc2 = control_flow_ops.while_loop(lambda i, acc: i < num_steps, fn,
# [i1, acc1])
# r = acc2.stack()
# grad = gradients_impl.gradients(r, [x])[0]
# self.assertAllClose(31.0, self.evaluate(grad))
def testSumOfTwoReadVariablesWithoutRepeatGrad(self):
with self.session() as session, self.test_scope():
g0 = -(np.arange(3 * 5, dtype=np.float32).reshape(3, 5) + 1)
def fn():
a = array_ops.identity(
np.arange(3 * 5, dtype=np.float32).reshape(3, 5) + 1)
b = array_ops.identity(
np.arange(3 * 5, dtype=np.float32).reshape(3, 5) + 1 + 3 * 5)
ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2)
ta = ta.write(0, a, name="write_a")
ta = ta.write(1, b, name="write_b")
c = (
ta.read(0, name="read_a_0") + # a + b
ta.read(1, name="read_b_0"))
grad_a = gradients_impl.gradients([c], [a], [g0])[0] # d(a+b)/da = 1
grad_b = gradients_impl.gradients([c], [b], [g0])[0] # d(a+b)/db = 1
return [grad_a, grad_b]
grad_a, grad_b = xla.compile(fn)
# Test gradients calculated individually
grad_a_t, = self.evaluate([grad_a])
self.assertAllEqual(grad_a_t, g0)
grad_b_t, = self.evaluate([grad_b])
self.assertAllEqual(grad_b_t, g0)
# Test gradients calculated jointly.
joint_grad_a_t, joint_grad_b_t = self.evaluate([grad_a, grad_b])
self.assertAllEqual(joint_grad_a_t, g0)
self.assertAllEqual(joint_grad_b_t, g0)
def testWriteShape(self):
with self.session(), self.test_scope():
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, tensor_array_name="foo", size=3)
c0 = constant_op.constant([4.0, 5.0])
w0 = ta.write(0, c0)
r0 = w0.read(0)
return [c0, r0]
c0, r0 = xla.compile(fn)
self.assertAllEqual(c0.get_shape(), r0.get_shape())
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, tensor_array_name="foo", size=3)
c1 = constant_op.constant([6.0, 7.0])
w0 = ta.write(0, c0)
w1 = w0.write(1, c1)
r0 = w1.read(0)
r1 = w1.read(1)
return [r0, c1, r1]
[r0, c1, r1] = xla.compile(fn)
self.assertAllEqual(c0.get_shape(), r0.get_shape())
self.assertAllEqual(c1.get_shape(), r1.get_shape())
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, tensor_array_name="foo", size=3)
w0 = ta.write(0, c0)
c2 = constant_op.constant([4.0, 5.0, 6.0])
return w0.write(0, c2).flow
with self.assertRaises(ValueError):
self.evaluate(xla.compile(fn))
def _testGradientWhenNotAllComponentsRead(self):
with self.session() as session, self.test_scope():
def fn():
ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2)
x = constant_op.constant([2.0, 3.0])
w = ta.unstack(x)
r0 = w.read(0)
# Calculate (dr0/dx0, dr0/dx1). since r0 = x0, gradients are (1, 0).
return gradients_impl.gradients(ys=[r0], xs=[x], grad_ys=[1.0])
grad_r0_vals = self.evaluate(xla.compile(fn))[0]
self.assertAllEqual(grad_r0_vals, [1.0, 0.0])
def testGradientWhenNotAllComponentsRead(self):
self._testGradientWhenNotAllComponentsRead()
def _testTensorArrayEvalEmpty(self):
with self.session(), self.test_scope():
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, size=0, infer_shape=False)
return ta.stack()
with self.assertRaisesWithPredicateMatch(
errors.InvalidArgumentError, "Uninitialized TensorArray passed to "
"TensorArrayStack/TensorArrayGatherV3"):
xla.compile(fn)[0].eval()
@test_util.disable_control_flow_v2("b/124335246")
def testTensorArrayEvalEmpty(self):
self._testTensorArrayEvalEmpty()
def _testTensorArrayEvalEmptyWithDefault(self):
with self.session(), self.test_scope():
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, size=0, infer_shape=True)
size = ta.size()
ta = ta.unstack(array_ops.zeros([0, 3, 5]))
return [size, ta.stack()]
[size, stack] = self.evaluate(xla.compile(fn))
self.assertEqual(0, size)
self.assertAllEqual([0, 3, 5], stack.shape)
# Concatenating zero tensors along their first dimension gives a
# first dimension of zero
if not control_flow_util.ENABLE_CONTROL_FLOW_V2:
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, size=0, infer_shape=True)
ta = ta.unstack(array_ops.zeros([0, 3, 5]))
return ta.concat()
# TODO(b/122315751): Enable this.
self.assertAllEqual([0, 5], self.evaluate(xla.compile(fn))[0].shape)
def testTensorArrayEvalEmptyWithDefault(self):
self._testTensorArrayEvalEmptyWithDefault()
def _testTensorArrayScatterRead(self, tf_dtype):
with self.session() as session, self.test_scope():
convert = _make_converter(tf_dtype)
id0 = array_ops.placeholder(dtypes.int32)
id1 = array_ops.placeholder(dtypes.int32)
def fn():
ta = tensor_array_ops.TensorArray(
dtype=tf_dtype, tensor_array_name="foo", size=10)
indices = constant_op.constant([1, 8])
value = constant_op.constant(convert([[1.0, -1.0], [10.0, -10.0]]))
w = ta.scatter(indices, value)
r0 = w.read(id0)
r1 = w.read(id1)
return [r0, r1]
# Test aggregation of read
read_vals = session.run(xla.compile(fn), feed_dict={id0: 1, id1: 8})
self.assertAllEqual(convert([1.0, -1.0]), read_vals[0])
self.assertAllEqual(convert([10.0, -10.0]), read_vals[1])
@test_util.disable_control_flow_v2("b/122315734 (scatter)")
def testTensorArrayScatterRead(self):
for dtype in self.numeric_tf_types:
self._testTensorArrayScatterRead(dtype)
self._testTensorArrayScatterRead(dtypes.bool)
@test_util.disable_control_flow_v2("b/122315734 (scatter)")
def testTensorArrayScatterReadAndGradients(self):
with self.session() as session, self.test_scope():
id0 = array_ops.placeholder(dtypes.int32)
id1 = array_ops.placeholder(dtypes.int32)
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, tensor_array_name="foo", size=10)
indices = constant_op.constant([1, 8])
value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]])
w = ta.scatter(indices, value)
r0 = w.read(id0)
r1 = w.read(id1)
# Test combined gradients + aggregation of read(0).
grad = gradients_impl.gradients(
ys=[r0, r1], xs=[value], grad_ys=[[2.0, 3.0], [4.0, 5.0]])
return [[r0, r1], grad]
read_vals, grad_vals = session.run(
xla.compile(fn), feed_dict={
id0: 1,
id1: 8
})
self.assertEqual(len(read_vals), 2)
self.assertEqual(len(grad_vals), 1)
self.assertAllEqual([1.0, -1.0], read_vals[0])
self.assertAllEqual([10.0, -10.0], read_vals[1])
self.assertAllEqual([[2.0, 3.0], [4.0, 5.0]], grad_vals[0])
@test_util.disable_control_flow_v2("b/122315378 (gather)")
def testTensorArrayWriteGatherAndGradients(self):
with self.session() as session, self.test_scope():
def fn():
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, tensor_array_name="foo", size=10)
values = constant_op.constant([[1.0 * x, -1.0 * x] for x in range(10)])
indices = constant_op.constant([1, 8])
w = ta.unstack(values)
g = w.gather(indices)
# Test combined gradients + aggregation of read(0).
grad = gradients_impl.gradients(
ys=[g], xs=[values], grad_ys=[[[2.0, 3.0], [4.0, 5.0]]])
return [[g], grad]
g_vals, grad_vals = self.evaluate(xla.compile(fn))
# Gradients for 8 of the 10 unread components are zero.
expected_grad = np.zeros((10, 2))
expected_grad[1] = [2.0, 3.0]
expected_grad[8] = [4.0, 5.0]
self.assertEqual(len(g_vals), 1)
self.assertEqual(len(grad_vals), 1)
self.assertAllEqual([[1.0, -1.0], [8.0, -8.0]], g_vals[0])
self.assertAllEqual(expected_grad, grad_vals[0])
def testTensorArrayIdentity(self):
with self.session() as session, self.test_scope():
tensor_arrays = {}
v0 = resource_variable_ops.ResourceVariable(0.0)
v1 = resource_variable_ops.ResourceVariable(0.0)
def fn():
ta0 = tensor_array_ops.TensorArray(
dtype=dtypes.float32, size=2, infer_shape=False)
ta1 = tensor_array_ops.TensorArray(
dtype=dtypes.int32, size=4, infer_shape=True)
ta0 = ta0.write(0, 0.)
ta1 = ta1.write(0, 1)
with ops.control_dependencies([v0.assign_add(1.0)]):
ta0 = ta0.identity()
with ops.control_dependencies([v1.assign_add(1.0)]):
ta1 = ta1.identity()
read0 = ta0.read(0)
read1 = ta1.read(0)
size0 = ta0.size()
size1 = ta1.size()
tensor_arrays[0] = ta0
tensor_arrays[1] = ta1
return [read0, read1, size0, size1, v0, v1]
variables.global_variables_initializer().run()
read0_v, read1_v, size0_v, size1_v, v0, v1 = self.evaluate(
xla.compile(fn))
# Tests correct properties on new TensorArrays.
self.assertEqual(dtypes.float32, tensor_arrays[0].dtype)
self.assertEqual(dtypes.int32, tensor_arrays[1].dtype)
# Tests that the control dependencies was added and executed.
self.assertEqual(1.0, v0)
self.assertEqual(1.0, v1)
# Tests correct TensorArray.
self.assertEqual(read0_v, 0)
self.assertEqual(read1_v, 1)
self.assertEqual(size0_v, 2)
self.assertEqual(size1_v, 4)
if __name__ == "__main__":
test.main()
| |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest ; pytest
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
# External imports
import bs4
# Bokeh imports
# Module under test
import bokeh.embed.server as bes
#-----------------------------------------------------------------------------
# Setup
#-----------------------------------------------------------------------------
@pytest.fixture
def test_plot():
from bokeh.plotting import figure
test_plot = figure()
test_plot.circle([1, 2], [2, 3])
return test_plot
#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------
class TestServerDocument(object):
def test_invalid_resources_param(self):
with pytest.raises(ValueError):
bes.server_document(url="http://localhost:8081/foo/bar/sliders", resources=123)
with pytest.raises(ValueError):
bes.server_document(url="http://localhost:8081/foo/bar/sliders", resources="whatever")
def test_resources_default_is_implicit(self):
r = bes.server_document(url="http://localhost:8081/foo/bar/sliders", resources="default")
assert 'resources=' not in r
def test_resources_none(self):
r = bes.server_document(url="http://localhost:8081/foo/bar/sliders", resources=None)
assert 'resources=none' in r
def test_general(self):
r = bes.server_document(url="http://localhost:8081/foo/bar/sliders")
assert 'bokeh-app-path=/foo/bar/sliders' in r
assert 'bokeh-absolute-url=http://localhost:8081/foo/bar/sliders' in r
html = bs4.BeautifulSoup(r, "lxml")
scripts = html.findAll(name='script')
assert len(scripts) == 1
attrs = scripts[0].attrs
assert set(attrs), set([
'src',
'data-bokeh-doc-id',
'data-bokeh-model-id',
'id'
])
divid = attrs['id']
src = "%s/autoload.js?bokeh-autoload-element=%s&bokeh-app-path=/foo/bar/sliders&bokeh-absolute-url=%s" % \
("http://localhost:8081/foo/bar/sliders", divid, "http://localhost:8081/foo/bar/sliders")
assert attrs == { 'data-bokeh-doc-id' : '',
'data-bokeh-model-id' : '',
'id' : divid,
'src' : src }
def test_script_attrs_arguments_provided(self):
r = bes.server_document(arguments=dict(foo=10))
assert 'foo=10' in r
html = bs4.BeautifulSoup(r, "lxml")
scripts = html.findAll(name='script')
assert len(scripts) == 1
attrs = scripts[0].attrs
assert set(attrs) == set([
'src',
'data-bokeh-doc-id',
'data-bokeh-model-id',
'id'
])
divid = attrs['id']
src = "%s/autoload.js?bokeh-autoload-element=%s&bokeh-absolute-url=%s&foo=10" % \
("http://localhost:5006", divid, "http://localhost:5006")
assert attrs == { 'data-bokeh-doc-id' : '',
'data-bokeh-model-id' : '',
'id' : divid,
'src' : src }
def test_script_attrs_url_provided_absolute_resources(self):
r = bes.server_document(url="http://localhost:8081/foo/bar/sliders")
assert 'bokeh-app-path=/foo/bar/sliders' in r
assert 'bokeh-absolute-url=http://localhost:8081/foo/bar/sliders' in r
html = bs4.BeautifulSoup(r, "lxml")
scripts = html.findAll(name='script')
assert len(scripts) == 1
attrs = scripts[0].attrs
assert set(attrs) == set([
'src',
'data-bokeh-doc-id',
'data-bokeh-model-id',
'id'
])
divid = attrs['id']
src = "%s/autoload.js?bokeh-autoload-element=%s&bokeh-app-path=/foo/bar/sliders&bokeh-absolute-url=%s" % \
("http://localhost:8081/foo/bar/sliders", divid, "http://localhost:8081/foo/bar/sliders")
assert attrs == { 'data-bokeh-doc-id' : '',
'data-bokeh-model-id' : '',
'id' : divid,
'src' : src }
def test_script_attrs_url_provided(self):
r = bes.server_document(url="http://localhost:8081/foo/bar/sliders", relative_urls=True)
assert 'bokeh-app-path=/foo/bar/sliders' in r
html = bs4.BeautifulSoup(r, "lxml")
scripts = html.findAll(name='script')
assert len(scripts) == 1
attrs = scripts[0].attrs
assert set(attrs) == set([
'src',
'data-bokeh-doc-id',
'data-bokeh-model-id',
'id'
])
divid = attrs['id']
src = "%s/autoload.js?bokeh-autoload-element=%s&bokeh-app-path=/foo/bar/sliders" % \
("http://localhost:8081/foo/bar/sliders", divid)
assert attrs == { 'data-bokeh-doc-id' : '',
'data-bokeh-model-id' : '',
'id' : divid,
'src' : src }
class TestServerSession(object):
def test_return_type(self, test_plot):
r = bes.server_session(test_plot, session_id='fakesession')
assert isinstance(r, str)
def test_script_attrs_session_id_provided(self, test_plot):
r = bes.server_session(test_plot, session_id='fakesession')
assert 'bokeh-session-id=fakesession' in r
html = bs4.BeautifulSoup(r, "lxml")
scripts = html.findAll(name='script')
assert len(scripts) == 1
attrs = scripts[0].attrs
assert set(attrs) == set([
'src',
'data-bokeh-doc-id',
'data-bokeh-model-id',
'id'
])
divid = attrs['id']
src = "%s/autoload.js?bokeh-autoload-element=%s&bokeh-absolute-url=%s&bokeh-session-id=fakesession" % \
("http://localhost:5006", divid, "http://localhost:5006")
assert attrs == { 'data-bokeh-doc-id' : '',
'data-bokeh-model-id' : str(test_plot._id),
'id' : divid,
'src' : src }
def test_invalid_resources_param(self, test_plot):
with pytest.raises(ValueError):
bes.server_session(test_plot, session_id='fakesession', resources=123)
with pytest.raises(ValueError):
bes.server_session(test_plot, session_id='fakesession', resources="whatever")
def test_resources_default_is_implicit(self, test_plot):
r = bes.server_session(test_plot, session_id='fakesession', resources="default")
assert 'resources=' not in r
def test_resources_none(self, test_plot):
r = bes.server_session(test_plot, session_id='fakesession', resources=None)
assert 'resources=none' in r
def test_model_none(self):
r = bes.server_session(None, session_id='fakesession')
html = bs4.BeautifulSoup(r, "lxml")
scripts = html.findAll(name='script')
assert len(scripts) == 1
attrs = scripts[0].attrs
assert set(attrs), set([
'src',
'data-bokeh-doc-id',
'data-bokeh-model-id',
'id'
])
divid = attrs['id']
src = "%s/autoload.js?bokeh-autoload-element=%s&bokeh-absolute-url=%s&bokeh-session-id=fakesession" % \
("http://localhost:5006", divid, "http://localhost:5006")
assert attrs == { 'data-bokeh-doc-id' : '',
'data-bokeh-model-id' : '',
'id' : divid,
'src' : src }
def test_general(self, test_plot):
r = bes.server_session(test_plot, session_id='fakesession')
assert 'bokeh-session-id=fakesession' in r
html = bs4.BeautifulSoup(r, "lxml")
scripts = html.findAll(name='script')
assert len(scripts) == 1
attrs = scripts[0].attrs
assert set(attrs), set([
'src',
'data-bokeh-doc-id',
'data-bokeh-model-id',
'id'
])
divid = attrs['id']
src = "%s/autoload.js?bokeh-autoload-element=%s&bokeh-absolute-url=%s&bokeh-session-id=fakesession" % \
("http://localhost:5006", divid, "http://localhost:5006")
assert attrs == { 'data-bokeh-doc-id' : '',
'data-bokeh-model-id' : str(test_plot._id),
'id' : divid,
'src' : src }
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
class Test__clean_url(object):
def test_default(self):
assert bes._clean_url("default") == bes.DEFAULT_SERVER_HTTP_URL.rstrip("/")
def test_bad_ws(self):
with pytest.raises(ValueError):
bes._clean_url("ws://foo")
def test_arg(self):
assert bes._clean_url("http://foo/bar") == "http://foo/bar"
assert bes._clean_url("http://foo/bar/") == "http://foo/bar"
class Test__get_app_path(object):
def test_arg(self):
assert bes._get_app_path("foo") == "/foo"
assert bes._get_app_path("http://foo") == "/"
assert bes._get_app_path("http://foo/bar") == "/bar"
assert bes._get_app_path("https://foo") == "/"
assert bes._get_app_path("https://foo/bar") == "/bar"
class Test__process_arguments(object):
def test_None(self):
assert bes._process_arguments(None) == ""
def test_args(self):
args = dict(foo=10, bar="baz")
r = bes._process_arguments(args)
# order unspecified
assert r == "&foo=10&bar=baz" or r == "&bar=baz&foo=10"
def test_args_ignores_bokeh_prefixed(self):
args = dict(foo=10, bar="baz")
args["bokeh-junk"] = 20
r = bes._process_arguments(args)
# order unspecified
assert r == "&foo=10&bar=baz" or r == "&bar=baz&foo=10"
class Test__process_app_path(object):
def test_root(self):
assert bes._process_app_path("/") == ""
def test_arg(self):
assert bes._process_app_path("/stuff") == "&bokeh-app-path=/stuff"
class Test__process_relative_urls(object):
def test_True(self):
assert bes._process_relative_urls(True, "") == ""
assert bes._process_relative_urls(True, "/stuff") == ""
def test_Flase(self):
assert bes._process_relative_urls(False, "/stuff") == "&bokeh-absolute-url=/stuff"
class Test__process_resources(object):
def test_bad_input(self):
with pytest.raises(ValueError):
bes._process_resources("foo")
def test_None(self):
assert bes._process_resources(None) == "&resources=none"
def test_default(self):
assert bes._process_resources("default") == ""
class Test__process_session_id(object):
def test_arg(self):
assert bes._process_session_id("foo123") == "&bokeh-session-id=foo123"
def Test__src_path(object):
def test_args(self):
assert bes._src_path("http://foo", "1234") =="http://foo/autoload.js?bokeh-autoload-element=1234"
| |
"""
Multi-part parsing for file uploads.
Exposes one class, ``MultiPartParser``, which feeds chunks of uploaded data to
file upload handlers for processing.
"""
from __future__ import unicode_literals
import base64
import binascii
import cgi
import sys
from django.conf import settings
from django.core.exceptions import (
RequestDataTooBig, SuspiciousMultipartForm, TooManyFieldsSent,
)
from django.core.files.uploadhandler import (
SkipFile, StopFutureHandlers, StopUpload,
)
from django.utils import six
from django.utils.datastructures import MultiValueDict
from django.utils.encoding import force_text
from django.utils.six.moves.urllib.parse import unquote
from django.utils.text import unescape_entities
__all__ = ('MultiPartParser', 'MultiPartParserError', 'InputStreamExhausted')
class MultiPartParserError(Exception):
pass
class InputStreamExhausted(Exception):
"""
No more reads are allowed from this device.
"""
pass
RAW = "raw"
FILE = "file"
FIELD = "field"
_BASE64_DECODE_ERROR = TypeError if six.PY2 else binascii.Error
class MultiPartParser(object):
"""
A rfc2388 multipart/form-data parser.
``MultiValueDict.parse()`` reads the input stream in ``chunk_size`` chunks
and returns a tuple of ``(MultiValueDict(POST), MultiValueDict(FILES))``.
"""
def __init__(self, META, input_data, upload_handlers, encoding=None):
"""
Initialize the MultiPartParser object.
:META:
The standard ``META`` dictionary in Django request objects.
:input_data:
The raw post data, as a file-like object.
:upload_handlers:
A list of UploadHandler instances that perform operations on the
uploaded data.
:encoding:
The encoding with which to treat the incoming data.
"""
# Content-Type should contain multipart and the boundary information.
content_type = META.get('CONTENT_TYPE', '')
if not content_type.startswith('multipart/'):
raise MultiPartParserError('Invalid Content-Type: %s' % content_type)
# Parse the header to get the boundary to split the parts.
ctypes, opts = parse_header(content_type.encode('ascii'))
boundary = opts.get('boundary')
if not boundary or not cgi.valid_boundary(boundary):
raise MultiPartParserError('Invalid boundary in multipart: %s' % boundary)
# Content-Length should contain the length of the body we are about
# to receive.
try:
content_length = int(META.get('CONTENT_LENGTH', 0))
except (ValueError, TypeError):
content_length = 0
if content_length < 0:
# This means we shouldn't continue...raise an error.
raise MultiPartParserError("Invalid content length: %r" % content_length)
if isinstance(boundary, six.text_type):
boundary = boundary.encode('ascii')
self._boundary = boundary
self._input_data = input_data
# For compatibility with low-level network APIs (with 32-bit integers),
# the chunk size should be < 2^31, but still divisible by 4.
possible_sizes = [x.chunk_size for x in upload_handlers if x.chunk_size]
self._chunk_size = min([2 ** 31 - 4] + possible_sizes)
self._meta = META
self._encoding = encoding or settings.DEFAULT_CHARSET
self._content_length = content_length
self._upload_handlers = upload_handlers
def parse(self):
"""
Parse the POST data and break it into a FILES MultiValueDict and a POST
MultiValueDict.
Return a tuple containing the POST and FILES dictionary, respectively.
"""
from django.http import QueryDict
encoding = self._encoding
handlers = self._upload_handlers
# HTTP spec says that Content-Length >= 0 is valid
# handling content-length == 0 before continuing
if self._content_length == 0:
return QueryDict(encoding=self._encoding), MultiValueDict()
# See if any of the handlers take care of the parsing.
# This allows overriding everything if need be.
for handler in handlers:
result = handler.handle_raw_input(
self._input_data,
self._meta,
self._content_length,
self._boundary,
encoding,
)
# Check to see if it was handled
if result is not None:
return result[0], result[1]
# Create the data structures to be used later.
self._post = QueryDict(mutable=True)
self._files = MultiValueDict()
# Instantiate the parser and stream:
stream = LazyStream(ChunkIter(self._input_data, self._chunk_size))
# Whether or not to signal a file-completion at the beginning of the loop.
old_field_name = None
counters = [0] * len(handlers)
# Number of bytes that have been read.
num_bytes_read = 0
# To count the number of keys in the request.
num_post_keys = 0
# To limit the amount of data read from the request.
read_size = None
try:
for item_type, meta_data, field_stream in Parser(stream, self._boundary):
if old_field_name:
# We run this at the beginning of the next loop
# since we cannot be sure a file is complete until
# we hit the next boundary/part of the multipart content.
self.handle_file_complete(old_field_name, counters)
old_field_name = None
try:
disposition = meta_data['content-disposition'][1]
field_name = disposition['name'].strip()
except (KeyError, IndexError, AttributeError):
continue
transfer_encoding = meta_data.get('content-transfer-encoding')
if transfer_encoding is not None:
transfer_encoding = transfer_encoding[0].strip()
field_name = force_text(field_name, encoding, errors='replace')
if item_type == FIELD:
# Avoid storing more than DATA_UPLOAD_MAX_NUMBER_FIELDS.
num_post_keys += 1
if (settings.DATA_UPLOAD_MAX_NUMBER_FIELDS is not None and
settings.DATA_UPLOAD_MAX_NUMBER_FIELDS < num_post_keys):
raise TooManyFieldsSent(
'The number of GET/POST parameters exceeded '
'settings.DATA_UPLOAD_MAX_NUMBER_FIELDS.'
)
# Avoid reading more than DATA_UPLOAD_MAX_MEMORY_SIZE.
if settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None:
read_size = settings.DATA_UPLOAD_MAX_MEMORY_SIZE - num_bytes_read
# This is a post field, we can just set it in the post
if transfer_encoding == 'base64':
raw_data = field_stream.read(size=read_size)
num_bytes_read += len(raw_data)
try:
data = base64.b64decode(raw_data)
except _BASE64_DECODE_ERROR:
data = raw_data
else:
data = field_stream.read(size=read_size)
num_bytes_read += len(data)
# Add two here to make the check consistent with the
# x-www-form-urlencoded check that includes '&='.
num_bytes_read += len(field_name) + 2
if (settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None and
num_bytes_read > settings.DATA_UPLOAD_MAX_MEMORY_SIZE):
raise RequestDataTooBig('Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE.')
self._post.appendlist(field_name, force_text(data, encoding, errors='replace'))
elif item_type == FILE:
# This is a file, use the handler...
file_name = disposition.get('filename')
if file_name:
file_name = force_text(file_name, encoding, errors='replace')
file_name = self.IE_sanitize(unescape_entities(file_name))
if not file_name:
continue
content_type, content_type_extra = meta_data.get('content-type', ('', {}))
content_type = content_type.strip()
charset = content_type_extra.get('charset')
try:
content_length = int(meta_data.get('content-length')[0])
except (IndexError, TypeError, ValueError):
content_length = None
counters = [0] * len(handlers)
try:
for handler in handlers:
try:
handler.new_file(
field_name, file_name, content_type,
content_length, charset, content_type_extra,
)
except StopFutureHandlers:
break
for chunk in field_stream:
if transfer_encoding == 'base64':
# We only special-case base64 transfer encoding
# We should always decode base64 chunks by multiple of 4,
# ignoring whitespace.
stripped_chunk = b"".join(chunk.split())
remaining = len(stripped_chunk) % 4
while remaining != 0:
over_chunk = field_stream.read(4 - remaining)
stripped_chunk += b"".join(over_chunk.split())
remaining = len(stripped_chunk) % 4
try:
chunk = base64.b64decode(stripped_chunk)
except Exception as e:
# Since this is only a chunk, any error is an unfixable error.
msg = "Could not decode base64 data: %r" % e
six.reraise(MultiPartParserError, MultiPartParserError(msg), sys.exc_info()[2])
for i, handler in enumerate(handlers):
chunk_length = len(chunk)
chunk = handler.receive_data_chunk(chunk, counters[i])
counters[i] += chunk_length
if chunk is None:
# Don't continue if the chunk received by
# the handler is None.
break
except SkipFile:
self._close_files()
# Just use up the rest of this file...
exhaust(field_stream)
else:
# Handle file upload completions on next iteration.
old_field_name = field_name
else:
# If this is neither a FIELD or a FILE, just exhaust the stream.
exhaust(stream)
except StopUpload as e:
self._close_files()
if not e.connection_reset:
exhaust(self._input_data)
else:
# Make sure that the request data is all fed
exhaust(self._input_data)
# Signal that the upload has completed.
for handler in handlers:
retval = handler.upload_complete()
if retval:
break
self._post._mutable = False
return self._post, self._files
def handle_file_complete(self, old_field_name, counters):
"""
Handle all the signaling that takes place when a file is complete.
"""
for i, handler in enumerate(self._upload_handlers):
file_obj = handler.file_complete(counters[i])
if file_obj:
# If it returns a file object, then set the files dict.
self._files.appendlist(force_text(old_field_name, self._encoding, errors='replace'), file_obj)
break
def IE_sanitize(self, filename):
"""Cleanup filename from Internet Explorer full paths."""
return filename and filename[filename.rfind("\\") + 1:].strip()
def _close_files(self):
# Free up all file handles.
# FIXME: this currently assumes that upload handlers store the file as 'file'
# We should document that... (Maybe add handler.free_file to complement new_file)
for handler in self._upload_handlers:
if hasattr(handler, 'file'):
handler.file.close()
class LazyStream(six.Iterator):
"""
The LazyStream wrapper allows one to get and "unget" bytes from a stream.
Given a producer object (an iterator that yields bytestrings), the
LazyStream object will support iteration, reading, and keeping a "look-back"
variable in case you need to "unget" some bytes.
"""
def __init__(self, producer, length=None):
"""
Every LazyStream must have a producer when instantiated.
A producer is an iterable that returns a string each time it
is called.
"""
self._producer = producer
self._empty = False
self._leftover = b''
self.length = length
self.position = 0
self._remaining = length
self._unget_history = []
def tell(self):
return self.position
def read(self, size=None):
def parts():
remaining = self._remaining if size is None else size
# do the whole thing in one shot if no limit was provided.
if remaining is None:
yield b''.join(self)
return
# otherwise do some bookkeeping to return exactly enough
# of the stream and stashing any extra content we get from
# the producer
while remaining != 0:
assert remaining > 0, 'remaining bytes to read should never go negative'
try:
chunk = next(self)
except StopIteration:
return
else:
emitting = chunk[:remaining]
self.unget(chunk[remaining:])
remaining -= len(emitting)
yield emitting
out = b''.join(parts())
return out
def __next__(self):
"""
Used when the exact number of bytes to read is unimportant.
This procedure just returns whatever is chunk is conveniently returned
from the iterator instead. Useful to avoid unnecessary bookkeeping if
performance is an issue.
"""
if self._leftover:
output = self._leftover
self._leftover = b''
else:
output = next(self._producer)
self._unget_history = []
self.position += len(output)
return output
def close(self):
"""
Used to invalidate/disable this lazy stream.
Replaces the producer with an empty list. Any leftover bytes that have
already been read will still be reported upon read() and/or next().
"""
self._producer = []
def __iter__(self):
return self
def unget(self, bytes):
"""
Places bytes back onto the front of the lazy stream.
Future calls to read() will return those bytes first. The
stream position and thus tell() will be rewound.
"""
if not bytes:
return
self._update_unget_history(len(bytes))
self.position -= len(bytes)
self._leftover = b''.join([bytes, self._leftover])
def _update_unget_history(self, num_bytes):
"""
Updates the unget history as a sanity check to see if we've pushed
back the same number of bytes in one chunk. If we keep ungetting the
same number of bytes many times (here, 50), we're mostly likely in an
infinite loop of some sort. This is usually caused by a
maliciously-malformed MIME request.
"""
self._unget_history = [num_bytes] + self._unget_history[:49]
number_equal = len([
current_number for current_number in self._unget_history
if current_number == num_bytes
])
if number_equal > 40:
raise SuspiciousMultipartForm(
"The multipart parser got stuck, which shouldn't happen with"
" normal uploaded files. Check for malicious upload activity;"
" if there is none, report this to the Django developers."
)
class ChunkIter(six.Iterator):
"""
An iterable that will yield chunks of data. Given a file-like object as the
constructor, this object will yield chunks of read operations from that
object.
"""
def __init__(self, flo, chunk_size=64 * 1024):
self.flo = flo
self.chunk_size = chunk_size
def __next__(self):
try:
data = self.flo.read(self.chunk_size)
except InputStreamExhausted:
raise StopIteration()
if data:
return data
else:
raise StopIteration()
def __iter__(self):
return self
class InterBoundaryIter(six.Iterator):
"""
A Producer that will iterate over boundaries.
"""
def __init__(self, stream, boundary):
self._stream = stream
self._boundary = boundary
def __iter__(self):
return self
def __next__(self):
try:
return LazyStream(BoundaryIter(self._stream, self._boundary))
except InputStreamExhausted:
raise StopIteration()
class BoundaryIter(six.Iterator):
"""
A Producer that is sensitive to boundaries.
Will happily yield bytes until a boundary is found. Will yield the bytes
before the boundary, throw away the boundary bytes themselves, and push the
post-boundary bytes back on the stream.
The future calls to next() after locating the boundary will raise a
StopIteration exception.
"""
def __init__(self, stream, boundary):
self._stream = stream
self._boundary = boundary
self._done = False
# rollback an additional six bytes because the format is like
# this: CRLF<boundary>[--CRLF]
self._rollback = len(boundary) + 6
# Try to use mx fast string search if available. Otherwise
# use Python find. Wrap the latter for consistency.
unused_char = self._stream.read(1)
if not unused_char:
raise InputStreamExhausted()
self._stream.unget(unused_char)
def __iter__(self):
return self
def __next__(self):
if self._done:
raise StopIteration()
stream = self._stream
rollback = self._rollback
bytes_read = 0
chunks = []
for bytes in stream:
bytes_read += len(bytes)
chunks.append(bytes)
if bytes_read > rollback:
break
if not bytes:
break
else:
self._done = True
if not chunks:
raise StopIteration()
chunk = b''.join(chunks)
boundary = self._find_boundary(chunk, len(chunk) < self._rollback)
if boundary:
end, next = boundary
stream.unget(chunk[next:])
self._done = True
return chunk[:end]
else:
# make sure we don't treat a partial boundary (and
# its separators) as data
if not chunk[:-rollback]: # and len(chunk) >= (len(self._boundary) + 6):
# There's nothing left, we should just return and mark as done.
self._done = True
return chunk
else:
stream.unget(chunk[-rollback:])
return chunk[:-rollback]
def _find_boundary(self, data, eof=False):
"""
Finds a multipart boundary in data.
Should no boundary exist in the data None is returned instead. Otherwise
a tuple containing the indices of the following are returned:
* the end of current encapsulation
* the start of the next encapsulation
"""
index = data.find(self._boundary)
if index < 0:
return None
else:
end = index
next = index + len(self._boundary)
# backup over CRLF
last = max(0, end - 1)
if data[last:last + 1] == b'\n':
end -= 1
last = max(0, end - 1)
if data[last:last + 1] == b'\r':
end -= 1
return end, next
def exhaust(stream_or_iterable):
"""Exhaust an iterator or stream."""
try:
iterator = iter(stream_or_iterable)
except TypeError:
iterator = ChunkIter(stream_or_iterable, 16384)
for __ in iterator:
pass
def parse_boundary_stream(stream, max_header_size):
"""
Parses one and exactly one stream that encapsulates a boundary.
"""
# Stream at beginning of header, look for end of header
# and parse it if found. The header must fit within one
# chunk.
chunk = stream.read(max_header_size)
# 'find' returns the top of these four bytes, so we'll
# need to munch them later to prevent them from polluting
# the payload.
header_end = chunk.find(b'\r\n\r\n')
def _parse_header(line):
main_value_pair, params = parse_header(line)
try:
name, value = main_value_pair.split(':', 1)
except ValueError:
raise ValueError("Invalid header: %r" % line)
return name, (value, params)
if header_end == -1:
# we find no header, so we just mark this fact and pass on
# the stream verbatim
stream.unget(chunk)
return (RAW, {}, stream)
header = chunk[:header_end]
# here we place any excess chunk back onto the stream, as
# well as throwing away the CRLFCRLF bytes from above.
stream.unget(chunk[header_end + 4:])
TYPE = RAW
outdict = {}
# Eliminate blank lines
for line in header.split(b'\r\n'):
# This terminology ("main value" and "dictionary of
# parameters") is from the Python docs.
try:
name, (value, params) = _parse_header(line)
except ValueError:
continue
if name == 'content-disposition':
TYPE = FIELD
if params.get('filename'):
TYPE = FILE
outdict[name] = value, params
if TYPE == RAW:
stream.unget(chunk)
return (TYPE, outdict, stream)
class Parser(object):
def __init__(self, stream, boundary):
self._stream = stream
self._separator = b'--' + boundary
def __iter__(self):
boundarystream = InterBoundaryIter(self._stream, self._separator)
for sub_stream in boundarystream:
# Iterate over each part
yield parse_boundary_stream(sub_stream, 1024)
def parse_header(line):
"""
Parse the header into a key-value.
Input (line): bytes, output: unicode for key/name, bytes for value which
will be decoded later.
"""
plist = _parse_header_params(b';' + line)
key = plist.pop(0).lower().decode('ascii')
pdict = {}
for p in plist:
i = p.find(b'=')
if i >= 0:
has_encoding = False
name = p[:i].strip().lower().decode('ascii')
if name.endswith('*'):
# Lang/encoding embedded in the value (like "filename*=UTF-8''file.ext")
# http://tools.ietf.org/html/rfc2231#section-4
name = name[:-1]
if p.count(b"'") == 2:
has_encoding = True
value = p[i + 1:].strip()
if has_encoding:
encoding, lang, value = value.split(b"'")
if six.PY3:
value = unquote(value.decode(), encoding=encoding.decode())
else:
value = unquote(value).decode(encoding)
if len(value) >= 2 and value[:1] == value[-1:] == b'"':
value = value[1:-1]
value = value.replace(b'\\\\', b'\\').replace(b'\\"', b'"')
pdict[name] = value
return key, pdict
def _parse_header_params(s):
plist = []
while s[:1] == b';':
s = s[1:]
end = s.find(b';')
while end > 0 and s.count(b'"', 0, end) % 2:
end = s.find(b';', end + 1)
if end < 0:
end = len(s)
f = s[:end]
plist.append(f.strip())
s = s[end:]
return plist
| |
import pytest
import shutil
import os
import numpy as np
import astropy.units as u
import astropy.table as at
from astropy.io import fits
import filecmp
from ....obsobj import obsObj
from .. import isoMeasurer
from .. import polytools
from .... import tabtools
dir_parent = './testing/'
bandline = 'i'
bandconti = 'r'
survey = 'hsc'
isocut = 1.e-15*u.Unit('erg / (arcsec2 cm2 s)')
@pytest.fixture(scope="module", autouse=True)
def setUp_tearDown():
""" rm ./testing/ and ./test2/ before and after testing"""
# setup
if os.path.isdir(dir_parent):
shutil.rmtree(dir_parent)
os.makedirs(dir_parent)
# yield
# # tear down
# if os.path.isdir(dir_parent):
# shutil.rmtree(dir_parent)
@pytest.fixture
def measurer1():
ra = 140.099341430207
dec = 0.580162492432517
z = 0.4114188
dir_obj = './testing/SDSSJ0920+0034/'
dir_verif = 'verification_data/SDSSJ0920+0034/'
if os.path.isdir(dir_obj):
shutil.rmtree(dir_obj)
shutil.copytree(dir_verif, dir_obj)
obj = obsObj(ra=ra, dec=dec, dir_obj = dir_obj)
return isoMeasurer(obj=obj, survey='hsc', z=z, center_mode='n/2-1')
@pytest.fixture
def measurer_nanimg():
ra = 140.826752453534
dec = 0.530545728517824
z = 0.548
dir_verif = './verification_data/SDSSJ092318+003149/'
dir_obj = './testing/SDSSJ092318+003149/'
if os.path.isdir(dir_obj):
shutil.rmtree(dir_obj)
shutil.copytree(dir_verif, dir_obj)
obj = obsObj(ra=ra, dec=dec, dir_obj=dir_obj, obj_naming_sys='sdss_precise')
return isoMeasurer(obj=obj, survey='hsc', z=z, center_mode='n/2-1')
def test_isomeasurer_get_fp_msr(measurer1):
m = measurer1
assert m.get_fp_msr() == m.dir_obj+'msr_iso.csv'
def test_isomeasurer_get_fp_contours(measurer1):
m = measurer1
imgtag = 'OIII5008_I'
assert m.get_fp_contours(imgtag=imgtag, onlycenter=False) == m.dir_obj+'msr_iso-OIII5008_I_contours.pkl'
assert m.get_fp_contours(imgtag=imgtag, onlycenter=True) == m.dir_obj+'msr_iso-OIII5008_I_contours-ctr.pkl'
def test_isomeasurer_get_contours_from_img(measurer1):
m = measurer1
fn_img = m.dir_obj+'stamp-OIII5008_I.fits'
img = fits.getdata(fn_img)
xc, yc = m._get_xc_yc(img)
isocut = 1.e-15
contours = m._get_contours_from_img(img=img, isocut=isocut, xc=xc, yc=yc, minarea=0., onlycenter=False, centerradius=2.*u.arcsec)
assert polytools.ispolys(contours)
assert polytools.NetPolygonsArea(contours) > 0
def test_isomeasurer_make_measurements(measurer1):
m = measurer1
imgtag = 'OIII5008_I'
minarea = 5
status = m.make_measurements(imgtag=imgtag, isocut=isocut, minarea=minarea, onlycenter=True, centerradius=5.*u.arcsec, overwrite=False, savecontours=True, plotmsr=True)
assert status
assert os.path.isfile(m.dir_obj+'msr_iso-OIII5008_I.pdf')
assert os.path.isfile(m.dir_obj+'msr_iso.csv')
assert os.path.isfile(m.dir_obj+'msr_iso-OIII5008_I_contours-ctr.pkl')
tab = at.Table.read(m.dir_obj+'msr_iso.csv')
assert tab['imgtag'][0] == imgtag
assert u.Quantity(tab['isocut'][0]) == isocut
assert tab['minarea'][0] == minarea
assert tab['area_ars'] == tab['area_pix'] * 0.168**2
assert tab['dmax_ars'] == tab['dmax_pix'] * 0.168
assert round(tab['area_kpc'], 1) == round(tab['area_ars'] * 5.465**2, 1)
assert round(tab['dmax_kpc'], 1) == round(tab['dmax_ars'] * 5.465, 1)
def test_isomeasurer_make_measurements_suffix(measurer1):
m = measurer1
fn = m.dir_obj+'msr_iso.csv'
imgtag = 'OIII5008_I'
minarea = 5
isocut1 = 1.e-15*u.Unit('erg / (arcsec2 cm2 s)')
suffix1 = '_1e-15'
isocut2 = 3.e-15*u.Unit('erg / (arcsec2 cm2 s)')
suffix2 = '_3e-15'
for isocut, suffix in ((isocut1, suffix1), (isocut2, suffix2)):
status = m.make_measurements(imgtag=imgtag, isocut=isocut, minarea=minarea, onlycenter=True, centerradius=5.*u.arcsec, plotsuffix=suffix, overwrite=True, savecontours=True, plotmsr=True)
assert status
assert os.path.isfile(m.dir_obj+'msr_iso-OIII5008_I{suffix}.pdf'.format(suffix=suffix))
assert os.path.isfile(m.dir_obj+'msr_iso-OIII5008_I{suffix}_contours-ctr.pkl'.format(suffix=suffix))
assert os.path.isfile(m.dir_obj+'msr_iso.csv')
tab = at.Table.read(fn)
assert tabtools.tab_has_row(tab, {'isocut': isocut})
tab = at.Table.read(fn)
assert len(tab) == 2
def test_isomeasurer_nan_image(measurer_nanimg):
m = measurer_nanimg
imgtag = 'OIII5008_I'
minarea = 5
status = m.make_measurements(imgtag=imgtag, isocut=isocut, minarea=minarea, onlycenter=True, centerradius=5.*u.arcsec, overwrite=False, savecontours=True, plotmsr=True)
fn = m.get_fp_msr()
tab = at.Table.read(fn)
for col in ['area_kpc', 'dmax_kpc', 'rmax_kpc', 'dper_kpc', 'area_ars', 'dmax_ars', 'rmax_ars', 'dper_ars', 'area_pix', 'dmax_pix', 'rmax_pix', 'dper_pix', 'theta_dmax', 'theta_rmax', 'theta_dper', 'aspectr', ]:
assert np.isnan(tab[col][0])
for col in ['imgtag', 'isocut', 'minarea', 'onlycenter', 'centerradius']:
assert col in tab.colnames
def test_isomeasurer_make_colorimg(measurer1):
m = measurer1
status = m.make_colorimg(bands ='gri', img_type='stamp', overwrite=False)
assert status
assert os.path.isfile(m.dir_obj+'color_stamp-gri.png')
def test_isomeasurer_make_visualpanel(measurer1):
m = measurer1
# isocut = 3.e-15*u.Unit('erg / (arcsec2 cm2 s)')
status = m.make_visualpanel(compo_bands ='riz', imgtag='OIII5008_I', overwrite=False)
assert status
assert os.path.isfile(m.dir_obj+'msr_iso-OIII5008_I_panel.pdf')
def test_isomeasurer_make_noiselevel(measurer1):
m = measurer1
# isocut = 3.e-15*u.Unit('erg / (arcsec2 cm2 s)')
status = m.make_noiselevel(imgtag='OIII5008_I', toplot=True, overwrite=False)
assert status
assert os.path.isfile(m.dir_obj+'noiselevel.csv')
assert os.path.isfile(m.dir_obj+'noiselevel-OIII5008_I.pdf')
assert m.get_noiselevel(imgtag='OIII5008_I', wunit=False) > 0.
assert m.get_noiselevel(imgtag='OIII5008_I', wunit=True).unit == u.Unit('1e-15 erg / (arcsec2 cm2 s)')
def test_isomeasurer_make_noiselevel_multifiles(measurer1):
m = measurer1
# isocut = 3.e-15*u.Unit('erg / (arcsec2 cm2 s)')
status = m.make_noiselevel(imgtag='OIII5008_I', toplot=True, overwrite=True)
status = m.make_noiselevel(imgtag='OIII5008_I', toplot=True, overwrite=True)
status = m.make_noiselevel(imgtag='i', toplot=True, overwrite=True)
assert status
assert os.path.isfile(m.dir_obj+'noiselevel.csv')
assert os.path.isfile(m.dir_obj+'noiselevel-OIII5008_I.pdf')
assert os.path.isfile(m.dir_obj+'noiselevel-i.pdf')
tab = at.Table.read(m.dir_obj+'noiselevel.csv')
assert len(tab) == 2
assert m.get_noiselevel(imgtag='OIII5008_I', wunit=False) > 0.
assert m.get_noiselevel(imgtag='i', wunit=False) > 0.
# def test_isomeasurer_summarize_tab(measurer1):
# m = measurer1
# # isocut = 3.e-15*u.Unit('erg / (arcsec2 cm2 s)')
# status = m.make_noiselevel(imgtag='OIII5008_I', toplot=True, overwrite=True)
# status = m.make_noiselevel(imgtag='OIII5008_I', toplot=True, overwrite=True)
# status = m.make_noiselevel(imgtag='i', toplot=True, overwrite=True)
# assert status
# assert os.path.isfile(m.dir_obj+'noiselevel.csv')
# assert os.path.isfile(m.dir_obj+'noiselevel-OIII5008_I.pdf')
# assert os.path.isfile(m.dir_obj+'noiselevel-i.pdf')
# tab = at.Table.read(m.dir_obj+'noiselevel.csv')
# assert len(tab) == 2
# assert m.get_noiselevel(imgtag='OIII5008_I', wunit=False) > 0.
# assert m.get_noiselevel(imgtag='i', wunit=False) > 0.
def test_isomeasurer_summarize(measurer1):
m = measurer1
fn = m.dir_obj+'msr_iso.csv'
fn_sum = m.dir_obj+'msr_iso_smr.csv'
imgtag = 'OIII5008_I'
minarea = 5
isocut1 = 1.e-15*u.Unit('erg / (arcsec2 cm2 s)')
isocut2 = 3.e-15*u.Unit('erg / (arcsec2 cm2 s)')
for isocut in (isocut1, isocut2):
status = m.make_measurements(imgtag=imgtag, isocut=isocut, minarea=minarea, onlycenter=True, centerradius=5.*u.arcsec, overwrite=True, savecontours=False, plotmsr=False)
assert status
tab = at.Table.read(fn)
assert len(tab) == 2
condi = {'imgtag': imgtag}
columns = ['area_ars']
m.summarize(columns=columns, condi=condi, msrsuffix='')
assert os.path.isfile(fn_sum)
tab_sum = at.Table.read(fn_sum)
assert len(tab_sum) == 1
assert tab_sum['area_ars_mean'] == np.mean(tab['area_ars'])
assert tab_sum['area_ars_std'] == np.std(tab['area_ars'])
assert tab_sum['area_ars_median'] == np.median(tab['area_ars'])
assert tab_sum['area_ars_p16'] == np.percentile(tab['area_ars'], 16)
assert tab_sum['area_ars_p84'] == np.percentile(tab['area_ars'], 84)
| |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for learn.dataframe.tensorflow_dataframe."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import math
import tempfile
import numpy as np
from tensorflow.contrib.learn.python.learn.dataframe import tensorflow_dataframe as df
from tensorflow.contrib.learn.python.learn.dataframe.transforms import densify
from tensorflow.core.example import example_pb2
from tensorflow.python.framework import dtypes
from tensorflow.python.lib.io import tf_record
from tensorflow.python.ops import parsing_ops
from tensorflow.python.platform import test
# pylint: disable=g-import-not-at-top
try:
import pandas as pd
HAS_PANDAS = True
except ImportError:
HAS_PANDAS = False
def _assert_df_equals_dict(expected_df, actual_dict):
for col in expected_df:
if expected_df[col].dtype in [np.float32, np.float64]:
assertion = np.testing.assert_allclose
else:
assertion = np.testing.assert_array_equal
if expected_df[col].dtype.kind in ["O", "S", "U"]:
# Python 2/3 compatibility
# TensorFlow always returns bytes, so we just convert the unicode
# expectations to bytes also before comparing.
expected_values = [x.encode("utf-8") for x in expected_df[col].values]
else:
expected_values = expected_df[col].values
assertion(
expected_values,
actual_dict[col],
err_msg="Expected {} in column '{}'; got {}.".format(expected_values,
col,
actual_dict[col]))
class TensorFlowDataFrameTestCase(test.TestCase):
"""Tests for `TensorFlowDataFrame`."""
def _make_test_csv(self):
f = tempfile.NamedTemporaryFile(
dir=self.get_temp_dir(), delete=False, mode="w")
w = csv.writer(f)
w.writerow(["int", "float", "bool", "string"])
for _ in range(100):
intvalue = np.random.randint(-10, 10)
floatvalue = np.random.rand()
boolvalue = int(np.random.rand() > 0.3)
stringvalue = "S: %.4f" % np.random.rand()
row = [intvalue, floatvalue, boolvalue, stringvalue]
w.writerow(row)
f.close()
return f.name
def _make_test_csv_sparse(self):
f = tempfile.NamedTemporaryFile(
dir=self.get_temp_dir(), delete=False, mode="w")
w = csv.writer(f)
w.writerow(["int", "float", "bool", "string"])
for _ in range(100):
# leave columns empty; these will be read as default value (e.g. 0 or NaN)
intvalue = np.random.randint(-10, 10) if np.random.rand() > 0.5 else ""
floatvalue = np.random.rand() if np.random.rand() > 0.5 else ""
boolvalue = int(np.random.rand() > 0.3) if np.random.rand() > 0.5 else ""
stringvalue = (
("S: %.4f" % np.random.rand()) if np.random.rand() > 0.5 else "")
row = [intvalue, floatvalue, boolvalue, stringvalue]
w.writerow(row)
f.close()
return f.name
def _make_test_tfrecord(self):
f = tempfile.NamedTemporaryFile(dir=self.get_temp_dir(), delete=False)
w = tf_record.TFRecordWriter(f.name)
for i in range(100):
ex = example_pb2.Example()
ex.features.feature["var_len_int"].int64_list.value.extend(range((i % 3)))
ex.features.feature["fixed_len_float"].float_list.value.extend(
[float(i), 2 * float(i)])
w.write(ex.SerializeToString())
return f.name
def _assert_pandas_equals_tensorflow(self, pandas_df, tensorflow_df,
num_batches, batch_size):
self.assertItemsEqual(
list(pandas_df.columns) + ["index"], tensorflow_df.columns())
for batch_num, batch in enumerate(tensorflow_df.run(num_batches)):
row_numbers = [
total_row_num % pandas_df.shape[0]
for total_row_num in range(batch_size * batch_num, batch_size * (
batch_num + 1))
]
expected_df = pandas_df.iloc[row_numbers]
_assert_df_equals_dict(expected_df, batch)
def testInitFromPandas(self):
"""Test construction from Pandas DataFrame."""
if not HAS_PANDAS:
return
pandas_df = pd.DataFrame({"sparrow": range(10), "ostrich": 1})
tensorflow_df = df.TensorFlowDataFrame.from_pandas(
pandas_df, batch_size=10, shuffle=False)
batch = tensorflow_df.run_one_batch()
np.testing.assert_array_equal(pandas_df.index.values, batch["index"],
"Expected index {}; got {}".format(
pandas_df.index.values, batch["index"]))
_assert_df_equals_dict(pandas_df, batch)
def testBatch(self):
"""Tests `batch` method.
`DataFrame.batch()` should iterate through the rows of the
`pandas.DataFrame`, and should "wrap around" when it reaches the last row.
"""
if not HAS_PANDAS:
return
pandas_df = pd.DataFrame({
"albatross": range(10),
"bluejay": 1,
"cockatoo": range(0, 20, 2),
"penguin": list("abcdefghij")
})
tensorflow_df = df.TensorFlowDataFrame.from_pandas(pandas_df, shuffle=False)
# Rebatch `df` into the following sizes successively.
batch_sizes = [4, 7]
num_batches = 3
final_batch_size = batch_sizes[-1]
for batch_size in batch_sizes:
tensorflow_df = tensorflow_df.batch(batch_size, shuffle=False)
self._assert_pandas_equals_tensorflow(
pandas_df,
tensorflow_df,
num_batches=num_batches,
batch_size=final_batch_size)
def testFromNumpy(self):
x = np.eye(20)
tensorflow_df = df.TensorFlowDataFrame.from_numpy(x, batch_size=10)
for batch in tensorflow_df.run(30):
for ind, val in zip(batch["index"], batch["value"]):
expected_val = np.zeros_like(val)
expected_val[ind] = 1
np.testing.assert_array_equal(expected_val, val)
def testFromCSV(self):
if not HAS_PANDAS:
return
num_batches = 100
batch_size = 8
enqueue_size = 7
data_path = self._make_test_csv()
default_values = [0, 0.0, 0, ""]
pandas_df = pd.read_csv(data_path)
tensorflow_df = df.TensorFlowDataFrame.from_csv(
[data_path],
enqueue_size=enqueue_size,
batch_size=batch_size,
shuffle=False,
default_values=default_values)
self._assert_pandas_equals_tensorflow(
pandas_df,
tensorflow_df,
num_batches=num_batches,
batch_size=batch_size)
def testFromCSVLimitEpoch(self):
batch_size = 8
num_epochs = 17
expected_num_batches = (num_epochs * 100) // batch_size
data_path = self._make_test_csv()
default_values = [0, 0.0, 0, ""]
tensorflow_df = df.TensorFlowDataFrame.from_csv(
[data_path],
batch_size=batch_size,
shuffle=False,
default_values=default_values)
result_batches = list(tensorflow_df.run(num_epochs=num_epochs))
actual_num_batches = len(result_batches)
self.assertEqual(expected_num_batches, actual_num_batches)
# TODO(soergel): figure out how to dequeue the final small batch
expected_rows = 1696 # num_epochs * 100
actual_rows = sum([len(x["int"]) for x in result_batches])
self.assertEqual(expected_rows, actual_rows)
def testFromCSVWithFeatureSpec(self):
if not HAS_PANDAS:
return
num_batches = 100
batch_size = 8
data_path = self._make_test_csv_sparse()
feature_spec = {
"int": parsing_ops.FixedLenFeature(None, dtypes.int16, np.nan),
"float": parsing_ops.VarLenFeature(dtypes.float16),
"bool": parsing_ops.VarLenFeature(dtypes.bool),
"string": parsing_ops.FixedLenFeature(None, dtypes.string, "")
}
pandas_df = pd.read_csv(data_path, dtype={"string": object})
# Pandas insanely uses NaN for empty cells in a string column.
# And, we can't use Pandas replace() to fix them because nan != nan
s = pandas_df["string"]
for i in range(0, len(s)):
if isinstance(s[i], float) and math.isnan(s[i]):
pandas_df.set_value(i, "string", "")
tensorflow_df = df.TensorFlowDataFrame.from_csv_with_feature_spec(
[data_path],
batch_size=batch_size,
shuffle=False,
feature_spec=feature_spec)
# These columns were sparse; re-densify them for comparison
tensorflow_df["float"] = densify.Densify(np.nan)(tensorflow_df["float"])
tensorflow_df["bool"] = densify.Densify(np.nan)(tensorflow_df["bool"])
self._assert_pandas_equals_tensorflow(
pandas_df,
tensorflow_df,
num_batches=num_batches,
batch_size=batch_size)
def testFromExamples(self):
num_batches = 77
enqueue_size = 11
batch_size = 13
data_path = self._make_test_tfrecord()
features = {
"fixed_len_float":
parsing_ops.FixedLenFeature(
shape=[2], dtype=dtypes.float32, default_value=[0.0, 0.0]),
"var_len_int":
parsing_ops.VarLenFeature(dtype=dtypes.int64)
}
tensorflow_df = df.TensorFlowDataFrame.from_examples(
data_path,
enqueue_size=enqueue_size,
batch_size=batch_size,
features=features,
shuffle=False)
# `test.tfrecord` contains 100 records with two features: var_len_int and
# fixed_len_float. Entry n contains `range(n % 3)` and
# `float(n)` for var_len_int and fixed_len_float,
# respectively.
num_records = 100
def _expected_fixed_len_float(n):
return np.array([float(n), 2 * float(n)])
def _expected_var_len_int(n):
return np.arange(n % 3)
for batch_num, batch in enumerate(tensorflow_df.run(num_batches)):
record_numbers = [
n % num_records
for n in range(batch_num * batch_size, (batch_num + 1) * batch_size)
]
for i, j in enumerate(record_numbers):
np.testing.assert_allclose(
_expected_fixed_len_float(j), batch["fixed_len_float"][i])
var_len_int = batch["var_len_int"]
for i, ind in enumerate(var_len_int.indices):
val = var_len_int.values[i]
expected_row = _expected_var_len_int(record_numbers[ind[0]])
expected_value = expected_row[ind[1]]
np.testing.assert_array_equal(expected_value, val)
def testSplitString(self):
batch_size = 8
num_epochs = 17
expected_num_batches = (num_epochs * 100) // batch_size
data_path = self._make_test_csv()
default_values = [0, 0.0, 0, ""]
tensorflow_df = df.TensorFlowDataFrame.from_csv(
[data_path],
batch_size=batch_size,
shuffle=False,
default_values=default_values)
a, b = tensorflow_df.split("string", 0.7) # no rebatching
total_result_batches = list(tensorflow_df.run(num_epochs=num_epochs))
a_result_batches = list(a.run(num_epochs=num_epochs))
b_result_batches = list(b.run(num_epochs=num_epochs))
self.assertEqual(expected_num_batches, len(total_result_batches))
self.assertEqual(expected_num_batches, len(a_result_batches))
self.assertEqual(expected_num_batches, len(b_result_batches))
total_rows = sum([len(x["int"]) for x in total_result_batches])
a_total_rows = sum([len(x["int"]) for x in a_result_batches])
b_total_rows = sum([len(x["int"]) for x in b_result_batches])
print("Split rows: %s => %s, %s" % (total_rows, a_total_rows, b_total_rows))
# TODO(soergel): figure out how to dequeue the final small batch
expected_total_rows = 1696 # (num_epochs * 100)
self.assertEqual(expected_total_rows, total_rows)
self.assertEqual(1087, a_total_rows) # stochastic but deterministic
# self.assertEqual(int(total_rows * 0.7), a_total_rows)
self.assertEqual(609, b_total_rows) # stochastic but deterministic
# self.assertEqual(int(total_rows * 0.3), b_total_rows)
# The strings used for hashing were all unique in the original data, but
# we ran 17 epochs, so each one should appear 17 times. Each copy should
# be hashed into the same partition, so there should be no overlap of the
# keys.
a_strings = set([s for x in a_result_batches for s in x["string"]])
b_strings = set([s for x in b_result_batches for s in x["string"]])
self.assertEqual(frozenset(), a_strings & b_strings)
if __name__ == "__main__":
test.main()
| |
'''
Created on Apr 2, 2014
@author: sstober
'''
import os
import logging
log = logging.getLogger(__name__)
import numpy as np
from pylearn2.utils.timing import log_timing
from functools import wraps
import librosa
from deepthought.util.fs_util import load
from deepthought.util.timeseries_util import frame as compute_frames
from deepthought.datasets.eeg.channel_filter import NoChannelFilter
from deepthought.datasets.eeg.MultiChannelEEGDataset import load_datafiles_metadata
from pylearn2.sandbox.rnn.space import SequenceDataSpace
from pylearn2.space import VectorSpace, CompositeSpace, IndexSpace
from pylearn2.datasets.vector_spaces_dataset import VectorSpacesDataset
from pylearn2.sandbox.rnn.utils.iteration import SequenceDatasetIterator
from pylearn2.utils.iteration import resolve_iterator_class
from pylearn2.utils.rng import make_np_rng
class MultiChannelEEGSequencesDataset(VectorSpacesDataset):
"""
TODO classdocs
"""
class Like(object):
"""
Helper class for lazy people to load an MultiChannelEEGSequencesDataset with similar parameters
Note: This is quite a hack as __new__ should return instances of Like.
Instead, it returns the loaded MultiChannelEEGSequencesDataset
"""
def __new__(Like,
base, # reference to copy initialize values from
**override
):
params = base.params.copy()
log.debug("base params: {}".format(params))
log.debug("override params: {}".format(override))
for key, value in override.iteritems():
params[key] = value
log.debug("merged params: {}".format(params))
return MultiChannelEEGSequencesDataset(**params)
def __init__(self,
path,
name = '', # optional name
# selectors
subjects='all', # optional selector (list) or 'all'
trial_types='all', # optional selector (list) or 'all'
trial_numbers='all', # optional selector (list) or 'all'
conditions='all', # optional selector (list) or 'all'
partitioner = None,
channel_filter = NoChannelFilter(), # optional channel filter, default: keep all
channel_names = None, # optional channel names (for metadata)
label_map = None, # optional conversion of labels
remove_dc_offset = False, # optional subtraction of channel mean, usually done already earlier
resample = None, # optional down-sampling
# optional sub-sequences selection
start_sample = 0,
stop_sample = None, # optional for selection of sub-sequences
# optional signal filter to by applied before spitting the signal
signal_filter = None,
# windowing parameters
frame_size = -1,
hop_size = -1, # values > 0 will lead to windowing
hop_fraction = None, # alternative to specifying absolute hop_size
# # optional spectrum parameters, n_fft = 0 keeps raw data
# n_fft = 0,
# n_freq_bins = None,
# spectrum_log_amplitude = False,
# spectrum_normalization_mode = None,
# include_phase = False,
flatten_channels=False,
# layout='tf', # (0,1)-axes layout tf=time x features or ft=features x time
# save_matrix_path = None,
keep_metadata = False,
target_mode='label',
):
'''
Constructor
'''
# save params
self.params = locals().copy()
del self.params['self']
# print self.params
# TODO: get the whole filtering into an extra class
datafiles_metadata, metadb = load_datafiles_metadata(path)
# print datafiles_metadata
def apply_filters(filters, node):
if isinstance(node, dict):
filtered = []
keepkeys = filters[0]
for key, value in node.items():
if keepkeys == 'all' or key in keepkeys:
filtered.extend(apply_filters(filters[1:], value))
return filtered
else:
return node # [node]
# keep only files that match the metadata filters
self.datafiles = apply_filters([subjects,trial_types,trial_numbers,conditions], datafiles_metadata)
# copy metadata for retained files
self.metadb = {}
for datafile in self.datafiles:
self.metadb[datafile] = metadb[datafile]
# print self.datafiles
# print self.metadb
self.name = name
if partitioner is not None:
self.datafiles = partitioner.get_partition(self.name, self.metadb)
# self.include_phase = include_phase
# self.spectrum_normalization_mode = spectrum_normalization_mode
# self.spectrum_log_amplitude = spectrum_log_amplitude
self.sequence_partitions = [] # used to keep track of original sequences
# metadata: [subject, trial_no, stimulus, channel, start, ]
self.metadata = []
sequences = []
labels = []
targets = []
n_sequences = 0
print hop_size
if frame_size > 0 and hop_size == -1 and hop_fraction is not None:
hop_size = np.ceil(frame_size / hop_fraction)
print hop_size
if target_mode == 'next':
# get 1 more value per frame as target
frame_size += 1
# print 'frame size: {}'.format(frame_size)
for i in xrange(len(self.datafiles)):
with log_timing(log, 'loading data from {}'.format(self.datafiles[i])):
# save start of next sequence
self.sequence_partitions.append(n_sequences)
data, metadata = load(os.path.join(path, self.datafiles[i]))
# data, metadata = self.generate_test_data()
label = metadata['label']
if label_map is not None:
label = label_map[label]
multi_channel_frames = []
multi_channel_targets = []
# process 1 channel at a time
for channel in xrange(data.shape[1]):
# filter channels
if not channel_filter.keep_channel(channel):
continue
samples = data[:, channel]
# print samples
# subtract channel mean
#FIXME
if remove_dc_offset:
samples -= samples.mean()
# down-sample if requested
if resample is not None and resample[0] != resample[1]:
samples = librosa.resample(samples, resample[0], resample[1])
# apply optional signal filter after down-sampling -> requires lower order
if signal_filter is not None:
samples = signal_filter.process(samples)
# get sub-sequence in resampled space
# log.info('using samples {}..{} of {}'.format(start_sample,stop_sample, samples.shape))
samples = samples[start_sample:stop_sample]
# print start_sample, stop_sample, samples.shape
# if n_fft is not None and n_fft > 0: # Optionally:
# ### frequency spectrum branch ###
#
# # transform to spectogram
# hop_length = n_fft / 4;
#
# '''
# from http://theremin.ucsd.edu/~bmcfee/librosadoc/librosa.html
# >>> # Get a power spectrogram from a waveform y
# >>> S = np.abs(librosa.stft(y)) ** 2
# >>> log_S = librosa.logamplitude(S)
# '''
#
# S = librosa.core.stft(samples, n_fft=n_fft, hop_length=hop_length)
# # mag = np.abs(S) # magnitude spectrum
# mag = np.abs(S)**2 # power spectrum
#
# # include phase information if requested
# if self.include_phase:
# # phase = np.unwrap(np.angle(S))
# phase = np.angle(S)
#
# # Optionally: cut off high bands
# if n_freq_bins is not None:
# mag = mag[0:n_freq_bins, :]
# if self.include_phase:
# phase = phase[0:n_freq_bins, :]
#
# if self.spectrum_log_amplitude:
# mag = librosa.logamplitude(mag)
#
# s = mag # for normalization
#
# '''
# NOTE on normalization:
# It depends on the structure of a neural network and (even more)
# on the properties of data. There is no best normalization algorithm
# because if there would be one, it would be used everywhere by default...
#
# In theory, there is no requirement for the data to be normalized at all.
# This is a purely practical thing because in practice convergence could
# take forever if your input is spread out too much. The simplest would be
# to just normalize it by scaling your data to (-1,1) (or (0,1) depending
# on activation function), and in most cases it does work. If your
# algorithm converges well, then this is your answer. If not, there are
# too many possible problems and methods to outline here without knowing
# the actual data.
# '''
#
# ## normalize to mean 0, std 1
# if self.spectrum_normalization_mode == 'mean0_std1':
# # s = preprocessing.scale(s, axis=0);
# mean = np.mean(s)
# std = np.std(s)
# s = (s - mean) / std
#
# ## normalize by linear transform to [0,1]
# elif self.spectrum_normalization_mode == 'linear_0_1':
# s = s / np.max(s)
#
# ## normalize by linear transform to [-1,1]
# elif self.spectrum_normalization_mode == 'linear_-1_1':
# s = -1 + 2 * (s - np.min(s)) / (np.max(s) - np.min(s))
#
# elif self.spectrum_normalization_mode is not None:
# raise ValueError(
# 'unsupported spectrum normalization mode {}'.format(
# self.spectrum_normalization_mode)
# )
#
# #print s.mean(axis=0)
# #print s.std(axis=0)
#
# # include phase information if requested
# if self.include_phase:
# # normalize phase to [-1.1]
# phase = phase / np.pi
# s = np.vstack([s, phase])
#
# # transpose to fit pylearn2 layout
# s = np.transpose(s)
# # print s.shape
#
# ### end of frequency spectrum branch ###
# else:
### raw waveform branch ###
# normalize to max amplitude 1
s = librosa.util.normalize(samples)
# add 2nd data dimension
# s = s.reshape(s.shape[0], 1)
# print s.shape
### end of raw waveform branch ###
s = np.asfarray(s, dtype='float32')
if frame_size > 0 and hop_size > 0:
# print 'frame size: {}'.format(frame_size)
s = s.copy() # FIXME: THIS IS NECESSARY - OTHERWISE, THE FOLLOWING OP DOES NOT WORK!!!!
frames = compute_frames(s, frame_length=frame_size, hop_length=hop_size)
# frames = librosa.util.frame(s, frame_length=frame_size, hop_length=hop_size)
else:
frames = s
del s
# print frames.shape
if target_mode == 'next':
frame_targets = np.empty(len(frames))
tmp = []
for f, frame in enumerate(frames):
tmp.append(frame[:-1])
frame_targets[f] = frame[-1]
frames = np.asarray(tmp)
# print frames.shape
# for f, frm in enumerate(frames):
# print frm, frame_targets[f]
# # FIXME: OK so far
if flatten_channels:
# add artificial channel dimension
frames = frames.reshape((frames.shape[0], frames.shape[1], frames.shape[2], 1))
# print frames.shape
sequences.append(frames)
# increment counter by new number of frames
n_sequences += frames.shape[0]
if keep_metadata:
# determine channel name
channel_name = None
if channel_names is not None:
channel_name = channel_names[channel]
elif 'channels' in metadata:
channel_name = metadata['channels'][channel]
self.metadata.append({
'subject' : metadata['subject'], # subject
'trial_type': metadata['trial_type'], # trial_type
'trial_no' : metadata['trial_no'], # trial_no
'condition' : metadata['condition'], # condition
'channel' : channel, # channel
'channel_name' : channel_name,
'start' : self.sequence_partitions[-1], # start
'stop' : n_sequences # stop
})
for _ in xrange(frames.shape[0]):
labels.append(label)
if target_mode == 'next':
for next in frame_targets:
targets.append(next)
else:
multi_channel_frames.append(frames)
if target_mode == 'next':
multi_channel_targets.append(frame_targets)
### end of channel iteration ###
# print np.asarray(multi_channel_frames, dtype=np.int)
# # FIXME: OK so far
if not flatten_channels:
# turn list into array
multi_channel_frames = np.asfarray(multi_channel_frames, dtype='float32')
# [channels x frames x time x freq] -> cb01
# [channels x frames x time x 1] -> cb0.
# move channel dimension to end
multi_channel_frames = np.rollaxis(multi_channel_frames, 0, len(multi_channel_frames.shape))
# print multi_channel_frames.shape
log.info(multi_channel_frames.shape)
sequences.append(multi_channel_frames)
# increment counter by new number of frames
n_sequences += multi_channel_frames.shape[0]
if keep_metadata:
self.metadata.append({
'subject' : metadata['subject'], # subject
'trial_type': metadata['trial_type'], # trial_type
'trial_no' : metadata['trial_no'], # trial_no
'condition' : metadata['condition'], # condition
'channel' : 'all', # channel
'start' : self.sequence_partitions[-1], # start
'stop' : n_sequences # stop
})
for _ in xrange(multi_channel_frames.shape[0]):
labels.append(label)
if target_mode == 'next':
multi_channel_targets = np.asfarray(multi_channel_targets, dtype='float32')
targets.append(multi_channel_targets.T)
### end of datafile iteration ###
# print sequences[0].shape
# print np.asarray(sequences[0], dtype=np.int)
# # FIXME: looks OK
# turn into numpy arrays
sequences = np.vstack(sequences)
# sequences = np.asarray(sequences).squeeze()
# sequences = sequences.reshape(sequences.shape[0]*sequences.shape[1], sequences.shape[2])
print 'sequences: {}'.format(sequences.shape)
labels = np.hstack(labels)
self.labels = labels
print 'labels: {}'.format(labels.shape)
if target_mode == 'label':
targets = labels.copy()
## copy targets to fit SequenceDataSpace(VectorSpace) structure (*, frame_size, 12)
# targets = targets.reshape((targets.shape[0], 1))
# targets = np.repeat(targets, frame_size, axis=1)
# print targets.shape
# one_hot_formatter = OneHotFormatter(max(targets.max() + 1, len(label_map)), dtype=np.int)
# one_hot_y = one_hot_formatter.format(targets)
# print one_hot_y.shape
## copy targets to fit SequenceDataSpace(IndexSpace) structure -> (*, frame_size, 1)
targets = targets.reshape((targets.shape[0], 1))
targets = np.repeat(targets, frame_size, axis=1)
targets = targets.reshape((targets.shape[0], targets.shape[1], 1))
print targets.shape
elif target_mode == 'next':
targets = np.concatenate(targets)
targets = targets.reshape((targets.shape[0], 1, targets.shape[1]))
print 'targets: {}'.format(targets.shape)
n_channels = sequences.shape[2]
print 'number of channels: {}'.format(n_channels)
# if layout == 'ft': # swap axes to (batch, feature, time, channels)
# sequences = sequences.swapaxes(1, 2)
log.debug('final dataset shape: {} (b,0,1,c)'.format(sequences.shape))
source = ('features', 'targets')
# space = CompositeSpace([
# # VectorSequenceSpace(dim=64),
# SequenceSpace(VectorSpace(dim=64)),
# VectorSpace(dim=12),
# ])
if target_mode == 'label':
space = CompositeSpace([
SequenceDataSpace(VectorSpace(dim=n_channels)),
# SequenceDataSpace(VectorSpace(dim=12)),
SequenceDataSpace(IndexSpace(dim=1, max_labels=12)),
# SequenceDataSpace(IndexSpace(dim=512, max_labels=12)),
])
elif target_mode == 'next':
space = CompositeSpace([
# does not work with VectorSpacesDataset
# SequenceSpace(VectorSpace(dim=64)),
# SequenceSpace(VectorSpace(dim=64))
SequenceDataSpace(VectorSpace(dim=n_channels)),
SequenceDataSpace(VectorSpace(dim=n_channels))
# VectorSpace(dim=n_channels)
])
# source = ('features')
# space = SequenceSpace(VectorSpace(dim=64))
print 'sequences: {}'.format(sequences.shape)
print 'targets: {}'.format(targets.shape)
# for i, seq in enumerate(sequences):
# print np.asarray(seq, dtype=np.int)
# print np.asarray(targets[i], dtype=np.int)
# break
# # FIXME: looks OK
# SequenceDataSpace(IndexSpace(dim=1, max_labels=self._max_labels)),
if target_mode == 'label':
super(MultiChannelEEGSequencesDataset, self).__init__(
# data=(sequences, one_hot_y), # works with vectorspace-target
data=(sequences, targets), # works with indexspace-target
# data=sequences,
data_specs=(space, source)
)
elif target_mode == 'next':
super(MultiChannelEEGSequencesDataset, self).__init__(
# data=(sequences, one_hot_y), # works with vectorspace-target
data=(sequences, targets), # works with indexspace-target
# data=sequences,
data_specs=(space, source)
)
# super(MultiChannelEEGSequencesDataset, self).__init__(topo_view=sequences, y=one_hot_y, axes=['b', 0, 1, 'c'])
# log.info('generated dataset "{}" with shape X={}={} y={} labels={} '.
# format(self.name, self.X.shape, sequences.shape, self.y.shape, self.labels.shape))
# if save_matrix_path is not None:
# matrix = DenseDesignMatrix(topo_view=sequences, y=one_hot_y, axes=['b', 0, 1, 'c'])
# with log_timing(log, 'saving DenseDesignMatrix to {}'.format(save_matrix_path)):
# serial.save(save_matrix_path, matrix)
### copied from PennTreebankSequences - otherwise monitor complains about dataset size change ###
def _create_subset_iterator(self, mode, batch_size=None, num_batches=None,
rng=None):
subset_iterator = resolve_iterator_class(mode)
if rng is None and subset_iterator.stochastic:
rng = make_np_rng()
return subset_iterator(self.get_num_examples(), batch_size,
num_batches, rng)
### copied from PennTreebankSequences - otherwise monitor complains about dataset size change ###
@wraps(VectorSpacesDataset.iterator)
def iterator(self, batch_size=None, num_batches=None, rng=None,
data_specs=None, return_tuple=False, mode='sequential'):
subset_iterator = self._create_subset_iterator(
mode=mode, batch_size=batch_size, num_batches=num_batches, rng=rng
)
# This should be fixed to allow iteration with default data_specs
# i.e. add a mask automatically maybe?
return SequenceDatasetIterator(self, data_specs, subset_iterator,
return_tuple=return_tuple)
def generate_test_data(self):
data = np.empty((50,68), dtype=np.float32)
for c in xrange(68):
for t in xrange(50):
data[t,c] = 100*c + t
print data[:10,c]
metadata = {
'label': 1
}
return data, metadata
| |
import json
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
from django.conf import settings
from django.shortcuts import render, redirect, get_object_or_404, reverse
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from django.views import generic
from foraliving.views import createInputToken
from .forms import *
from foraliving.models import Volunteer_User_Add_Ons, Interview, Interview_Question_Video_Map, Interview_Question_Map
from mail_templated import EmailMessage
class VolunteerProfile(LoginRequiredMixin, generic.View):
"""Generic view to display the volunteer profile,
this will be shown after login success"""
login_url = settings.LOGIN_URL
question_view = 'volunteer/profile.html'
def get(self, request, user_id, interview_id):
"""
Method to render the template with the videos and information of the volunteer
:param request:
:param user_id:
:param interview_id:
:return:
"""
class_id = request.GET.get("class")
assignment = request.GET.get("assignment")
volunteer = Volunteer_User_Add_Ons.objects.get(user=user_id)
interview = Interview.objects.filter(interviewee=user_id)
interview_question = Interview_Question_Map.objects.filter(interview__in=interview)
interview_question_video = Interview_Question_Video_Map.objects.filter(
interview_question__in=interview_question, video__status="approved").order_by('-video')
user = User.objects.get(id=request.user.id)
user_type = User_Type.objects.get(user=user)
return render(request, self.question_view,
{'volunteer': volunteer, 'interview': interview_id, 'videos': interview_question_video,
'user_type': user_type.type.name, 'class_id': class_id, 'assignment': assignment})
class Contact(LoginRequiredMixin, generic.View):
"""Generic view to display the volunteer profile,
this will be shown after login success"""
contact_view = 'volunteer/contact.html'
login_url = settings.LOGIN_URL
def get(self, request):
if request.user.is_superuser:
return render(request, self.contact_view)
else:
return redirect(self.login_url)
def post(self, request):
if request.method == 'POST':
email = request.POST.get("email")
first_name = request.POST.get("first_name")
last_name = request.POST.get("last_name")
phone = request.POST.get("phone")
workTitle = request.POST.get("work_title")
if email == "":
messages.error(request, "Email is required.")
elif first_name == "":
messages.error(request, "First Name is required.")
elif last_name == "":
messages.error(request, "Last Name is required.")
else:
email_to = email
domain = request.build_absolute_uri('/')[:-1]
url = domain + "/volunteer/create/?email=" + email_to + "&phone=" + phone + "&workTitle=" + workTitle + "&first_name=" + first_name + "&last_name=" + last_name;
message = EmailMessage('volunteer/invitation.html',
{'url': url, 'first_name': first_name, 'last_name': last_name, 'phone': phone,
'workTitle': workTitle},
"noelia.pazos@viaro.net", cc=["jacquie@foraliving.org"],
to=[email_to])
message.send()
messages.success(request, "Invitation Sent Successfully")
return redirect(self.contact_view)
class VolunteerEdit(LoginRequiredMixin, generic.View):
"""
Class to edit the volunteer information
"""
url_volunteer_edit = 'volunteer/profile_edit.html'
url_volunteer_list = 'volunteer_profile'
login_url = settings.LOGIN_URL
def get(self, request, user_id):
"""
Return the volunteer information to edit the profile.
"""
user = User.objects.get(pk=request.user.id)
volunteer_user = User.objects.get(pk=user_id)
if user.id == volunteer_user.id:
volunteer = get_object_or_404(Volunteer_User_Add_Ons, user=user_id)
infoForm = volunteerSignupForm(instance=volunteer)
return render(
request,
self.url_volunteer_edit,
{
'infoForm': infoForm,
'user_id': volunteer.user.id,
'volunteer': volunteer
}
)
else:
return redirect(self.login_url)
def post(self, request, user_id):
"""
Method to receive the profile information that the user want to edit.
"""
volunteer = get_object_or_404(Volunteer_User_Add_Ons, user=user_id)
volunteer_form = volunteerSignupForm(request.POST, instance=volunteer)
if not volunteer_form.is_valid():
return render(
request,
self.url_volunteer_edit,
{
'infoForm': volunteer_form,
'user_id': volunteer.user.id
}
)
volunteer_form.save()
messages.success(request, "Profile Edited Successfully")
return HttpResponse(volunteer.id)
def editSkill(request, volunteer_id):
"""Method to edit skills and interests"""
if request.method == 'POST':
volunteer = Volunteer_User_Add_Ons.objects.get(pk=volunteer_id)
for data in volunteer.skills.all():
volunteer.skills.remove(data)
for data in volunteer.interests.all():
volunteer.interests.remove(data)
skills = request.POST.getlist('skills')
interests = request.POST.getlist('interests')
# call to save the skills
createInputToken(request, skills, 'Skill', volunteer_id)
# call to save the interests
createInputToken(request, interests, 'Interest', volunteer_id)
return HttpResponse('ok')
class GetInterviewed(LoginRequiredMixin, generic.View):
"""
This view will show the list of pending interview for a volunteer
"""
template = 'volunteer/get_interviewed.html'
def get(self, request):
# First of all we get the pending interviews of the volunteer
interviews = Interview.objects.filter(interviewee=request.user)
return_data = []
for interview in interviews:
# We get all students assigned to interverview.assignment class
# that belongs to the interview.group
students = Student_Class.objects.filter(falClass=interview.assignment.falClass)
users = interview.group.user_set.all()
students_class_group = self.get_students_group(students, users)
# We want to return the username-firstname of each student
user_names = ''
group_name = interview.group
if (len(students_class_group) == 0):
continue
# This is the general case (more than one student)
if (len(students_class_group) > 1):
cont = 0
for user in students_class_group:
user_names += user.first_name
if not (cont == (len(users) - 1)):
user_names += ', '
cont += 1
# This is the base case (Just one student)
else:
user_names = students_class_group[0].first_name
return_data.append(
{
'interview': interview,
'group_users': user_names,
'group_name': group_name
}
)
return render(
request,
self.template,
{'interviews_data': return_data}
)
def get_students_group(self, students=[], group=[]):
students_in_group = []
for student in students:
if student.student in group:
students_in_group.append(student.student)
return students_in_group
class InterviewQuestionsView(LoginRequiredMixin, generic.View):
"""
This view will show the questions of an Interview (previously selected)
"""
template = 'volunteer/interview_questions.html'
def get(self, request, interview_id):
# We get the Interview if exists
interview = get_object_or_404(Interview, pk=interview_id)
# We search the questions of the interview
questions = Interview_Question_Map.objects.filter(interview=interview)
return render(
request,
self.template,
{
'interview_questions': questions,
'group_name': interview.group
}
)
return questions
class JoinInterviewView(LoginRequiredMixin, generic.View):
"""
This wiew will manage the remote connection of an interview
"""
template = 'volunteer/join_interview.html'
def get(self, request, interview_id):
# We get the Interview if exists
interview = get_object_or_404(Interview, pk=interview_id)
# We search the questions of the interview
questions = Interview_Question_Map.objects.filter(interview=interview)
data = {}
for i_question in questions:
data[i_question.question.id] = i_question.question.name
return render(
request,
self.template,
{
'interview_questions': questions,
'questions_array': data
}
)
class GetQuestionFromInterviewQuestion(LoginRequiredMixin, generic.View):
"""
Get the GPG key for customer
"""
def get(self, request, question_id):
interview_question = get_object_or_404(Interview_Question_Map, pk=question_id)
return JsonResponse(interview_question.question.name, safe=False)
| |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Grid Dynamics
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
import fixtures
from oslo.config import cfg
from nova import exception
from nova.openstack.common import uuidutils
from nova import test
from nova.tests import fake_processutils
from nova.tests.virt.libvirt import fake_libvirt_utils
from nova.virt.libvirt import imagebackend
CONF = cfg.CONF
class _ImageTestCase(object):
INSTANCES_PATH = '/instances_path'
def mock_create_image(self, image):
def create_image(fn, base, size, *args, **kwargs):
fn(target=base, *args, **kwargs)
image.create_image = create_image
def setUp(self):
super(_ImageTestCase, self).setUp()
self.flags(disable_process_locking=True,
instances_path=self.INSTANCES_PATH)
self.INSTANCE = {'name': 'instance',
'uuid': uuidutils.generate_uuid()}
self.NAME = 'fake.vm'
self.TEMPLATE = 'template'
self.OLD_STYLE_INSTANCE_PATH = \
fake_libvirt_utils.get_instance_path(self.INSTANCE, forceold=True)
self.PATH = os.path.join(
fake_libvirt_utils.get_instance_path(self.INSTANCE), self.NAME)
# TODO(mikal): rename template_dir to base_dir and template_path
# to cached_image_path. This will be less confusing.
self.TEMPLATE_DIR = os.path.join(CONF.instances_path, '_base')
self.TEMPLATE_PATH = os.path.join(self.TEMPLATE_DIR, 'template')
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.imagebackend.libvirt_utils',
fake_libvirt_utils))
def test_cache(self):
self.mox.StubOutWithMock(os.path, 'exists')
if self.OLD_STYLE_INSTANCE_PATH:
os.path.exists(self.OLD_STYLE_INSTANCE_PATH).AndReturn(False)
os.path.exists(self.TEMPLATE_DIR).AndReturn(False)
os.path.exists(self.PATH).AndReturn(False)
os.path.exists(self.TEMPLATE_PATH).AndReturn(False)
fn = self.mox.CreateMockAnything()
fn(target=self.TEMPLATE_PATH)
self.mox.StubOutWithMock(imagebackend.fileutils, 'ensure_tree')
imagebackend.fileutils.ensure_tree(self.TEMPLATE_DIR)
self.mox.ReplayAll()
image = self.image_class(self.INSTANCE, self.NAME)
self.mock_create_image(image)
image.cache(fn, self.TEMPLATE)
self.mox.VerifyAll()
def test_cache_image_exists(self):
self.mox.StubOutWithMock(os.path, 'exists')
if self.OLD_STYLE_INSTANCE_PATH:
os.path.exists(self.OLD_STYLE_INSTANCE_PATH).AndReturn(False)
os.path.exists(self.TEMPLATE_DIR).AndReturn(True)
os.path.exists(self.PATH).AndReturn(True)
os.path.exists(self.TEMPLATE_PATH).AndReturn(True)
self.mox.ReplayAll()
image = self.image_class(self.INSTANCE, self.NAME)
image.cache(None, self.TEMPLATE)
self.mox.VerifyAll()
def test_cache_base_dir_exists(self):
self.mox.StubOutWithMock(os.path, 'exists')
if self.OLD_STYLE_INSTANCE_PATH:
os.path.exists(self.OLD_STYLE_INSTANCE_PATH).AndReturn(False)
os.path.exists(self.TEMPLATE_DIR).AndReturn(True)
os.path.exists(self.PATH).AndReturn(False)
os.path.exists(self.TEMPLATE_PATH).AndReturn(False)
fn = self.mox.CreateMockAnything()
fn(target=self.TEMPLATE_PATH)
self.mox.StubOutWithMock(imagebackend.fileutils, 'ensure_tree')
self.mox.ReplayAll()
image = self.image_class(self.INSTANCE, self.NAME)
self.mock_create_image(image)
image.cache(fn, self.TEMPLATE)
self.mox.VerifyAll()
def test_cache_template_exists(self):
self.mox.StubOutWithMock(os.path, 'exists')
if self.OLD_STYLE_INSTANCE_PATH:
os.path.exists(self.OLD_STYLE_INSTANCE_PATH).AndReturn(False)
os.path.exists(self.TEMPLATE_DIR).AndReturn(True)
os.path.exists(self.PATH).AndReturn(False)
os.path.exists(self.TEMPLATE_PATH).AndReturn(True)
fn = self.mox.CreateMockAnything()
self.mox.ReplayAll()
image = self.image_class(self.INSTANCE, self.NAME)
self.mock_create_image(image)
image.cache(fn, self.TEMPLATE)
self.mox.VerifyAll()
def test_prealloc_image(self):
CONF.set_override('preallocate_images', 'space')
fake_processutils.fake_execute_clear_log()
fake_processutils.stub_out_processutils_execute(self.stubs)
image = self.image_class(self.INSTANCE, self.NAME)
def fake_fetch(target, *args, **kwargs):
return
self.stubs.Set(os.path, 'exists', lambda _: True)
# Call twice to verify testing fallocate is only called once.
image.cache(fake_fetch, self.TEMPLATE_PATH, self.SIZE)
image.cache(fake_fetch, self.TEMPLATE_PATH, self.SIZE)
self.assertEqual(fake_processutils.fake_execute_get_log(),
['fallocate -n -l 1 %s.fallocate_test' % self.PATH,
'fallocate -n -l %s %s' % (self.SIZE, self.PATH),
'fallocate -n -l %s %s' % (self.SIZE, self.PATH)])
class RawTestCase(_ImageTestCase, test.TestCase):
SIZE = 1024
def setUp(self):
self.image_class = imagebackend.Raw
super(RawTestCase, self).setUp()
self.stubs.Set(imagebackend.Raw, 'correct_format', lambda _: None)
def prepare_mocks(self):
fn = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(imagebackend.utils.synchronized,
'__call__')
self.mox.StubOutWithMock(imagebackend.libvirt_utils, 'copy_image')
self.mox.StubOutWithMock(imagebackend.disk, 'extend')
return fn
def test_create_image(self):
fn = self.prepare_mocks()
fn(target=self.TEMPLATE_PATH, image_id=None)
imagebackend.libvirt_utils.copy_image(self.TEMPLATE_PATH, self.PATH)
self.mox.ReplayAll()
image = self.image_class(self.INSTANCE, self.NAME)
image.create_image(fn, self.TEMPLATE_PATH, None, image_id=None)
self.mox.VerifyAll()
def test_create_image_generated(self):
fn = self.prepare_mocks()
fn(target=self.PATH)
self.mox.ReplayAll()
image = self.image_class(self.INSTANCE, self.NAME)
image.create_image(fn, self.TEMPLATE_PATH, None)
self.mox.VerifyAll()
def test_create_image_extend(self):
fn = self.prepare_mocks()
fn(target=self.TEMPLATE_PATH, image_id=None)
imagebackend.libvirt_utils.copy_image(self.TEMPLATE_PATH, self.PATH)
imagebackend.disk.extend(self.PATH, self.SIZE)
self.mox.ReplayAll()
image = self.image_class(self.INSTANCE, self.NAME)
image.create_image(fn, self.TEMPLATE_PATH, self.SIZE, image_id=None)
self.mox.VerifyAll()
def test_correct_format(self):
info = self.mox.CreateMockAnything()
self.stubs.UnsetAll()
self.mox.StubOutWithMock(os.path, 'exists')
self.mox.StubOutWithMock(imagebackend.images, 'qemu_img_info')
os.path.exists(self.PATH).AndReturn(True)
info = self.mox.CreateMockAnything()
info.file_format = 'foo'
imagebackend.images.qemu_img_info(self.PATH).AndReturn(info)
self.mox.ReplayAll()
image = self.image_class(self.INSTANCE, self.NAME, path=self.PATH)
self.assertEqual(image.driver_format, 'foo')
self.mox.VerifyAll()
class Qcow2TestCase(_ImageTestCase, test.TestCase):
SIZE = 1024 * 1024 * 1024
def setUp(self):
self.image_class = imagebackend.Qcow2
super(Qcow2TestCase, self).setUp()
self.QCOW2_BASE = (self.TEMPLATE_PATH +
'_%d' % (self.SIZE / (1024 * 1024 * 1024)))
def prepare_mocks(self):
fn = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(imagebackend.utils.synchronized,
'__call__')
self.mox.StubOutWithMock(imagebackend.libvirt_utils,
'create_cow_image')
self.mox.StubOutWithMock(imagebackend.libvirt_utils, 'copy_image')
self.mox.StubOutWithMock(imagebackend.disk, 'extend')
return fn
def test_create_image(self):
fn = self.prepare_mocks()
fn(target=self.TEMPLATE_PATH)
imagebackend.libvirt_utils.create_cow_image(self.TEMPLATE_PATH,
self.PATH)
self.mox.ReplayAll()
image = self.image_class(self.INSTANCE, self.NAME)
image.create_image(fn, self.TEMPLATE_PATH, None)
self.mox.VerifyAll()
def test_create_image_with_size(self):
fn = self.prepare_mocks()
fn(target=self.TEMPLATE_PATH)
self.mox.StubOutWithMock(os.path, 'exists')
self.mox.StubOutWithMock(imagebackend.disk, 'get_disk_size')
if self.OLD_STYLE_INSTANCE_PATH:
os.path.exists(self.OLD_STYLE_INSTANCE_PATH).AndReturn(False)
os.path.exists(self.TEMPLATE_PATH).AndReturn(False)
os.path.exists(self.PATH).AndReturn(False)
imagebackend.disk.get_disk_size(self.TEMPLATE_PATH
).AndReturn(self.SIZE)
os.path.exists(self.PATH).AndReturn(False)
imagebackend.libvirt_utils.create_cow_image(self.TEMPLATE_PATH,
self.PATH)
imagebackend.disk.extend(self.PATH, self.SIZE)
self.mox.ReplayAll()
image = self.image_class(self.INSTANCE, self.NAME)
image.create_image(fn, self.TEMPLATE_PATH, self.SIZE)
self.mox.VerifyAll()
def test_create_image_too_small(self):
fn = self.prepare_mocks()
fn(target=self.TEMPLATE_PATH)
self.mox.StubOutWithMock(os.path, 'exists')
self.mox.StubOutWithMock(imagebackend.disk, 'get_disk_size')
if self.OLD_STYLE_INSTANCE_PATH:
os.path.exists(self.OLD_STYLE_INSTANCE_PATH).AndReturn(False)
os.path.exists(self.TEMPLATE_PATH).AndReturn(False)
os.path.exists(self.PATH).AndReturn(False)
imagebackend.disk.get_disk_size(self.TEMPLATE_PATH
).AndReturn(self.SIZE)
self.mox.ReplayAll()
image = self.image_class(self.INSTANCE, self.NAME)
self.assertRaises(exception.InstanceTypeDiskTooSmall,
image.create_image, fn, self.TEMPLATE_PATH, 1)
self.mox.VerifyAll()
def test_generate_resized_backing_files(self):
fn = self.prepare_mocks()
fn(target=self.TEMPLATE_PATH)
self.mox.StubOutWithMock(os.path, 'exists')
self.mox.StubOutWithMock(imagebackend.disk, 'get_disk_size')
self.mox.StubOutWithMock(imagebackend.libvirt_utils,
'get_disk_backing_file')
if self.OLD_STYLE_INSTANCE_PATH:
os.path.exists(self.OLD_STYLE_INSTANCE_PATH).AndReturn(False)
os.path.exists(self.TEMPLATE_PATH).AndReturn(False)
os.path.exists(self.PATH).AndReturn(True)
imagebackend.libvirt_utils.get_disk_backing_file(self.PATH)\
.AndReturn(self.QCOW2_BASE)
os.path.exists(self.QCOW2_BASE).AndReturn(False)
imagebackend.libvirt_utils.copy_image(self.TEMPLATE_PATH,
self.QCOW2_BASE)
imagebackend.disk.extend(self.QCOW2_BASE, self.SIZE)
imagebackend.disk.get_disk_size(self.TEMPLATE_PATH
).AndReturn(self.SIZE)
os.path.exists(self.PATH).AndReturn(True)
self.mox.ReplayAll()
image = self.image_class(self.INSTANCE, self.NAME)
image.create_image(fn, self.TEMPLATE_PATH, self.SIZE)
self.mox.VerifyAll()
class LvmTestCase(_ImageTestCase, test.TestCase):
VG = 'FakeVG'
TEMPLATE_SIZE = 512
SIZE = 1024
def setUp(self):
self.image_class = imagebackend.Lvm
super(LvmTestCase, self).setUp()
self.flags(libvirt_images_volume_group=self.VG)
self.LV = '%s_%s' % (self.INSTANCE['name'], self.NAME)
self.OLD_STYLE_INSTANCE_PATH = None
self.PATH = os.path.join('/dev', self.VG, self.LV)
self.disk = imagebackend.disk
self.utils = imagebackend.utils
self.libvirt_utils = imagebackend.libvirt_utils
def prepare_mocks(self):
fn = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(self.disk, 'resize2fs')
self.mox.StubOutWithMock(self.libvirt_utils, 'create_lvm_image')
self.mox.StubOutWithMock(self.disk, 'get_disk_size')
self.mox.StubOutWithMock(self.utils, 'execute')
return fn
def _create_image(self, sparse):
fn = self.prepare_mocks()
fn(target=self.TEMPLATE_PATH)
self.libvirt_utils.create_lvm_image(self.VG,
self.LV,
self.TEMPLATE_SIZE,
sparse=sparse)
self.disk.get_disk_size(self.TEMPLATE_PATH
).AndReturn(self.TEMPLATE_SIZE)
cmd = ('qemu-img', 'convert', '-O', 'raw', self.TEMPLATE_PATH,
self.PATH)
self.utils.execute(*cmd, run_as_root=True)
self.mox.ReplayAll()
image = self.image_class(self.INSTANCE, self.NAME)
image.create_image(fn, self.TEMPLATE_PATH, None)
self.mox.VerifyAll()
def _create_image_generated(self, sparse):
fn = self.prepare_mocks()
self.libvirt_utils.create_lvm_image(self.VG, self.LV,
self.SIZE, sparse=sparse)
fn(target=self.PATH, ephemeral_size=None)
self.mox.ReplayAll()
image = self.image_class(self.INSTANCE, self.NAME)
image.create_image(fn, self.TEMPLATE_PATH,
self.SIZE, ephemeral_size=None)
self.mox.VerifyAll()
def _create_image_resize(self, sparse):
fn = self.prepare_mocks()
fn(target=self.TEMPLATE_PATH)
self.libvirt_utils.create_lvm_image(self.VG, self.LV,
self.SIZE, sparse=sparse)
self.disk.get_disk_size(self.TEMPLATE_PATH
).AndReturn(self.TEMPLATE_SIZE)
cmd = ('qemu-img', 'convert', '-O', 'raw', self.TEMPLATE_PATH,
self.PATH)
self.utils.execute(*cmd, run_as_root=True)
self.disk.resize2fs(self.PATH, run_as_root=True)
self.mox.ReplayAll()
image = self.image_class(self.INSTANCE, self.NAME)
image.create_image(fn, self.TEMPLATE_PATH, self.SIZE)
self.mox.VerifyAll()
def test_create_image(self):
self._create_image(False)
def test_create_image_sparsed(self):
self.flags(libvirt_sparse_logical_volumes=True)
self._create_image(True)
def test_create_image_generated(self):
self._create_image_generated(False)
def test_create_image_generated_sparsed(self):
self.flags(libvirt_sparse_logical_volumes=True)
self._create_image_generated(True)
def test_create_image_resize(self):
self._create_image_resize(False)
def test_create_image_resize_sparsed(self):
self.flags(libvirt_sparse_logical_volumes=True)
self._create_image_resize(True)
def test_create_image_negative(self):
fn = self.prepare_mocks()
fn(target=self.TEMPLATE_PATH)
self.libvirt_utils.create_lvm_image(self.VG,
self.LV,
self.SIZE,
sparse=False
).AndRaise(RuntimeError())
self.disk.get_disk_size(self.TEMPLATE_PATH
).AndReturn(self.TEMPLATE_SIZE)
self.mox.StubOutWithMock(self.libvirt_utils, 'remove_logical_volumes')
self.libvirt_utils.remove_logical_volumes(self.PATH)
self.mox.ReplayAll()
image = self.image_class(self.INSTANCE, self.NAME)
self.assertRaises(RuntimeError, image.create_image, fn,
self.TEMPLATE_PATH, self.SIZE)
self.mox.VerifyAll()
def test_create_image_generated_negative(self):
fn = self.prepare_mocks()
fn(target=self.PATH,
ephemeral_size=None).AndRaise(RuntimeError())
self.libvirt_utils.create_lvm_image(self.VG,
self.LV,
self.SIZE,
sparse=False)
self.mox.StubOutWithMock(self.libvirt_utils, 'remove_logical_volumes')
self.libvirt_utils.remove_logical_volumes(self.PATH)
self.mox.ReplayAll()
image = self.image_class(self.INSTANCE, self.NAME)
self.assertRaises(RuntimeError, image.create_image, fn,
self.TEMPLATE_PATH, self.SIZE,
ephemeral_size=None)
self.mox.VerifyAll()
def test_prealloc_image(self):
CONF.set_override('preallocate_images', 'space')
fake_processutils.fake_execute_clear_log()
fake_processutils.stub_out_processutils_execute(self.stubs)
image = self.image_class(self.INSTANCE, self.NAME)
def fake_fetch(target, *args, **kwargs):
return
self.stubs.Set(os.path, 'exists', lambda _: True)
image.cache(fake_fetch, self.TEMPLATE_PATH, self.SIZE)
self.assertEqual(fake_processutils.fake_execute_get_log(), [])
class BackendTestCase(test.TestCase):
INSTANCE = {'name': 'fake-instance',
'uuid': uuidutils.generate_uuid()}
NAME = 'fake-name.suffix'
def get_image(self, use_cow, image_type):
return imagebackend.Backend(use_cow).image(self.INSTANCE,
self.NAME,
image_type)
def _test_image(self, image_type, image_not_cow, image_cow):
image1 = self.get_image(False, image_type)
image2 = self.get_image(True, image_type)
def assertIsInstance(instance, class_object):
failure = ('Expected %s,' +
' but got %s.') % (class_object.__name__,
instance.__class__.__name__)
self.assertTrue(isinstance(instance, class_object), failure)
assertIsInstance(image1, image_not_cow)
assertIsInstance(image2, image_cow)
def test_image_raw(self):
self._test_image('raw', imagebackend.Raw, imagebackend.Raw)
def test_image_qcow2(self):
self._test_image('qcow2', imagebackend.Qcow2, imagebackend.Qcow2)
def test_image_lvm(self):
self.flags(libvirt_images_volume_group='FakeVG')
self._test_image('lvm', imagebackend.Lvm, imagebackend.Lvm)
def test_image_default(self):
self._test_image('default', imagebackend.Raw, imagebackend.Qcow2)
| |
"""Tests for the Google Assistant traits."""
from unittest.mock import patch, Mock
import pytest
from homeassistant.components import (
binary_sensor,
camera,
cover,
fan,
input_boolean,
light,
lock,
media_player,
scene,
script,
switch,
vacuum,
group,
)
from homeassistant.components.climate import const as climate
from homeassistant.components.google_assistant import (
trait, helpers, const, error)
from homeassistant.const import (
STATE_ON, STATE_OFF, ATTR_ENTITY_ID, SERVICE_TURN_ON, SERVICE_TURN_OFF,
TEMP_CELSIUS, TEMP_FAHRENHEIT, ATTR_SUPPORTED_FEATURES, ATTR_TEMPERATURE,
ATTR_DEVICE_CLASS, ATTR_ASSUMED_STATE, STATE_UNKNOWN)
from homeassistant.core import State, DOMAIN as HA_DOMAIN, EVENT_CALL_SERVICE
from homeassistant.util import color
from tests.common import async_mock_service, mock_coro
BASIC_CONFIG = helpers.Config(
should_expose=lambda state: True,
)
REQ_ID = 'ff36a3cc-ec34-11e6-b1a0-64510650abcf'
BASIC_DATA = helpers.RequestData(
BASIC_CONFIG,
'test-agent',
REQ_ID,
)
PIN_CONFIG = helpers.Config(
should_expose=lambda state: True,
secure_devices_pin='1234'
)
PIN_DATA = helpers.RequestData(
PIN_CONFIG,
'test-agent',
REQ_ID,
)
async def test_brightness_light(hass):
"""Test brightness trait support for light domain."""
assert helpers.get_google_type(light.DOMAIN, None) is not None
assert trait.BrightnessTrait.supported(light.DOMAIN,
light.SUPPORT_BRIGHTNESS, None)
trt = trait.BrightnessTrait(hass, State('light.bla', light.STATE_ON, {
light.ATTR_BRIGHTNESS: 243
}), BASIC_CONFIG)
assert trt.sync_attributes() == {}
assert trt.query_attributes() == {
'brightness': 95
}
events = []
hass.bus.async_listen(EVENT_CALL_SERVICE, events.append)
calls = async_mock_service(hass, light.DOMAIN, light.SERVICE_TURN_ON)
await trt.execute(
trait.COMMAND_BRIGHTNESS_ABSOLUTE, BASIC_DATA,
{'brightness': 50}, {})
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data == {
ATTR_ENTITY_ID: 'light.bla',
light.ATTR_BRIGHTNESS_PCT: 50
}
assert len(events) == 1
assert events[0].data == {
'domain': 'light',
'service': 'turn_on',
'service_data': {'brightness_pct': 50, 'entity_id': 'light.bla'}
}
async def test_camera_stream(hass):
"""Test camera stream trait support for camera domain."""
hass.config.api = Mock(base_url='http://1.1.1.1:8123')
assert helpers.get_google_type(camera.DOMAIN, None) is not None
assert trait.CameraStreamTrait.supported(camera.DOMAIN,
camera.SUPPORT_STREAM, None)
trt = trait.CameraStreamTrait(
hass, State('camera.bla', camera.STATE_IDLE, {}), BASIC_CONFIG
)
assert trt.sync_attributes() == {
'cameraStreamSupportedProtocols': [
"hls",
],
'cameraStreamNeedAuthToken': False,
'cameraStreamNeedDrmEncryption': False,
}
assert trt.query_attributes() == {}
with patch('homeassistant.components.camera.async_request_stream',
return_value=mock_coro('/api/streams/bla')):
await trt.execute(trait.COMMAND_GET_CAMERA_STREAM, BASIC_DATA, {}, {})
assert trt.query_attributes() == {
'cameraStreamAccessUrl': 'http://1.1.1.1:8123/api/streams/bla'
}
async def test_onoff_group(hass):
"""Test OnOff trait support for group domain."""
assert helpers.get_google_type(group.DOMAIN, None) is not None
assert trait.OnOffTrait.supported(group.DOMAIN, 0, None)
trt_on = trait.OnOffTrait(hass, State('group.bla', STATE_ON), BASIC_CONFIG)
assert trt_on.sync_attributes() == {}
assert trt_on.query_attributes() == {
'on': True
}
trt_off = trait.OnOffTrait(hass, State('group.bla', STATE_OFF),
BASIC_CONFIG)
assert trt_off.query_attributes() == {
'on': False
}
on_calls = async_mock_service(hass, HA_DOMAIN, SERVICE_TURN_ON)
await trt_on.execute(
trait.COMMAND_ONOFF, BASIC_DATA,
{'on': True}, {})
assert len(on_calls) == 1
assert on_calls[0].data == {
ATTR_ENTITY_ID: 'group.bla',
}
off_calls = async_mock_service(hass, HA_DOMAIN, SERVICE_TURN_OFF)
await trt_on.execute(
trait.COMMAND_ONOFF, BASIC_DATA,
{'on': False}, {})
assert len(off_calls) == 1
assert off_calls[0].data == {
ATTR_ENTITY_ID: 'group.bla',
}
async def test_onoff_input_boolean(hass):
"""Test OnOff trait support for input_boolean domain."""
assert helpers.get_google_type(input_boolean.DOMAIN, None) is not None
assert trait.OnOffTrait.supported(input_boolean.DOMAIN, 0, None)
trt_on = trait.OnOffTrait(hass, State('input_boolean.bla', STATE_ON),
BASIC_CONFIG)
assert trt_on.sync_attributes() == {}
assert trt_on.query_attributes() == {
'on': True
}
trt_off = trait.OnOffTrait(hass, State('input_boolean.bla', STATE_OFF),
BASIC_CONFIG)
assert trt_off.query_attributes() == {
'on': False
}
on_calls = async_mock_service(hass, input_boolean.DOMAIN, SERVICE_TURN_ON)
await trt_on.execute(
trait.COMMAND_ONOFF, BASIC_DATA,
{'on': True}, {})
assert len(on_calls) == 1
assert on_calls[0].data == {
ATTR_ENTITY_ID: 'input_boolean.bla',
}
off_calls = async_mock_service(hass, input_boolean.DOMAIN,
SERVICE_TURN_OFF)
await trt_on.execute(
trait.COMMAND_ONOFF, BASIC_DATA,
{'on': False}, {})
assert len(off_calls) == 1
assert off_calls[0].data == {
ATTR_ENTITY_ID: 'input_boolean.bla',
}
async def test_onoff_switch(hass):
"""Test OnOff trait support for switch domain."""
assert helpers.get_google_type(switch.DOMAIN, None) is not None
assert trait.OnOffTrait.supported(switch.DOMAIN, 0, None)
trt_on = trait.OnOffTrait(hass, State('switch.bla', STATE_ON),
BASIC_CONFIG)
assert trt_on.sync_attributes() == {}
assert trt_on.query_attributes() == {
'on': True
}
trt_off = trait.OnOffTrait(hass, State('switch.bla', STATE_OFF),
BASIC_CONFIG)
assert trt_off.query_attributes() == {
'on': False
}
on_calls = async_mock_service(hass, switch.DOMAIN, SERVICE_TURN_ON)
await trt_on.execute(
trait.COMMAND_ONOFF, BASIC_DATA,
{'on': True}, {})
assert len(on_calls) == 1
assert on_calls[0].data == {
ATTR_ENTITY_ID: 'switch.bla',
}
off_calls = async_mock_service(hass, switch.DOMAIN, SERVICE_TURN_OFF)
await trt_on.execute(
trait.COMMAND_ONOFF, BASIC_DATA,
{'on': False}, {})
assert len(off_calls) == 1
assert off_calls[0].data == {
ATTR_ENTITY_ID: 'switch.bla',
}
async def test_onoff_fan(hass):
"""Test OnOff trait support for fan domain."""
assert helpers.get_google_type(fan.DOMAIN, None) is not None
assert trait.OnOffTrait.supported(fan.DOMAIN, 0, None)
trt_on = trait.OnOffTrait(hass, State('fan.bla', STATE_ON), BASIC_CONFIG)
assert trt_on.sync_attributes() == {}
assert trt_on.query_attributes() == {
'on': True
}
trt_off = trait.OnOffTrait(hass, State('fan.bla', STATE_OFF), BASIC_CONFIG)
assert trt_off.query_attributes() == {
'on': False
}
on_calls = async_mock_service(hass, fan.DOMAIN, SERVICE_TURN_ON)
await trt_on.execute(
trait.COMMAND_ONOFF, BASIC_DATA,
{'on': True}, {})
assert len(on_calls) == 1
assert on_calls[0].data == {
ATTR_ENTITY_ID: 'fan.bla',
}
off_calls = async_mock_service(hass, fan.DOMAIN, SERVICE_TURN_OFF)
await trt_on.execute(
trait.COMMAND_ONOFF, BASIC_DATA,
{'on': False}, {})
assert len(off_calls) == 1
assert off_calls[0].data == {
ATTR_ENTITY_ID: 'fan.bla',
}
async def test_onoff_light(hass):
"""Test OnOff trait support for light domain."""
assert helpers.get_google_type(light.DOMAIN, None) is not None
assert trait.OnOffTrait.supported(light.DOMAIN, 0, None)
trt_on = trait.OnOffTrait(hass, State('light.bla', STATE_ON), BASIC_CONFIG)
assert trt_on.sync_attributes() == {}
assert trt_on.query_attributes() == {
'on': True
}
trt_off = trait.OnOffTrait(hass, State('light.bla', STATE_OFF),
BASIC_CONFIG)
assert trt_off.query_attributes() == {
'on': False
}
on_calls = async_mock_service(hass, light.DOMAIN, SERVICE_TURN_ON)
await trt_on.execute(
trait.COMMAND_ONOFF, BASIC_DATA,
{'on': True}, {})
assert len(on_calls) == 1
assert on_calls[0].data == {
ATTR_ENTITY_ID: 'light.bla',
}
off_calls = async_mock_service(hass, light.DOMAIN, SERVICE_TURN_OFF)
await trt_on.execute(
trait.COMMAND_ONOFF, BASIC_DATA,
{'on': False}, {})
assert len(off_calls) == 1
assert off_calls[0].data == {
ATTR_ENTITY_ID: 'light.bla',
}
async def test_onoff_media_player(hass):
"""Test OnOff trait support for media_player domain."""
assert helpers.get_google_type(media_player.DOMAIN, None) is not None
assert trait.OnOffTrait.supported(media_player.DOMAIN, 0, None)
trt_on = trait.OnOffTrait(hass, State('media_player.bla', STATE_ON),
BASIC_CONFIG)
assert trt_on.sync_attributes() == {}
assert trt_on.query_attributes() == {
'on': True
}
trt_off = trait.OnOffTrait(hass, State('media_player.bla', STATE_OFF),
BASIC_CONFIG)
assert trt_off.query_attributes() == {
'on': False
}
on_calls = async_mock_service(hass, media_player.DOMAIN, SERVICE_TURN_ON)
await trt_on.execute(
trait.COMMAND_ONOFF, BASIC_DATA,
{'on': True}, {})
assert len(on_calls) == 1
assert on_calls[0].data == {
ATTR_ENTITY_ID: 'media_player.bla',
}
off_calls = async_mock_service(hass, media_player.DOMAIN,
SERVICE_TURN_OFF)
await trt_on.execute(
trait.COMMAND_ONOFF, BASIC_DATA,
{'on': False}, {})
assert len(off_calls) == 1
assert off_calls[0].data == {
ATTR_ENTITY_ID: 'media_player.bla',
}
async def test_onoff_climate(hass):
"""Test OnOff trait not supported for climate domain."""
assert helpers.get_google_type(climate.DOMAIN, None) is not None
assert not trait.OnOffTrait.supported(
climate.DOMAIN, climate.SUPPORT_ON_OFF, None)
async def test_dock_vacuum(hass):
"""Test dock trait support for vacuum domain."""
assert helpers.get_google_type(vacuum.DOMAIN, None) is not None
assert trait.DockTrait.supported(vacuum.DOMAIN, 0, None)
trt = trait.DockTrait(hass, State('vacuum.bla', vacuum.STATE_IDLE),
BASIC_CONFIG)
assert trt.sync_attributes() == {}
assert trt.query_attributes() == {
'isDocked': False
}
calls = async_mock_service(hass, vacuum.DOMAIN,
vacuum.SERVICE_RETURN_TO_BASE)
await trt.execute(
trait.COMMAND_DOCK, BASIC_DATA, {}, {})
assert len(calls) == 1
assert calls[0].data == {
ATTR_ENTITY_ID: 'vacuum.bla',
}
async def test_startstop_vacuum(hass):
"""Test startStop trait support for vacuum domain."""
assert helpers.get_google_type(vacuum.DOMAIN, None) is not None
assert trait.StartStopTrait.supported(vacuum.DOMAIN, 0, None)
trt = trait.StartStopTrait(hass, State('vacuum.bla', vacuum.STATE_PAUSED, {
ATTR_SUPPORTED_FEATURES: vacuum.SUPPORT_PAUSE,
}), BASIC_CONFIG)
assert trt.sync_attributes() == {'pausable': True}
assert trt.query_attributes() == {
'isRunning': False,
'isPaused': True
}
start_calls = async_mock_service(hass, vacuum.DOMAIN,
vacuum.SERVICE_START)
await trt.execute(trait.COMMAND_STARTSTOP, BASIC_DATA, {'start': True}, {})
assert len(start_calls) == 1
assert start_calls[0].data == {
ATTR_ENTITY_ID: 'vacuum.bla',
}
stop_calls = async_mock_service(hass, vacuum.DOMAIN,
vacuum.SERVICE_STOP)
await trt.execute(
trait.COMMAND_STARTSTOP, BASIC_DATA, {'start': False}, {})
assert len(stop_calls) == 1
assert stop_calls[0].data == {
ATTR_ENTITY_ID: 'vacuum.bla',
}
pause_calls = async_mock_service(hass, vacuum.DOMAIN,
vacuum.SERVICE_PAUSE)
await trt.execute(
trait.COMMAND_PAUSEUNPAUSE, BASIC_DATA, {'pause': True}, {})
assert len(pause_calls) == 1
assert pause_calls[0].data == {
ATTR_ENTITY_ID: 'vacuum.bla',
}
unpause_calls = async_mock_service(hass, vacuum.DOMAIN,
vacuum.SERVICE_START)
await trt.execute(
trait.COMMAND_PAUSEUNPAUSE, BASIC_DATA, {'pause': False}, {})
assert len(unpause_calls) == 1
assert unpause_calls[0].data == {
ATTR_ENTITY_ID: 'vacuum.bla',
}
async def test_color_setting_color_light(hass):
"""Test ColorSpectrum trait support for light domain."""
assert helpers.get_google_type(light.DOMAIN, None) is not None
assert not trait.ColorSettingTrait.supported(light.DOMAIN, 0, None)
assert trait.ColorSettingTrait.supported(light.DOMAIN,
light.SUPPORT_COLOR, None)
trt = trait.ColorSettingTrait(hass, State('light.bla', STATE_ON, {
light.ATTR_HS_COLOR: (20, 94),
light.ATTR_BRIGHTNESS: 200,
ATTR_SUPPORTED_FEATURES: light.SUPPORT_COLOR,
}), BASIC_CONFIG)
assert trt.sync_attributes() == {
'colorModel': 'hsv'
}
assert trt.query_attributes() == {
'color': {
'spectrumHsv': {
'hue': 20,
'saturation': 0.94,
'value': 200 / 255,
}
}
}
assert trt.can_execute(trait.COMMAND_COLOR_ABSOLUTE, {
'color': {
'spectrumRGB': 16715792
}
})
calls = async_mock_service(hass, light.DOMAIN, SERVICE_TURN_ON)
await trt.execute(trait.COMMAND_COLOR_ABSOLUTE, BASIC_DATA, {
'color': {
'spectrumRGB': 1052927
}
}, {})
assert len(calls) == 1
assert calls[0].data == {
ATTR_ENTITY_ID: 'light.bla',
light.ATTR_HS_COLOR: (240, 93.725),
}
await trt.execute(trait.COMMAND_COLOR_ABSOLUTE, BASIC_DATA, {
'color': {
'spectrumHSV': {
'hue': 100,
'saturation': .50,
'value': .20,
}
}
}, {})
assert len(calls) == 2
assert calls[1].data == {
ATTR_ENTITY_ID: 'light.bla',
light.ATTR_HS_COLOR: [100, 50],
light.ATTR_BRIGHTNESS: .2 * 255,
}
async def test_color_setting_temperature_light(hass):
"""Test ColorTemperature trait support for light domain."""
assert helpers.get_google_type(light.DOMAIN, None) is not None
assert not trait.ColorSettingTrait.supported(light.DOMAIN, 0, None)
assert trait.ColorSettingTrait.supported(light.DOMAIN,
light.SUPPORT_COLOR_TEMP, None)
trt = trait.ColorSettingTrait(hass, State('light.bla', STATE_ON, {
light.ATTR_MIN_MIREDS: 200,
light.ATTR_COLOR_TEMP: 300,
light.ATTR_MAX_MIREDS: 500,
ATTR_SUPPORTED_FEATURES: light.SUPPORT_COLOR_TEMP,
}), BASIC_CONFIG)
assert trt.sync_attributes() == {
'colorTemperatureRange': {
'temperatureMinK': 2000,
'temperatureMaxK': 5000,
}
}
assert trt.query_attributes() == {
'color': {
'temperatureK': 3333
}
}
assert trt.can_execute(trait.COMMAND_COLOR_ABSOLUTE, {
'color': {
'temperature': 400
}
})
calls = async_mock_service(hass, light.DOMAIN, SERVICE_TURN_ON)
with pytest.raises(helpers.SmartHomeError) as err:
await trt.execute(trait.COMMAND_COLOR_ABSOLUTE, BASIC_DATA, {
'color': {
'temperature': 5555
}
}, {})
assert err.value.code == const.ERR_VALUE_OUT_OF_RANGE
await trt.execute(trait.COMMAND_COLOR_ABSOLUTE, BASIC_DATA, {
'color': {
'temperature': 2857
}
}, {})
assert len(calls) == 1
assert calls[0].data == {
ATTR_ENTITY_ID: 'light.bla',
light.ATTR_COLOR_TEMP: color.color_temperature_kelvin_to_mired(2857)
}
async def test_color_light_temperature_light_bad_temp(hass):
"""Test ColorTemperature trait support for light domain."""
assert helpers.get_google_type(light.DOMAIN, None) is not None
assert not trait.ColorSettingTrait.supported(light.DOMAIN, 0, None)
assert trait.ColorSettingTrait.supported(light.DOMAIN,
light.SUPPORT_COLOR_TEMP, None)
trt = trait.ColorSettingTrait(hass, State('light.bla', STATE_ON, {
light.ATTR_MIN_MIREDS: 200,
light.ATTR_COLOR_TEMP: 0,
light.ATTR_MAX_MIREDS: 500,
}), BASIC_CONFIG)
assert trt.query_attributes() == {
}
async def test_scene_scene(hass):
"""Test Scene trait support for scene domain."""
assert helpers.get_google_type(scene.DOMAIN, None) is not None
assert trait.SceneTrait.supported(scene.DOMAIN, 0, None)
trt = trait.SceneTrait(hass, State('scene.bla', scene.STATE), BASIC_CONFIG)
assert trt.sync_attributes() == {}
assert trt.query_attributes() == {}
assert trt.can_execute(trait.COMMAND_ACTIVATE_SCENE, {})
calls = async_mock_service(hass, scene.DOMAIN, SERVICE_TURN_ON)
await trt.execute(trait.COMMAND_ACTIVATE_SCENE, BASIC_DATA, {}, {})
assert len(calls) == 1
assert calls[0].data == {
ATTR_ENTITY_ID: 'scene.bla',
}
async def test_scene_script(hass):
"""Test Scene trait support for script domain."""
assert helpers.get_google_type(script.DOMAIN, None) is not None
assert trait.SceneTrait.supported(script.DOMAIN, 0, None)
trt = trait.SceneTrait(hass, State('script.bla', STATE_OFF), BASIC_CONFIG)
assert trt.sync_attributes() == {}
assert trt.query_attributes() == {}
assert trt.can_execute(trait.COMMAND_ACTIVATE_SCENE, {})
calls = async_mock_service(hass, script.DOMAIN, SERVICE_TURN_ON)
await trt.execute(trait.COMMAND_ACTIVATE_SCENE, BASIC_DATA, {}, {})
# We don't wait till script execution is done.
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data == {
ATTR_ENTITY_ID: 'script.bla',
}
async def test_temperature_setting_climate_onoff(hass):
"""Test TemperatureSetting trait support for climate domain - range."""
assert helpers.get_google_type(climate.DOMAIN, None) is not None
assert not trait.TemperatureSettingTrait.supported(climate.DOMAIN, 0, None)
assert trait.TemperatureSettingTrait.supported(
climate.DOMAIN, climate.SUPPORT_OPERATION_MODE, None)
hass.config.units.temperature_unit = TEMP_FAHRENHEIT
trt = trait.TemperatureSettingTrait(hass, State(
'climate.bla', climate.STATE_AUTO, {
ATTR_SUPPORTED_FEATURES: (
climate.SUPPORT_OPERATION_MODE | climate.SUPPORT_ON_OFF |
climate.SUPPORT_TARGET_TEMPERATURE_HIGH |
climate.SUPPORT_TARGET_TEMPERATURE_LOW),
climate.ATTR_OPERATION_MODE: climate.STATE_COOL,
climate.ATTR_OPERATION_LIST: [
climate.STATE_COOL,
climate.STATE_HEAT,
climate.STATE_AUTO,
],
climate.ATTR_MIN_TEMP: None,
climate.ATTR_MAX_TEMP: None,
}), BASIC_CONFIG)
assert trt.sync_attributes() == {
'availableThermostatModes': 'off,on,cool,heat,heatcool',
'thermostatTemperatureUnit': 'F',
}
assert trt.can_execute(trait.COMMAND_THERMOSTAT_SET_MODE, {})
calls = async_mock_service(
hass, climate.DOMAIN, SERVICE_TURN_ON)
await trt.execute(trait.COMMAND_THERMOSTAT_SET_MODE, BASIC_DATA, {
'thermostatMode': 'on',
}, {})
assert len(calls) == 1
calls = async_mock_service(
hass, climate.DOMAIN, SERVICE_TURN_OFF)
await trt.execute(trait.COMMAND_THERMOSTAT_SET_MODE, BASIC_DATA, {
'thermostatMode': 'off',
}, {})
assert len(calls) == 1
async def test_temperature_setting_climate_range(hass):
"""Test TemperatureSetting trait support for climate domain - range."""
assert helpers.get_google_type(climate.DOMAIN, None) is not None
assert not trait.TemperatureSettingTrait.supported(climate.DOMAIN, 0, None)
assert trait.TemperatureSettingTrait.supported(
climate.DOMAIN, climate.SUPPORT_OPERATION_MODE, None)
hass.config.units.temperature_unit = TEMP_FAHRENHEIT
trt = trait.TemperatureSettingTrait(hass, State(
'climate.bla', climate.STATE_AUTO, {
climate.ATTR_CURRENT_TEMPERATURE: 70,
climate.ATTR_CURRENT_HUMIDITY: 25,
ATTR_SUPPORTED_FEATURES:
climate.SUPPORT_OPERATION_MODE |
climate.SUPPORT_TARGET_TEMPERATURE_HIGH |
climate.SUPPORT_TARGET_TEMPERATURE_LOW,
climate.ATTR_OPERATION_MODE: climate.STATE_AUTO,
climate.ATTR_OPERATION_LIST: [
STATE_OFF,
climate.STATE_COOL,
climate.STATE_HEAT,
climate.STATE_AUTO,
],
climate.ATTR_TARGET_TEMP_HIGH: 75,
climate.ATTR_TARGET_TEMP_LOW: 65,
climate.ATTR_MIN_TEMP: 50,
climate.ATTR_MAX_TEMP: 80
}), BASIC_CONFIG)
assert trt.sync_attributes() == {
'availableThermostatModes': 'off,cool,heat,heatcool',
'thermostatTemperatureUnit': 'F',
}
assert trt.query_attributes() == {
'thermostatMode': 'heatcool',
'thermostatTemperatureAmbient': 21.1,
'thermostatHumidityAmbient': 25,
'thermostatTemperatureSetpointLow': 18.3,
'thermostatTemperatureSetpointHigh': 23.9,
}
assert trt.can_execute(trait.COMMAND_THERMOSTAT_TEMPERATURE_SET_RANGE, {})
assert trt.can_execute(trait.COMMAND_THERMOSTAT_SET_MODE, {})
calls = async_mock_service(
hass, climate.DOMAIN, climate.SERVICE_SET_TEMPERATURE)
await trt.execute(
trait.COMMAND_THERMOSTAT_TEMPERATURE_SET_RANGE, BASIC_DATA, {
'thermostatTemperatureSetpointHigh': 25,
'thermostatTemperatureSetpointLow': 20,
}, {})
assert len(calls) == 1
assert calls[0].data == {
ATTR_ENTITY_ID: 'climate.bla',
climate.ATTR_TARGET_TEMP_HIGH: 77,
climate.ATTR_TARGET_TEMP_LOW: 68,
}
calls = async_mock_service(
hass, climate.DOMAIN, climate.SERVICE_SET_OPERATION_MODE)
await trt.execute(trait.COMMAND_THERMOSTAT_SET_MODE, BASIC_DATA, {
'thermostatMode': 'heatcool',
}, {})
assert len(calls) == 1
assert calls[0].data == {
ATTR_ENTITY_ID: 'climate.bla',
climate.ATTR_OPERATION_MODE: climate.STATE_AUTO,
}
with pytest.raises(helpers.SmartHomeError) as err:
await trt.execute(
trait.COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT, BASIC_DATA,
{'thermostatTemperatureSetpoint': -100}, {})
assert err.value.code == const.ERR_VALUE_OUT_OF_RANGE
hass.config.units.temperature_unit = TEMP_CELSIUS
async def test_temperature_setting_climate_setpoint(hass):
"""Test TemperatureSetting trait support for climate domain - setpoint."""
assert helpers.get_google_type(climate.DOMAIN, None) is not None
assert not trait.TemperatureSettingTrait.supported(climate.DOMAIN, 0, None)
assert trait.TemperatureSettingTrait.supported(
climate.DOMAIN, climate.SUPPORT_OPERATION_MODE, None)
hass.config.units.temperature_unit = TEMP_CELSIUS
trt = trait.TemperatureSettingTrait(hass, State(
'climate.bla', climate.STATE_AUTO, {
ATTR_SUPPORTED_FEATURES: (
climate.SUPPORT_OPERATION_MODE | climate.SUPPORT_ON_OFF),
climate.ATTR_OPERATION_MODE: climate.STATE_COOL,
climate.ATTR_OPERATION_LIST: [
STATE_OFF,
climate.STATE_COOL,
],
climate.ATTR_MIN_TEMP: 10,
climate.ATTR_MAX_TEMP: 30,
ATTR_TEMPERATURE: 18,
climate.ATTR_CURRENT_TEMPERATURE: 20
}), BASIC_CONFIG)
assert trt.sync_attributes() == {
'availableThermostatModes': 'off,on,cool',
'thermostatTemperatureUnit': 'C',
}
assert trt.query_attributes() == {
'thermostatMode': 'cool',
'thermostatTemperatureAmbient': 20,
'thermostatTemperatureSetpoint': 18,
}
assert trt.can_execute(trait.COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT, {})
assert trt.can_execute(trait.COMMAND_THERMOSTAT_SET_MODE, {})
calls = async_mock_service(
hass, climate.DOMAIN, climate.SERVICE_SET_TEMPERATURE)
with pytest.raises(helpers.SmartHomeError):
await trt.execute(
trait.COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT, BASIC_DATA,
{'thermostatTemperatureSetpoint': -100}, {})
await trt.execute(
trait.COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT, BASIC_DATA,
{'thermostatTemperatureSetpoint': 19}, {})
assert len(calls) == 1
assert calls[0].data == {
ATTR_ENTITY_ID: 'climate.bla',
ATTR_TEMPERATURE: 19
}
async def test_temperature_setting_climate_setpoint_auto(hass):
"""
Test TemperatureSetting trait support for climate domain.
Setpoint in auto mode.
"""
hass.config.units.temperature_unit = TEMP_CELSIUS
trt = trait.TemperatureSettingTrait(hass, State(
'climate.bla', climate.STATE_AUTO, {
ATTR_SUPPORTED_FEATURES: (
climate.SUPPORT_OPERATION_MODE | climate.SUPPORT_ON_OFF),
climate.ATTR_OPERATION_MODE: climate.STATE_AUTO,
climate.ATTR_OPERATION_LIST: [
STATE_OFF,
climate.STATE_AUTO,
],
climate.ATTR_MIN_TEMP: 10,
climate.ATTR_MAX_TEMP: 30,
ATTR_TEMPERATURE: 18,
climate.ATTR_CURRENT_TEMPERATURE: 20
}), BASIC_CONFIG)
assert trt.sync_attributes() == {
'availableThermostatModes': 'off,on,heatcool',
'thermostatTemperatureUnit': 'C',
}
assert trt.query_attributes() == {
'thermostatMode': 'heatcool',
'thermostatTemperatureAmbient': 20,
'thermostatTemperatureSetpointHigh': 18,
'thermostatTemperatureSetpointLow': 18,
}
assert trt.can_execute(trait.COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT, {})
assert trt.can_execute(trait.COMMAND_THERMOSTAT_SET_MODE, {})
calls = async_mock_service(
hass, climate.DOMAIN, climate.SERVICE_SET_TEMPERATURE)
await trt.execute(
trait.COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT, BASIC_DATA,
{'thermostatTemperatureSetpoint': 19}, {})
assert len(calls) == 1
assert calls[0].data == {
ATTR_ENTITY_ID: 'climate.bla',
ATTR_TEMPERATURE: 19
}
async def test_lock_unlock_lock(hass):
"""Test LockUnlock trait locking support for lock domain."""
assert helpers.get_google_type(lock.DOMAIN, None) is not None
assert trait.LockUnlockTrait.supported(lock.DOMAIN, lock.SUPPORT_OPEN,
None)
trt = trait.LockUnlockTrait(hass,
State('lock.front_door', lock.STATE_UNLOCKED),
PIN_CONFIG)
assert trt.sync_attributes() == {}
assert trt.query_attributes() == {
'isLocked': False
}
assert trt.can_execute(trait.COMMAND_LOCKUNLOCK, {'lock': True})
calls = async_mock_service(hass, lock.DOMAIN, lock.SERVICE_LOCK)
# No challenge data
with pytest.raises(error.ChallengeNeeded) as err:
await trt.execute(
trait.COMMAND_LOCKUNLOCK, PIN_DATA, {'lock': True}, {})
assert len(calls) == 0
assert err.code == const.ERR_CHALLENGE_NEEDED
assert err.challenge_type == const.CHALLENGE_PIN_NEEDED
# invalid pin
with pytest.raises(error.ChallengeNeeded) as err:
await trt.execute(
trait.COMMAND_LOCKUNLOCK, PIN_DATA, {'lock': True},
{'pin': 9999})
assert len(calls) == 0
assert err.code == const.ERR_CHALLENGE_NEEDED
assert err.challenge_type == const.CHALLENGE_FAILED_PIN_NEEDED
await trt.execute(trait.COMMAND_LOCKUNLOCK, PIN_DATA, {'lock': True},
{'pin': '1234'})
assert len(calls) == 1
assert calls[0].data == {
ATTR_ENTITY_ID: 'lock.front_door'
}
async def test_lock_unlock_unlock(hass):
"""Test LockUnlock trait unlocking support for lock domain."""
assert helpers.get_google_type(lock.DOMAIN, None) is not None
assert trait.LockUnlockTrait.supported(lock.DOMAIN, lock.SUPPORT_OPEN,
None)
trt = trait.LockUnlockTrait(hass,
State('lock.front_door', lock.STATE_LOCKED),
PIN_CONFIG)
assert trt.sync_attributes() == {}
assert trt.query_attributes() == {
'isLocked': True
}
assert trt.can_execute(trait.COMMAND_LOCKUNLOCK, {'lock': False})
calls = async_mock_service(hass, lock.DOMAIN, lock.SERVICE_UNLOCK)
# No challenge data
with pytest.raises(error.ChallengeNeeded) as err:
await trt.execute(
trait.COMMAND_LOCKUNLOCK, PIN_DATA, {'lock': False}, {})
assert len(calls) == 0
assert err.code == const.ERR_CHALLENGE_NEEDED
assert err.challenge_type == const.CHALLENGE_PIN_NEEDED
# invalid pin
with pytest.raises(error.ChallengeNeeded) as err:
await trt.execute(
trait.COMMAND_LOCKUNLOCK, PIN_DATA, {'lock': False},
{'pin': 9999})
assert len(calls) == 0
assert err.code == const.ERR_CHALLENGE_NEEDED
assert err.challenge_type == const.CHALLENGE_FAILED_PIN_NEEDED
await trt.execute(
trait.COMMAND_LOCKUNLOCK, PIN_DATA, {'lock': False}, {'pin': '1234'})
assert len(calls) == 1
assert calls[0].data == {
ATTR_ENTITY_ID: 'lock.front_door'
}
async def test_fan_speed(hass):
"""Test FanSpeed trait speed control support for fan domain."""
assert helpers.get_google_type(fan.DOMAIN, None) is not None
assert trait.FanSpeedTrait.supported(fan.DOMAIN, fan.SUPPORT_SET_SPEED,
None)
trt = trait.FanSpeedTrait(
hass, State(
'fan.living_room_fan', fan.SPEED_HIGH, attributes={
'speed_list': [
fan.SPEED_OFF, fan.SPEED_LOW, fan.SPEED_MEDIUM,
fan.SPEED_HIGH
],
'speed': 'low'
}), BASIC_CONFIG)
assert trt.sync_attributes() == {
'availableFanSpeeds': {
'ordered': True,
'speeds': [
{
'speed_name': 'off',
'speed_values': [
{
'speed_synonym': ['stop', 'off'],
'lang': 'en'
}
]
},
{
'speed_name': 'low',
'speed_values': [
{
'speed_synonym': [
'slow', 'low', 'slowest', 'lowest'],
'lang': 'en'
}
]
},
{
'speed_name': 'medium',
'speed_values': [
{
'speed_synonym': ['medium', 'mid', 'middle'],
'lang': 'en'
}
]
},
{
'speed_name': 'high',
'speed_values': [
{
'speed_synonym': [
'high', 'max', 'fast', 'highest', 'fastest',
'maximum'],
'lang': 'en'
}
]
}
]
},
'reversible': False
}
assert trt.query_attributes() == {
'currentFanSpeedSetting': 'low',
'on': True,
'online': True
}
assert trt.can_execute(
trait.COMMAND_FANSPEED, params={'fanSpeed': 'medium'})
calls = async_mock_service(hass, fan.DOMAIN, fan.SERVICE_SET_SPEED)
await trt.execute(
trait.COMMAND_FANSPEED, BASIC_DATA, {'fanSpeed': 'medium'}, {})
assert len(calls) == 1
assert calls[0].data == {
'entity_id': 'fan.living_room_fan',
'speed': 'medium'
}
async def test_modes(hass):
"""Test Mode trait."""
assert helpers.get_google_type(media_player.DOMAIN, None) is not None
assert trait.ModesTrait.supported(
media_player.DOMAIN, media_player.SUPPORT_SELECT_SOURCE, None)
trt = trait.ModesTrait(
hass, State(
'media_player.living_room', media_player.STATE_PLAYING,
attributes={
media_player.ATTR_INPUT_SOURCE_LIST: [
'media', 'game', 'chromecast', 'plex'
],
media_player.ATTR_INPUT_SOURCE: 'game'
}),
BASIC_CONFIG)
attribs = trt.sync_attributes()
assert attribs == {
'availableModes': [
{
'name': 'input source',
'name_values': [
{
'name_synonym': ['input source'],
'lang': 'en'
}
],
'settings': [
{
'setting_name': 'media',
'setting_values': [
{
'setting_synonym': ['media', 'media mode'],
'lang': 'en'
}
]
},
{
'setting_name': 'game',
'setting_values': [
{
'setting_synonym': ['game', 'game mode'],
'lang': 'en'
}
]
},
{
'setting_name': 'chromecast',
'setting_values': [
{
'setting_synonym': ['chromecast'],
'lang': 'en'
}
]
}
],
'ordered': False
}
]
}
assert trt.query_attributes() == {
'currentModeSettings': {'source': 'game'},
'on': True,
'online': True
}
assert trt.can_execute(
trait.COMMAND_MODES, params={
'updateModeSettings': {
trt.HA_TO_GOOGLE.get(media_player.ATTR_INPUT_SOURCE): 'media'
}})
calls = async_mock_service(
hass, media_player.DOMAIN, media_player.SERVICE_SELECT_SOURCE)
await trt.execute(
trait.COMMAND_MODES, BASIC_DATA, {
'updateModeSettings': {
trt.HA_TO_GOOGLE.get(media_player.ATTR_INPUT_SOURCE): 'media'
}}, {})
assert len(calls) == 1
assert calls[0].data == {
'entity_id': 'media_player.living_room',
'source': 'media'
}
async def test_openclose_cover(hass):
"""Test OpenClose trait support for cover domain."""
assert helpers.get_google_type(cover.DOMAIN, None) is not None
assert trait.OpenCloseTrait.supported(cover.DOMAIN,
cover.SUPPORT_SET_POSITION, None)
trt = trait.OpenCloseTrait(hass, State('cover.bla', cover.STATE_OPEN, {
cover.ATTR_CURRENT_POSITION: 75,
ATTR_SUPPORTED_FEATURES: cover.SUPPORT_SET_POSITION,
}), BASIC_CONFIG)
assert trt.sync_attributes() == {}
assert trt.query_attributes() == {
'openPercent': 75
}
calls = async_mock_service(
hass, cover.DOMAIN, cover.SERVICE_SET_COVER_POSITION)
await trt.execute(
trait.COMMAND_OPENCLOSE, BASIC_DATA,
{'openPercent': 50}, {})
assert len(calls) == 1
assert calls[0].data == {
ATTR_ENTITY_ID: 'cover.bla',
cover.ATTR_POSITION: 50
}
async def test_openclose_cover_unknown_state(hass):
"""Test OpenClose trait support for cover domain with unknown state."""
assert helpers.get_google_type(cover.DOMAIN, None) is not None
assert trait.OpenCloseTrait.supported(cover.DOMAIN,
cover.SUPPORT_SET_POSITION, None)
# No state
trt = trait.OpenCloseTrait(hass, State('cover.bla', STATE_UNKNOWN, {
}), BASIC_CONFIG)
assert trt.sync_attributes() == {}
with pytest.raises(helpers.SmartHomeError):
trt.query_attributes()
calls = async_mock_service(
hass, cover.DOMAIN, cover.SERVICE_OPEN_COVER)
await trt.execute(
trait.COMMAND_OPENCLOSE, BASIC_DATA,
{'openPercent': 100}, {})
assert len(calls) == 1
assert calls[0].data == {
ATTR_ENTITY_ID: 'cover.bla',
}
assert trt.query_attributes() == {'openPercent': 100}
async def test_openclose_cover_assumed_state(hass):
"""Test OpenClose trait support for cover domain."""
assert helpers.get_google_type(cover.DOMAIN, None) is not None
assert trait.OpenCloseTrait.supported(cover.DOMAIN,
cover.SUPPORT_SET_POSITION, None)
trt = trait.OpenCloseTrait(hass, State('cover.bla', cover.STATE_OPEN, {
ATTR_ASSUMED_STATE: True,
ATTR_SUPPORTED_FEATURES: cover.SUPPORT_SET_POSITION,
}), BASIC_CONFIG)
assert trt.sync_attributes() == {}
with pytest.raises(helpers.SmartHomeError):
trt.query_attributes()
calls = async_mock_service(
hass, cover.DOMAIN, cover.SERVICE_SET_COVER_POSITION)
await trt.execute(
trait.COMMAND_OPENCLOSE, BASIC_DATA,
{'openPercent': 40}, {})
assert len(calls) == 1
assert calls[0].data == {
ATTR_ENTITY_ID: 'cover.bla',
cover.ATTR_POSITION: 40
}
assert trt.query_attributes() == {'openPercent': 40}
async def test_openclose_cover_no_position(hass):
"""Test OpenClose trait support for cover domain."""
assert helpers.get_google_type(cover.DOMAIN, None) is not None
assert trait.OpenCloseTrait.supported(cover.DOMAIN,
cover.SUPPORT_SET_POSITION, None)
trt = trait.OpenCloseTrait(hass, State('cover.bla', cover.STATE_OPEN, {
}), BASIC_CONFIG)
assert trt.sync_attributes() == {}
assert trt.query_attributes() == {
'openPercent': 100
}
calls = async_mock_service(
hass, cover.DOMAIN, cover.SERVICE_CLOSE_COVER)
await trt.execute(
trait.COMMAND_OPENCLOSE, BASIC_DATA,
{'openPercent': 0}, {})
assert len(calls) == 1
assert calls[0].data == {
ATTR_ENTITY_ID: 'cover.bla',
}
@pytest.mark.parametrize('device_class', (
cover.DEVICE_CLASS_DOOR,
cover.DEVICE_CLASS_GARAGE,
))
async def test_openclose_cover_secure(hass, device_class):
"""Test OpenClose trait support for cover domain."""
assert helpers.get_google_type(cover.DOMAIN, device_class) is not None
assert trait.OpenCloseTrait.supported(
cover.DOMAIN, cover.SUPPORT_SET_POSITION, device_class)
trt = trait.OpenCloseTrait(hass, State('cover.bla', cover.STATE_OPEN, {
ATTR_DEVICE_CLASS: device_class,
ATTR_SUPPORTED_FEATURES: cover.SUPPORT_SET_POSITION,
cover.ATTR_CURRENT_POSITION: 75
}), PIN_CONFIG)
assert trt.sync_attributes() == {}
assert trt.query_attributes() == {
'openPercent': 75
}
calls = async_mock_service(
hass, cover.DOMAIN, cover.SERVICE_SET_COVER_POSITION)
# No challenge data
with pytest.raises(error.ChallengeNeeded) as err:
await trt.execute(
trait.COMMAND_OPENCLOSE, PIN_DATA,
{'openPercent': 50}, {})
assert len(calls) == 0
assert err.code == const.ERR_CHALLENGE_NEEDED
assert err.challenge_type == const.CHALLENGE_PIN_NEEDED
# invalid pin
with pytest.raises(error.ChallengeNeeded) as err:
await trt.execute(
trait.COMMAND_OPENCLOSE, PIN_DATA,
{'openPercent': 50}, {'pin': '9999'})
assert len(calls) == 0
assert err.code == const.ERR_CHALLENGE_NEEDED
assert err.challenge_type == const.CHALLENGE_FAILED_PIN_NEEDED
await trt.execute(
trait.COMMAND_OPENCLOSE, PIN_DATA,
{'openPercent': 50}, {'pin': '1234'})
assert len(calls) == 1
assert calls[0].data == {
ATTR_ENTITY_ID: 'cover.bla',
cover.ATTR_POSITION: 50
}
@pytest.mark.parametrize('device_class', (
binary_sensor.DEVICE_CLASS_DOOR,
binary_sensor.DEVICE_CLASS_GARAGE_DOOR,
binary_sensor.DEVICE_CLASS_LOCK,
binary_sensor.DEVICE_CLASS_OPENING,
binary_sensor.DEVICE_CLASS_WINDOW,
))
async def test_openclose_binary_sensor(hass, device_class):
"""Test OpenClose trait support for binary_sensor domain."""
assert helpers.get_google_type(
binary_sensor.DOMAIN, device_class) is not None
assert trait.OpenCloseTrait.supported(binary_sensor.DOMAIN,
0, device_class)
trt = trait.OpenCloseTrait(hass, State('binary_sensor.test', STATE_ON, {
ATTR_DEVICE_CLASS: device_class,
}), BASIC_CONFIG)
assert trt.sync_attributes() == {
'queryOnlyOpenClose': True,
}
assert trt.query_attributes() == {
'openPercent': 100
}
trt = trait.OpenCloseTrait(hass, State('binary_sensor.test', STATE_OFF, {
ATTR_DEVICE_CLASS: device_class,
}), BASIC_CONFIG)
assert trt.sync_attributes() == {
'queryOnlyOpenClose': True,
}
assert trt.query_attributes() == {
'openPercent': 0
}
async def test_volume_media_player(hass):
"""Test volume trait support for media player domain."""
assert helpers.get_google_type(media_player.DOMAIN, None) is not None
assert trait.VolumeTrait.supported(media_player.DOMAIN,
media_player.SUPPORT_VOLUME_SET |
media_player.SUPPORT_VOLUME_MUTE,
None)
trt = trait.VolumeTrait(hass, State(
'media_player.bla', media_player.STATE_PLAYING, {
media_player.ATTR_MEDIA_VOLUME_LEVEL: .3,
media_player.ATTR_MEDIA_VOLUME_MUTED: False,
}), BASIC_CONFIG)
assert trt.sync_attributes() == {}
assert trt.query_attributes() == {
'currentVolume': 30,
'isMuted': False
}
calls = async_mock_service(
hass, media_player.DOMAIN, media_player.SERVICE_VOLUME_SET)
await trt.execute(
trait.COMMAND_SET_VOLUME, BASIC_DATA,
{'volumeLevel': 60}, {})
assert len(calls) == 1
assert calls[0].data == {
ATTR_ENTITY_ID: 'media_player.bla',
media_player.ATTR_MEDIA_VOLUME_LEVEL: .6
}
async def test_volume_media_player_relative(hass):
"""Test volume trait support for media player domain."""
trt = trait.VolumeTrait(hass, State(
'media_player.bla', media_player.STATE_PLAYING, {
media_player.ATTR_MEDIA_VOLUME_LEVEL: .3,
media_player.ATTR_MEDIA_VOLUME_MUTED: False,
}), BASIC_CONFIG)
assert trt.sync_attributes() == {}
assert trt.query_attributes() == {
'currentVolume': 30,
'isMuted': False
}
calls = async_mock_service(
hass, media_player.DOMAIN, media_player.SERVICE_VOLUME_SET)
await trt.execute(
trait.COMMAND_VOLUME_RELATIVE, BASIC_DATA,
{'volumeRelativeLevel': 20,
'relativeSteps': 2}, {})
assert len(calls) == 1
assert calls[0].data == {
ATTR_ENTITY_ID: 'media_player.bla',
media_player.ATTR_MEDIA_VOLUME_LEVEL: .5
}
| |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated from MetricAlertCondition.g4 by ANTLR 4.7.2
# encoding: utf-8
# pylint: disable=all
from antlr4 import *
# This class defines a complete listener for a parse tree produced by MetricAlertConditionParser.
class MetricAlertConditionListener(ParseTreeListener):
# Enter a parse tree produced by MetricAlertConditionParser#expression.
def enterExpression(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#expression.
def exitExpression(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#aggregation.
def enterAggregation(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#aggregation.
def exitAggregation(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#namespace.
def enterNamespace(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#namespace.
def exitNamespace(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#metric.
def enterMetric(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#metric.
def exitMetric(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#operator.
def enterOperator(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#operator.
def exitOperator(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#threshold.
def enterThreshold(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#threshold.
def exitThreshold(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#dynamic.
def enterDynamic(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#dynamic.
def exitDynamic(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#dynamics.
def enterDynamics(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#dynamics.
def exitDynamics(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#dyn_sensitivity.
def enterDyn_sensitivity(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#dyn_sensitivity.
def exitDyn_sensitivity(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#dyn_violations.
def enterDyn_violations(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#dyn_violations.
def exitDyn_violations(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#dyn_of_separator.
def enterDyn_of_separator(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#dyn_of_separator.
def exitDyn_of_separator(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#dyn_windows.
def enterDyn_windows(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#dyn_windows.
def exitDyn_windows(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#dyn_since_seperator.
def enterDyn_since_seperator(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#dyn_since_seperator.
def exitDyn_since_seperator(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#dyn_datetime.
def enterDyn_datetime(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#dyn_datetime.
def exitDyn_datetime(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#where.
def enterWhere(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#where.
def exitWhere(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#dimensions.
def enterDimensions(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#dimensions.
def exitDimensions(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#dimension.
def enterDimension(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#dimension.
def exitDimension(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#dim_separator.
def enterDim_separator(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#dim_separator.
def exitDim_separator(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#dim_operator.
def enterDim_operator(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#dim_operator.
def exitDim_operator(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#dim_val_separator.
def enterDim_val_separator(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#dim_val_separator.
def exitDim_val_separator(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#dim_name.
def enterDim_name(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#dim_name.
def exitDim_name(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#dim_values.
def enterDim_values(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#dim_values.
def exitDim_values(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#dim_value.
def enterDim_value(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#dim_value.
def exitDim_value(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#options_.
def enterOptions_(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#options_.
def exitOptions_(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#with_.
def enterWith_(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#with_.
def exitWith_(self, ctx):
pass
# Enter a parse tree produced by MetricAlertConditionParser#option.
def enterOption(self, ctx):
pass
# Exit a parse tree produced by MetricAlertConditionParser#option.
def exitOption(self, ctx):
pass
| |
# 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_config import cfg
from oslo_log import log
import six
from neutron._i18n import _, _LI, _LW
from neutron.quota import resource
LOG = log.getLogger(__name__)
# Wrappers for easing access to the ResourceRegistry singleton
def register_resource(resource):
ResourceRegistry.get_instance().register_resource(resource)
def register_resource_by_name(resource_name, plural_name=None):
ResourceRegistry.get_instance().register_resource_by_name(
resource_name, plural_name)
def get_all_resources():
return ResourceRegistry.get_instance().resources
def unregister_all_resources():
if not ResourceRegistry._instance:
return
return ResourceRegistry.get_instance().unregister_resources()
def get_resource(resource_name):
return ResourceRegistry.get_instance().get_resource(resource_name)
def is_tracked(resource_name):
return ResourceRegistry.get_instance().is_tracked(resource_name)
# auxiliary functions and decorators
def set_resources_dirty(context):
"""Sets the dirty bit for resources with usage changes.
This routine scans all registered resources, and, for those whose
dirty status is True, sets the dirty bit to True in the database
for the appropriate tenants.
Please note that this routine begins a nested transaction, and it
is not recommended that this transaction begins within another
transaction. For this reason the function will raise a SqlAlchemy
exception if such an attempt is made.
:param context: a Neutron request context with a DB session
"""
if not cfg.CONF.QUOTAS.track_quota_usage:
return
for res in get_all_resources().values():
with context.session.begin(subtransactions=True):
if is_tracked(res.name) and res.dirty:
res.mark_dirty(context)
def resync_resource(context, resource_name, tenant_id):
if not cfg.CONF.QUOTAS.track_quota_usage:
return
if is_tracked(resource_name):
res = get_resource(resource_name)
# If the resource is tracked count supports the resync_usage parameter
res.resync(context, tenant_id)
def mark_resources_dirty(f):
"""Decorator for functions which alter resource usage.
This decorator ensures set_resource_dirty is invoked after completion
of the decorated function.
"""
@six.wraps(f)
def wrapper(_self, context, *args, **kwargs):
ret_val = f(_self, context, *args, **kwargs)
set_resources_dirty(context)
return ret_val
return wrapper
class tracked_resources(object):
"""Decorator for specifying resources for which usage should be tracked.
A plugin class can use this decorator to specify for which resources
usage info should be tracked into an appropriate table rather than being
explicitly counted.
"""
def __init__(self, override=False, **kwargs):
self._tracked_resources = kwargs
self._override = override
def __call__(self, f):
@six.wraps(f)
def wrapper(*args, **kwargs):
registry = ResourceRegistry.get_instance()
for resource_name in self._tracked_resources:
registry.set_tracked_resource(
resource_name,
self._tracked_resources[resource_name],
self._override)
return f(*args, **kwargs)
return wrapper
class ResourceRegistry(object):
"""Registry for resource subject to quota limits.
This class keeps track of Neutron resources for which quota limits are
enforced, regardless of whether their usage is being tracked or counted.
For tracked-usage resources, that is to say those resources for which
there are usage counters which are kept in sync with the actual number
of rows in the database, this class allows the plugin to register their
names either explicitly or through the @tracked_resources decorator,
which should preferably be applied to the __init__ method of the class.
"""
_instance = None
@classmethod
def get_instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
def __init__(self):
self._resources = {}
# Map usage tracked resources to the correspondent db model class
self._tracked_resource_mappings = {}
def __contains__(self, resource):
return resource in self._resources
def _create_resource_instance(self, resource_name, plural_name):
"""Factory function for quota Resource.
This routine returns a resource instance of the appropriate type
according to system configuration.
If QUOTAS.track_quota_usage is True, and there is a model mapping for
the current resource, this function will return an instance of
AccountedResource; otherwise an instance of CountableResource.
"""
if (not cfg.CONF.QUOTAS.track_quota_usage or
resource_name not in self._tracked_resource_mappings):
LOG.info(_LI("Creating instance of CountableResource for "
"resource:%s"), resource_name)
return resource.CountableResource(
resource_name, resource._count_resource,
'quota_%s' % resource_name)
else:
LOG.info(_LI("Creating instance of TrackedResource for "
"resource:%s"), resource_name)
return resource.TrackedResource(
resource_name,
self._tracked_resource_mappings[resource_name],
'quota_%s' % resource_name)
def set_tracked_resource(self, resource_name, model_class, override=False):
# Do not do anything if tracking is disabled by config
if not cfg.CONF.QUOTAS.track_quota_usage:
return
if isinstance(self._resources.get(resource_name),
resource.CountableResource):
raise RuntimeError(_("Resource %s is already registered as a "
"countable resource.") % resource_name)
current_model_class = self._tracked_resource_mappings.setdefault(
resource_name, model_class)
# Check whether setdefault also set the entry in the dict
if current_model_class != model_class:
LOG.debug("A model class is already defined for %(resource)s: "
"%(current_model_class)s. Override:%(override)s",
{'resource': resource_name,
'current_model_class': current_model_class,
'override': override})
if override:
self._tracked_resource_mappings[resource_name] = model_class
LOG.debug("Tracking information for resource: %s configured",
resource_name)
def is_tracked(self, resource_name):
"""Find out if a resource if tracked or not.
:param resource_name: name of the resource.
:returns True if resource_name is registered and tracked, otherwise
False. Please note that here when False it returned it
simply means that resource_name is not a TrackedResource
instance, it does not necessarily mean that the resource
is not registered.
"""
return resource_name in self._tracked_resource_mappings
def register_resource(self, resource):
if resource.name in self._resources:
LOG.warning(_LW('%s is already registered'), resource.name)
if resource.name in self._tracked_resource_mappings:
resource.register_events()
self._resources[resource.name] = resource
def register_resources(self, resources):
for res in resources:
self.register_resource(res)
def register_resource_by_name(self, resource_name,
plural_name=None):
"""Register a resource by name."""
resource = self._create_resource_instance(
resource_name, plural_name)
self.register_resource(resource)
def unregister_resources(self):
"""Unregister all resources."""
for (res_name, res) in self._resources.items():
if res_name in self._tracked_resource_mappings:
res.unregister_events()
self._resources.clear()
self._tracked_resource_mappings.clear()
def get_resource(self, resource_name):
"""Return a resource given its name.
:returns: The resource instance or None if the resource is not found
"""
return self._resources.get(resource_name)
@property
def resources(self):
return self._resources
| |
"""
This applet can be viewed directly on a bokeh-server.
See the README.md file in this directory for instructions on running.
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import lib.bayesian_ab as ab
import numpy as np
from scipy.stats import beta
from bokeh.plotting import segment, line, show, figure, rect, multi_line
from bokeh.objects import Plot, ColumnDataSource, Range1d
from bokeh.properties import Instance, String
from bokeh.server.app import bokeh_app
from bokeh.server.utils.plugins import object_page
from bokeh.widgets import HBox, InputWidget, TextInput, VBoxForm, Slider, PreText, VBox
class ABTestApp(HBox):
extra_generated_classes = [["ABTestApp", "ABTestApp", "VBox"]]
jsmodel = "VBox"
inputs = Instance(VBoxForm)
outputs = Instance(VBox)
pretext = Instance(PreText)
installs_A = Instance(TextInput)
installs_B = Instance(TextInput)
views_A = Instance(TextInput)
views_B = Instance(TextInput)
sensitivity = Instance(InputWidget)
plot = Instance(Plot)
source = Instance(ColumnDataSource)
@classmethod
def create(cls):
"""
This function is called once, and is responsible for
creating all objects (plots, datasources, etc)
"""
obj = cls()
obj.pretext = PreText(text="", width=500, height=80)
obj.inputs = VBoxForm()
obj.outputs = VBox()
#inputs
obj.source = ColumnDataSource(data=dict(xs=[], ys=[]))
obj.make_inputs()
# outputs
obj.make_data()
obj.make_line_plot()
obj.make_stats(err=None)
obj.set_children()
return obj
def make_inputs(self):
self.installs_A = TextInput(
title='Version A Installs', name='Version A Installs',
value='200'
)
self.installs_B = TextInput(
title='Version B Installs', name='Version B Installs',
value='220'
)
self.views_A = TextInput(
title='Version A Views', name='Version A Views',
value='100000'
)
self.views_B = TextInput(
title='Version B Views', name='Version B Views',
value='100000'
)
self.sensitivity = Slider(
title='Sensitivity', name='Sensitivity',
value=.03, start=0, end=.5
)
def make_data(self):
post_A, post_B = self.get_posteriors()
samps_A = ab.get_samples(post_A)
samps_B = ab.get_samples(post_B)
x0 = min([min(samps_A), min(samps_B)])
x1 = max([max(samps_A), max(samps_B)])
x_range = np.linspace(x0, x1, 500)
self.source.data = dict(xs=[x_range, x_range],
ys=[post_A.pdf(x_range), post_B.pdf(x_range)])
def set_children(self):
self.children = [self.inputs, self.outputs]
self.inputs.children = [
self.installs_A,
self.installs_B,
self.views_A,
self.views_B,
self.sensitivity
]
self.outputs.children = [
self.pretext,
self.plot
]
def make_line_plot(self):
self.plot = multi_line('xs', 'ys',
source=self.source,
color=['#1F78B4', '#FB9A99'],
legend='Version A',
title='Likelihood of Install Rates',
height=200,
width=500
)
def setup_events(self):
super(ABTestApp, self).setup_events()
if not self.pretext:
return
for w in ["installs_A", "installs_B", "views_A", "views_B", "sensitivity"]:
getattr(self, w).on_change('value', self, 'input_change')
def input_change(self, obj, attrname, old, new):
"""
This callback is executed whenever the input form changes. It is
responsible for updating the plot, or anything else you want.
The signature is:
Args:
obj : the object that changed
attrname : the attr that changed
old : old value of attr
new : new value of attr
"""
input_errs = self._check_inputs()
if input_errs:
self.make_stats(err=input_errs)
else:
self.make_data()
self.make_stats(err=None)
self.make_line_plot()
self.set_children()
def _check_inputs(self):
output = []
i_A = np.float(self.installs_A.value)
i_B = np.float(self.installs_B.value)
v_A = np.float(self.views_A.value)
v_B = np.float(self.views_B.value)
if i_A < 100:
output.append('Version A installs < 100')
if i_B < 100:
output.append('Version B installs < 100')
if i_A > v_A:
output.append('Version A has more installs than views')
if i_B > v_B:
output.append('Version B has more installs than views')
return output
def get_posteriors(self):
post_A, post_B = ab.calculate_posteriors(np.float(self.installs_A.value),
np.float(self.installs_B.value),
np.float(self.views_A.value),
np.float(self.views_B.value))
return post_A, post_B
def make_stats(self, err):
if not err:
post_A, post_B = self.get_posteriors()
samps_A = ab.get_samples(post_A)
samps_B = ab.get_samples(post_B)
p_better = ab.get_prob_better(samps_A, samps_B)
p_X_better = ab.get_prob_X_better(samps_A, samps_B, self.sensitivity.value)
lift = ab.get_expected_lift(samps_A, samps_B)
stats_string = " Probability B > A: {0}\
\n Probability B > A by {1} Percent: {2}\
\n Expected Percent Difference: {3}" \
.format(p_better, self.sensitivity.value * 100, p_X_better, lift)
self.pretext.text = str(stats_string)
else:
err.insert(0, ' ')
self.pretext.text = '\n Input Error: '.join(err)
# The following code adds a "/bokeh/abtest/" url to the bokeh-server.
# This URL will render this app.
@bokeh_app.route("/bokeh/abtest/")
@object_page("AB_Test")
def make_object():
app = ABTestApp.create()
return app
| |
"""The tests for the MQTT light platform.
Configuration for RGB Version with brightness:
light:
platform: mqtt
name: "Office Light RGB"
state_topic: "office/rgb1/light/status"
command_topic: "office/rgb1/light/switch"
brightness_state_topic: "office/rgb1/brightness/status"
brightness_command_topic: "office/rgb1/brightness/set"
rgb_state_topic: "office/rgb1/rgb/status"
rgb_command_topic: "office/rgb1/rgb/set"
qos: 0
payload_on: "on"
payload_off: "off"
config without RGB:
light:
platform: mqtt
name: "Office Light"
state_topic: "office/rgb1/light/status"
command_topic: "office/rgb1/light/switch"
brightness_state_topic: "office/rgb1/brightness/status"
brightness_command_topic: "office/rgb1/brightness/set"
qos: 0
payload_on: "on"
payload_off: "off"
config without RGB and brightness:
light:
platform: mqtt
name: "Office Light"
state_topic: "office/rgb1/light/status"
command_topic: "office/rgb1/light/switch"
qos: 0
payload_on: "on"
payload_off: "off"
config for RGB Version with brightness and scale:
light:
platform: mqtt
name: "Office Light RGB"
state_topic: "office/rgb1/light/status"
command_topic: "office/rgb1/light/switch"
brightness_state_topic: "office/rgb1/brightness/status"
brightness_command_topic: "office/rgb1/brightness/set"
brightness_scale: 99
rgb_state_topic: "office/rgb1/rgb/status"
rgb_command_topic: "office/rgb1/rgb/set"
rgb_scale: 99
qos: 0
payload_on: "on"
payload_off: "off"
"""
import unittest
from homeassistant.bootstrap import _setup_component
from homeassistant.const import STATE_ON, STATE_OFF, ATTR_ASSUMED_STATE
import homeassistant.components.light as light
from tests.common import (
get_test_home_assistant, mock_mqtt_component, fire_mqtt_message)
class TestLightMQTT(unittest.TestCase):
"""Test the MQTT light."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.mock_publish = mock_mqtt_component(self.hass)
def tearDown(self): # pylint: disable=invalid-name
"""Stop everything that was started."""
self.hass.stop()
def test_fail_setup_if_no_command_topic(self):
"""Test if command fails with command topic."""
self.hass.config.components = ['mqtt']
assert not _setup_component(self.hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
}
})
self.assertIsNone(self.hass.states.get('light.test'))
def test_no_color_or_brightness_if_no_topics(self):
"""Test if there is no color and brightness if no topic."""
self.hass.config.components = ['mqtt']
assert _setup_component(self.hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'test_light_rgb/status',
'command_topic': 'test_light_rgb/set',
}
})
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
self.assertIsNone(state.attributes.get('rgb_color'))
self.assertIsNone(state.attributes.get('brightness'))
fire_mqtt_message(self.hass, 'test_light_rgb/status', 'ON')
self.hass.pool.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
self.assertIsNone(state.attributes.get('rgb_color'))
self.assertIsNone(state.attributes.get('brightness'))
def test_controlling_state_via_topic(self):
"""Test the controlling of the state via topic."""
self.hass.config.components = ['mqtt']
assert _setup_component(self.hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'test_light_rgb/status',
'command_topic': 'test_light_rgb/set',
'brightness_state_topic': 'test_light_rgb/brightness/status',
'brightness_command_topic': 'test_light_rgb/brightness/set',
'rgb_state_topic': 'test_light_rgb/rgb/status',
'rgb_command_topic': 'test_light_rgb/rgb/set',
'qos': '0',
'payload_on': 1,
'payload_off': 0
}
})
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
self.assertIsNone(state.attributes.get('rgb_color'))
self.assertIsNone(state.attributes.get('brightness'))
self.assertIsNone(state.attributes.get(ATTR_ASSUMED_STATE))
fire_mqtt_message(self.hass, 'test_light_rgb/status', '1')
self.hass.pool.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
self.assertEqual([255, 255, 255], state.attributes.get('rgb_color'))
self.assertEqual(255, state.attributes.get('brightness'))
fire_mqtt_message(self.hass, 'test_light_rgb/status', '0')
self.hass.pool.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
fire_mqtt_message(self.hass, 'test_light_rgb/status', '1')
self.hass.pool.block_till_done()
fire_mqtt_message(self.hass, 'test_light_rgb/brightness/status', '100')
self.hass.pool.block_till_done()
light_state = self.hass.states.get('light.test')
self.hass.pool.block_till_done()
self.assertEqual(100,
light_state.attributes['brightness'])
fire_mqtt_message(self.hass, 'test_light_rgb/status', '1')
self.hass.pool.block_till_done()
fire_mqtt_message(self.hass, 'test_light_rgb/rgb/status',
'125,125,125')
self.hass.pool.block_till_done()
light_state = self.hass.states.get('light.test')
self.assertEqual([125, 125, 125],
light_state.attributes.get('rgb_color'))
def test_controlling_scale(self):
"""Test the controlling scale."""
self.hass.config.components = ['mqtt']
assert _setup_component(self.hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'test_scale/status',
'command_topic': 'test_scale/set',
'brightness_state_topic': 'test_scale/brightness/status',
'brightness_command_topic': 'test_scale/brightness/set',
'brightness_scale': '99',
'qos': 0,
'payload_on': 'on',
'payload_off': 'off'
}
})
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
self.assertIsNone(state.attributes.get('brightness'))
self.assertIsNone(state.attributes.get(ATTR_ASSUMED_STATE))
fire_mqtt_message(self.hass, 'test_scale/status', 'on')
self.hass.pool.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
self.assertEqual(255, state.attributes.get('brightness'))
fire_mqtt_message(self.hass, 'test_scale/status', 'off')
self.hass.pool.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
fire_mqtt_message(self.hass, 'test_scale/status', 'on')
self.hass.pool.block_till_done()
fire_mqtt_message(self.hass, 'test_scale/brightness/status', '99')
self.hass.pool.block_till_done()
light_state = self.hass.states.get('light.test')
self.hass.pool.block_till_done()
self.assertEqual(255,
light_state.attributes['brightness'])
def test_controlling_state_via_topic_with_templates(self):
"""Test the setting og the state with a template."""
self.hass.config.components = ['mqtt']
assert _setup_component(self.hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'test_light_rgb/status',
'command_topic': 'test_light_rgb/set',
'brightness_state_topic': 'test_light_rgb/brightness/status',
'rgb_state_topic': 'test_light_rgb/rgb/status',
'state_value_template': '{{ value_json.hello }}',
'brightness_value_template': '{{ value_json.hello }}',
'rgb_value_template': '{{ value_json.hello | join(",") }}',
}
})
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
self.assertIsNone(state.attributes.get('brightness'))
self.assertIsNone(state.attributes.get('rgb_color'))
fire_mqtt_message(self.hass, 'test_light_rgb/rgb/status',
'{"hello": [1, 2, 3]}')
fire_mqtt_message(self.hass, 'test_light_rgb/status',
'{"hello": "ON"}')
fire_mqtt_message(self.hass, 'test_light_rgb/brightness/status',
'{"hello": "50"}')
self.hass.pool.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
self.assertEqual(50, state.attributes.get('brightness'))
self.assertEqual([1, 2, 3], state.attributes.get('rgb_color'))
def test_sending_mqtt_commands_and_optimistic(self):
"""Test the sending of command in optimistic mode."""
self.hass.config.components = ['mqtt']
assert _setup_component(self.hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'command_topic': 'test_light_rgb/set',
'brightness_command_topic': 'test_light_rgb/brightness/set',
'rgb_command_topic': 'test_light_rgb/rgb/set',
'qos': 2,
'payload_on': 'on',
'payload_off': 'off'
}
})
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE))
light.turn_on(self.hass, 'light.test')
self.hass.pool.block_till_done()
self.assertEqual(('test_light_rgb/set', 'on', 2, False),
self.mock_publish.mock_calls[-1][1])
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
light.turn_off(self.hass, 'light.test')
self.hass.pool.block_till_done()
self.assertEqual(('test_light_rgb/set', 'off', 2, False),
self.mock_publish.mock_calls[-1][1])
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
light.turn_on(self.hass, 'light.test', rgb_color=[75, 75, 75],
brightness=50)
self.hass.pool.block_till_done()
# Calls are threaded so we need to reorder them
bright_call, rgb_call, state_call = \
sorted((call[1] for call in self.mock_publish.mock_calls[-3:]),
key=lambda call: call[0])
self.assertEqual(('test_light_rgb/set', 'on', 2, False),
state_call)
self.assertEqual(('test_light_rgb/rgb/set', '75,75,75', 2, False),
rgb_call)
self.assertEqual(('test_light_rgb/brightness/set', 50, 2, False),
bright_call)
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
self.assertEqual((75, 75, 75), state.attributes['rgb_color'])
self.assertEqual(50, state.attributes['brightness'])
def test_show_brightness_if_only_command_topic(self):
"""Test the brightness if only a command topic is present."""
self.hass.config.components = ['mqtt']
assert _setup_component(self.hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'brightness_command_topic': 'test_light_rgb/brightness/set',
'command_topic': 'test_light_rgb/set',
'state_topic': 'test_light_rgb/status',
}
})
state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state)
self.assertIsNone(state.attributes.get('brightness'))
fire_mqtt_message(self.hass, 'test_light_rgb/status', 'ON')
self.hass.pool.block_till_done()
state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state)
self.assertEqual(255, state.attributes.get('brightness'))
| |
import fpformat
import curses
import glob
from math import sqrt, fsum
class Benchmark(object):
"""
Class to define benchmark environment. Accept a game constructor during init
TODO: create a better organization with curses and benchmark itself separation
"""
benchmark_game = None
def __init__(self, game):
self.benchmark_game = game
def tests(self, size, screen, knowledge=False, reduxed=False):
results = []
counter = 1
test_size = size - 1
j = 1
self.prepare_window(screen)
screen.addstr(2, 2, "Eseguo i test...")
for end_x in range(test_size / 2 - test_size / 4, test_size / 2 + test_size / 4):
for end_y in range(test_size / 2 - test_size / 4, test_size / 2 + test_size / 4):
for start_x in range(j, test_size - 1):
for start_y in range(j, test_size - 1):
# Mostro la percentuale di avanzamento dello script
i = (counter * 100) / (((test_size - j - 1) ** 2) * ((test_size / 4) * 2) ** 2)
screen.addstr(4, 2, str(i) + "%")
screen.refresh()
counter += 1
game = self.benchmark_game(size, end_x, end_y, start_x, start_y, knowledge=knowledge, benchmark=True)
result = game.start_game()
results.append(result)
return results
def save_results(self, results, name, screen):
self.prepare_window(screen)
self.get_param("Saving results in " + str(name), screen, True)
file = open(name, 'w')
for ris in results:
print>>file, ris
file.close()
def stats(self, results):
# Average, fails and worst case
sum = 0
not_found = 0
worst = 0
for ris in results:
sum += ris
if ris > worst:
worst = ris
if ris == 0:
not_found += 1
# Calculate the parameters
size = len(results)
avg = sum / size
varianza = fsum([(x - avg) ** 2 for x in results]) / size
scarto = fpformat.fix(sqrt(varianza), 2)
valori = set(results)
frequenze = dict(zip(valori, [results.count(v) for v in valori]))
sorted_frequenze = sorted(frequenze, key=frequenze.get, reverse=True)
sorted_frequenze = sorted_frequenze[:10]
return not_found, worst, avg, scarto, frequenze, sorted_frequenze
def prepare_window(self, screen):
screen.clear()
screen.border(0)
def get_matrix_size(self, screen):
self.prepare_window(screen)
curses.echo()
curses.nocbreak()
curses.curs_set(0)
screen.addstr(2, 2, "Enter matrix size (integer):")
size = screen.getstr(4, 2, 60)
try:
if int(size) > 5:
return int(size)
else:
return self.get_matrix_size(screen)
except:
return self.get_matrix_size(screen)
def get_file(self, string, screen, ms):
x = None
curses.noecho()
curses.cbreak()
curses.curs_set(0)
files = glob.glob('./*' + str(ms) + '*.result')
h = curses.A_REVERSE # h is the coloring for a highlighted menu option
n = curses.A_NORMAL # n is the coloring for a non highlighted menu option
pos = 0
old_pos = 1
while x != ord('\n'):
cnt = 6
self.prepare_window(screen)
if pos != old_pos:
old_pos = pos
screen.addstr(2, 2, string)
screen.addstr(4, 2, "(suggerimenti: possibili file trovati nella cartella attuale)")
i = 0
for file in files:
style = n if i != pos else h
screen.addstr(cnt, 2, "%s" % (file), style)
cnt += 2
i += 1
style = n
style = h if pos == len(files) else n
screen.addstr(cnt, 2, "%s" % ("Altro file"), style)
style = h if pos == len(files) + 1 else n
screen.addstr(cnt + 2, 2, "%s" % ("Nessun file"), style)
screen.refresh()
x = screen.getch()
if x == 258: # down arrow
if pos < len(files) + 1:
pos += 1
else:
pos = 0
elif x == 259: # up arrow
if pos > 0:
pos += -1
else:
pos = len(files) + 1
# return index of the selected item
if pos == len(files):
self.prepare_window(screen)
curses.echo()
curses.curs_set(1)
screen.addstr(2, 2, string)
file = screen.getstr(4, 2, 60)
curses.noecho()
curses.curs_set(0)
elif pos == len(files) + 1:
file = ""
else:
file = files[pos]
return file
def get_param(self, prompt_string, screen, cbreak=False):
self.prepare_window(screen)
curses.echo()
curses.cbreak() if cbreak else curses.nocbreak()
curses.curs_set(0)
screen.addstr(2, 2, prompt_string)
screen.refresh()
input = screen.getch()
return input
def close(self, screen):
curses.cbreak()
curses.noecho()
a = screen.getch()
if a == 113:
curses.nocbreak()
curses.echo()
screen.keypad(0)
curses.endwin()
else:
self.close(screen)
def start(self, screen):
MATRIX_SIZE = self.get_matrix_size(screen)
optimal_file = "OPTIMAL-" + str(MATRIX_SIZE) + ".result"
RIDOTTI = True if self.get_param("Calcoli ridotti? [s/N]", screen, True) == 115 else False
INPUTFILE = self.get_file("File da cui prendere i risultati per i calcoli ('Nessun file' per eseguire i calcoli)", screen, MATRIX_SIZE)
OUTPUTFILE = self.get_file("File in cui salvare i risultati ('Nessun file' per non salvare)", screen, MATRIX_SIZE)
try:
f = open(optimal_file, 'r')
optimal = [int(x) for x in f.readlines()]
f.close()
self.get_param("Trovato file con i risultati dell'algoritmo ottimale! (" + optimal_file + ")", screen, True)
except:
optimal = self.tests(MATRIX_SIZE, screen, knowledge=True, reduxed=RIDOTTI)
self.save_results(optimal, optimal_file, screen)
if not INPUTFILE == "":
try:
f = open(INPUTFILE, 'r')
results = [int(x) for x in f.readlines()]
f.close()
self.get_param("Calcolo le statistiche dal file " + INPUTFILE, screen, True)
except:
self.get_param("File non trovato! Rieseguo i test", screen, True)
results = self.tests(MATRIX_SIZE, screen, knowledge=False, reduxed=RIDOTTI)
else:
results = self.tests(MATRIX_SIZE, screen, knowledge=False, reduxed=RIDOTTI)
if OUTPUTFILE:
self.save_results(results, OUTPUTFILE, screen)
not_found, worst, avg, scarto, frequenze, sorted_frequenze = self.stats(results)
opt_not_found, opt_worst, opt_avg, opt_scarto, opt_frequenze, opt_sorted_frequenze = self.stats(optimal)
ratio_avg = fpformat.fix(float(avg) / float(opt_avg), 2)
ratio_worst = fpformat.fix(float(worst) / float(opt_worst), 2)
ratio_scarto = fpformat.fix((float(scarto) / float(opt_scarto)), 2)
screen.clear()
screen.border(0)
screen.addstr(2, 2, "Statistiche:\t\t\t\tOffline\t\tOnline\t\tRapporto")
screen.addstr(4, 2, "Numero di test eseguiti:\t\t " + str(len(results)) + "\t\t" + str(len(optimal)))
screen.addstr(6, 2, "Carburante esaurito:\t\t\t " + str(not_found) + "\t\t" + str(opt_not_found))
screen.addstr(8, 2, "Caso peggiore:\t\t\t " + str(worst) + "\t\t" + str(opt_worst) + "\t\t" + str(ratio_worst))
screen.addstr(10, 2, "Media aritmetica dei risultati:\t " + str(avg) + "\t\t" + str(opt_avg) + "\t\t" + str(ratio_avg))
screen.addstr(12, 2, "Scarto quadratico medio:\t\t " + str(scarto) + "\t\t" + str(opt_scarto) + "\t\t" + str(ratio_scarto))
screen.addstr(14, 1, "-" * (screen.getmaxyx()[1] - 2))
screen.addstr(16, 2, "I dieci risultati piu' riscontrati nell'algoritmo non ottimale:")
screen.addstr(18, 2, "Costo:\tOttenuto:\tSotto la media?")
cnt = 20
for el in sorted_frequenze:
sotto = "media"
if el < avg:
sotto = "si"
elif el > avg:
sotto = "no"
screen.addstr(cnt, 2, str(el) + "\t\t" + str(frequenze[el]) + "\t\t" + sotto)
cnt += 2
screen.addstr(cnt, 2, "Premere q per uscire")
self.close(screen)
| |
#!/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.
"""Provides an interface to start and stop Android emulator.
Assumes system environment ANDROID_NDK_ROOT has been set.
Emulator: The class provides the methods to launch/shutdown the emulator with
the android virtual device named 'avd_armeabi' .
"""
import logging
import os
import shutil
import signal
import subprocess
import sys
import time
import time_profile
# TODO(craigdh): Move these pylib dependencies to pylib/utils/.
from pylib import android_commands
from pylib import cmd_helper
from pylib import constants
from pylib import pexpect
import errors
import run_command
# Android API level
API_TARGET = 'android-%s' % constants.ANDROID_SDK_VERSION
class EmulatorLaunchException(Exception):
"""Emulator failed to launch."""
pass
def _KillAllEmulators():
"""Kill all running emulators that look like ones we started.
There are odd 'sticky' cases where there can be no emulator process
running but a device slot is taken. A little bot trouble and and
we're out of room forever.
"""
emulators = android_commands.GetEmulators()
if not emulators:
return
for emu_name in emulators:
cmd_helper.RunCmd(['adb', '-s', emu_name, 'emu', 'kill'])
logging.info('Emulator killing is async; give a few seconds for all to die.')
for i in range(5):
if not android_commands.GetEmulators():
return
time.sleep(1)
def DeleteAllTempAVDs():
"""Delete all temporary AVDs which are created for tests.
If the test exits abnormally and some temporary AVDs created when testing may
be left in the system. Clean these AVDs.
"""
avds = android_commands.GetAVDs()
if not avds:
return
for avd_name in avds:
if 'run_tests_avd' in avd_name:
cmd = ['android', '-s', 'delete', 'avd', '--name', avd_name]
cmd_helper.RunCmd(cmd)
logging.info('Delete AVD %s' % avd_name)
class PortPool(object):
"""Pool for emulator port starting position that changes over time."""
_port_min = 5554
_port_max = 5585
_port_current_index = 0
@classmethod
def port_range(cls):
"""Return a range of valid ports for emulator use.
The port must be an even number between 5554 and 5584. Sometimes
a killed emulator "hangs on" to a port long enough to prevent
relaunch. This is especially true on slow machines (like a bot).
Cycling through a port start position helps make us resilient."""
ports = range(cls._port_min, cls._port_max, 2)
n = cls._port_current_index
cls._port_current_index = (n + 1) % len(ports)
return ports[n:] + ports[:n]
def _GetAvailablePort():
"""Returns an available TCP port for the console."""
used_ports = []
emulators = android_commands.GetEmulators()
for emulator in emulators:
used_ports.append(emulator.split('-')[1])
for port in PortPool.port_range():
if str(port) not in used_ports:
return port
def LaunchEmulators(emulator_count, abi, wait_for_boot=True):
"""Launch multiple emulators and wait for them to boot.
Args:
emulator_count: number of emulators to launch.
abi: the emulator target platform
wait_for_boot: whether or not to wait for emulators to boot up
Returns:
List of emulators.
"""
emulators = []
for n in xrange(emulator_count):
t = time_profile.TimeProfile('Emulator launch %d' % n)
# Creates a temporary AVD.
avd_name = 'run_tests_avd_%d' % n
logging.info('Emulator launch %d with avd_name=%s', n, avd_name)
emulator = Emulator(avd_name, abi)
emulator.Launch(kill_all_emulators=n == 0)
t.Stop()
emulators.append(emulator)
# Wait for all emulators to boot completed.
if wait_for_boot:
for emulator in emulators:
emulator.ConfirmLaunch(True)
return emulators
class Emulator(object):
"""Provides the methods to launch/shutdown the emulator.
The emulator has the android virtual device named 'avd_armeabi'.
The emulator could use any even TCP port between 5554 and 5584 for the
console communication, and this port will be part of the device name like
'emulator-5554'. Assume it is always True, as the device name is the id of
emulator managed in this class.
Attributes:
emulator: Path of Android's emulator tool.
popen: Popen object of the running emulator process.
device: Device name of this emulator.
"""
# Signals we listen for to kill the emulator on
_SIGNALS = (signal.SIGINT, signal.SIGHUP)
# Time to wait for an emulator launch, in seconds. This includes
# the time to launch the emulator and a wait-for-device command.
_LAUNCH_TIMEOUT = 120
# Timeout interval of wait-for-device command before bouncing to a a
# process life check.
_WAITFORDEVICE_TIMEOUT = 5
# Time to wait for a "wait for boot complete" (property set on device).
_WAITFORBOOT_TIMEOUT = 300
def __init__(self, avd_name, abi):
"""Init an Emulator.
Args:
avd_name: name of the AVD to create
abi: target platform for emulator being created
"""
android_sdk_root = os.path.join(constants.EMULATOR_SDK_ROOT,
'android_tools', 'sdk')
self.emulator = os.path.join(android_sdk_root, 'tools', 'emulator')
self.android = os.path.join(android_sdk_root, 'tools', 'android')
self.popen = None
self.device = None
self.abi = abi
self.avd_name = avd_name
self._CreateAVD()
def _DeviceName(self):
"""Return our device name."""
port = _GetAvailablePort()
return ('emulator-%d' % port, port)
def _CreateAVD(self):
"""Creates an AVD with the given name.
Return avd_name.
"""
if self.abi == 'arm':
abi_option = 'armeabi-v7a'
else:
abi_option = 'x86'
avd_command = [
self.android,
'--silent',
'create', 'avd',
'--name', self.avd_name,
'--abi', abi_option,
'--target', API_TARGET,
'--force',
]
avd_cmd_str = ' '.join(avd_command)
logging.info('Create AVD command: %s', avd_cmd_str)
avd_process = pexpect.spawn(avd_cmd_str)
# Instead of creating a custom profile, we overwrite config files.
avd_process.expect('Do you wish to create a custom hardware profile')
avd_process.sendline('no\n')
avd_process.expect('Created AVD \'%s\'' % self.avd_name)
# Setup test device as default Galaxy Nexus AVD
avd_config_dir = os.path.join(constants.DIR_SOURCE_ROOT, 'build', 'android',
'avd_configs')
avd_config_ini = os.path.join(avd_config_dir,
'AVD_for_Galaxy_Nexus_by_Google_%s.avd' %
self.abi, 'config.ini')
# Replace current configuration with default Galaxy Nexus config.
avds_dir = os.path.join(os.path.expanduser('~'), '.android', 'avd')
ini_file = os.path.join(avds_dir, '%s.ini' % self.avd_name)
new_config_ini = os.path.join(avds_dir, '%s.avd' % self.avd_name,
'config.ini')
# Remove config files with defaults to replace with Google's GN settings.
os.unlink(ini_file)
os.unlink(new_config_ini)
# Create new configuration files with Galaxy Nexus by Google settings.
with open(ini_file, 'w') as new_ini:
new_ini.write('avd.ini.encoding=ISO-8859-1\n')
new_ini.write('target=%s\n' % API_TARGET)
new_ini.write('path=%s/%s.avd\n' % (avds_dir, self.avd_name))
new_ini.write('path.rel=avd/%s.avd\n' % self.avd_name)
shutil.copy(avd_config_ini, new_config_ini)
return self.avd_name
def _DeleteAVD(self):
"""Delete the AVD of this emulator."""
avd_command = [
self.android,
'--silent',
'delete',
'avd',
'--name', self.avd_name,
]
logging.info('Delete AVD command: %s', ' '.join(avd_command))
cmd_helper.RunCmd(avd_command)
def Launch(self, kill_all_emulators):
"""Launches the emulator asynchronously. Call ConfirmLaunch() to ensure the
emulator is ready for use.
If fails, an exception will be raised.
"""
if kill_all_emulators:
_KillAllEmulators() # just to be sure
self._AggressiveImageCleanup()
(self.device, port) = self._DeviceName()
emulator_command = [
self.emulator,
# Speed up emulator launch by 40%. Really.
'-no-boot-anim',
# The default /data size is 64M.
# That's not enough for 8 unit test bundles and their data.
'-partition-size', '512',
# Use a familiar name and port.
'-avd', self.avd_name,
'-port', str(port),
# Wipe the data. We've seen cases where an emulator gets 'stuck' if we
# don't do this (every thousand runs or so).
'-wipe-data',
# Enable GPU by default.
'-gpu', 'on',
'-qemu', '-m', '1024',
]
if self.abi == 'x86':
emulator_command.extend([
# For x86 emulator --enable-kvm will fail early, avoiding accidental
# runs in a slow mode (i.e. without hardware virtualization support).
'--enable-kvm',
])
logging.info('Emulator launch command: %s', ' '.join(emulator_command))
self.popen = subprocess.Popen(args=emulator_command,
stderr=subprocess.STDOUT)
self._InstallKillHandler()
def _AggressiveImageCleanup(self):
"""Aggressive cleanup of emulator images.
Experimentally it looks like our current emulator use on the bot
leaves image files around in /tmp/android-$USER. If a "random"
name gets reused, we choke with a 'File exists' error.
TODO(jrg): is there a less hacky way to accomplish the same goal?
"""
logging.info('Aggressive Image Cleanup')
emulator_imagedir = '/tmp/android-%s' % os.environ['USER']
if not os.path.exists(emulator_imagedir):
return
for image in os.listdir(emulator_imagedir):
full_name = os.path.join(emulator_imagedir, image)
if 'emulator' in full_name:
logging.info('Deleting emulator image %s', full_name)
os.unlink(full_name)
def ConfirmLaunch(self, wait_for_boot=False):
"""Confirm the emulator launched properly.
Loop on a wait-for-device with a very small timeout. On each
timeout, check the emulator process is still alive.
After confirming a wait-for-device can be successful, make sure
it returns the right answer.
"""
seconds_waited = 0
number_of_waits = 2 # Make sure we can wfd twice
adb_cmd = "adb -s %s %s" % (self.device, 'wait-for-device')
while seconds_waited < self._LAUNCH_TIMEOUT:
try:
run_command.RunCommand(adb_cmd,
timeout_time=self._WAITFORDEVICE_TIMEOUT,
retry_count=1)
number_of_waits -= 1
if not number_of_waits:
break
except errors.WaitForResponseTimedOutError as e:
seconds_waited += self._WAITFORDEVICE_TIMEOUT
adb_cmd = "adb -s %s %s" % (self.device, 'kill-server')
run_command.RunCommand(adb_cmd)
self.popen.poll()
if self.popen.returncode != None:
raise EmulatorLaunchException('EMULATOR DIED')
if seconds_waited >= self._LAUNCH_TIMEOUT:
raise EmulatorLaunchException('TIMEOUT with wait-for-device')
logging.info('Seconds waited on wait-for-device: %d', seconds_waited)
if wait_for_boot:
# Now that we checked for obvious problems, wait for a boot complete.
# Waiting for the package manager is sometimes problematic.
a = android_commands.AndroidCommands(self.device)
a.WaitForSystemBootCompleted(self._WAITFORBOOT_TIMEOUT)
def Shutdown(self):
"""Shuts down the process started by launch."""
self._DeleteAVD()
if self.popen:
self.popen.poll()
if self.popen.returncode == None:
self.popen.kill()
self.popen = None
def _ShutdownOnSignal(self, signum, frame):
logging.critical('emulator _ShutdownOnSignal')
for sig in self._SIGNALS:
signal.signal(sig, signal.SIG_DFL)
self.Shutdown()
raise KeyboardInterrupt # print a stack
def _InstallKillHandler(self):
"""Install a handler to kill the emulator when we exit unexpectedly."""
for sig in self._SIGNALS:
signal.signal(sig, self._ShutdownOnSignal)
| |
# Copyright 2019 The MLIR 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: %p/test_edsc %s | FileCheck %s
"""Python2 and 3 test for the MLIR EDSC Python bindings"""
import google_mlir.bindings.python.pybind as E
import inspect
# Prints `str` prefixed by the current test function name so we can use it in
# Filecheck label directives.
# This is achieved by inspecting the stack and getting the parent name.
def printWithCurrentFunctionName(str):
print(inspect.stack()[1][3])
print(str)
class EdscTest:
def setUp(self):
self.module = E.MLIRModule()
self.boolType = self.module.make_type("i1")
self.i32Type = self.module.make_type("i32")
self.f32Type = self.module.make_type("f32")
self.indexType = self.module.make_index_type()
def testBlockArguments(self):
self.setUp()
with self.module.function_context("foo", [], []) as fun:
E.constant_index(42)
with E.BlockContext([self.f32Type, self.f32Type]) as b:
b.arg(0) + b.arg(1)
printWithCurrentFunctionName(str(fun))
# CHECK-LABEL: testBlockArguments
# CHECK: %{{.*}} = constant 42 : index
# CHECK: ^bb{{.*}}(%{{.*}}: f32, %{{.*}}: f32):
# CHECK: %{{.*}} = addf %{{.*}}, %{{.*}} : f32
def testBlockContext(self):
self.setUp()
with self.module.function_context("foo", [], []) as fun:
cst = E.constant_index(42)
with E.BlockContext():
cst + cst
printWithCurrentFunctionName(str(fun))
# CHECK-LABEL: testBlockContext
# CHECK: %{{.*}} = constant 42 : index
# CHECK: ^bb
# CHECK: %{{.*}} = "affine.apply"() {map = () -> (84)} : () -> index
def testBlockContextAppend(self):
self.setUp()
with self.module.function_context("foo", [], []) as fun:
E.constant_index(41)
with E.BlockContext() as b:
blk = b # save block handle for later
E.constant_index(0)
E.constant_index(42)
with E.BlockContext(E.appendTo(blk)):
E.constant_index(1)
printWithCurrentFunctionName(str(fun))
# CHECK-LABEL: testBlockContextAppend
# CHECK: %{{.*}} = constant 41 : index
# CHECK: %{{.*}} = constant 42 : index
# CHECK: ^bb
# CHECK: %{{.*}} = constant 0 : index
# CHECK: %{{.*}} = constant 1 : index
def testBlockContextStandalone(self):
self.setUp()
with self.module.function_context("foo", [], []) as fun:
blk1 = E.BlockContext()
blk2 = E.BlockContext()
with blk1:
E.constant_index(0)
with blk2:
E.constant_index(56)
E.constant_index(57)
E.constant_index(41)
with blk1:
E.constant_index(1)
E.constant_index(42)
printWithCurrentFunctionName(str(fun))
# CHECK-LABEL: testBlockContextStandalone
# CHECK: %{{.*}} = constant 41 : index
# CHECK: %{{.*}} = constant 42 : index
# CHECK: ^bb
# CHECK: %{{.*}} = constant 0 : index
# CHECK: %{{.*}} = constant 1 : index
# CHECK: ^bb
# CHECK: %{{.*}} = constant 56 : index
# CHECK: %{{.*}} = constant 57 : index
def testBooleanOps(self):
self.setUp()
with self.module.function_context(
"booleans", [self.boolType for _ in range(4)], []) as fun:
i, j, k, l = (fun.arg(x) for x in range(4))
stmt1 = (i < j) & (j >= k)
stmt2 = ~(stmt1 | (k == l))
printWithCurrentFunctionName(str(fun))
# CHECK-LABEL: testBooleanOps
# CHECK: %{{.*}} = cmpi "slt", %{{.*}}, %{{.*}} : i1
# CHECK: %{{.*}} = cmpi "sge", %{{.*}}, %{{.*}} : i1
# CHECK: %{{.*}} = muli %{{.*}}, %{{.*}} : i1
# CHECK: %{{.*}} = cmpi "eq", %{{.*}}, %{{.*}} : i1
# CHECK: %{{.*}} = constant 1 : i1
# CHECK: %{{.*}} = subi %{{.*}}, %{{.*}} : i1
# CHECK: %{{.*}} = constant 1 : i1
# CHECK: %{{.*}} = subi %{{.*}}, %{{.*}} : i1
# CHECK: %{{.*}} = muli %{{.*}}, %{{.*}} : i1
# CHECK: %{{.*}} = constant 1 : i1
# CHECK: %{{.*}} = subi %{{.*}}, %{{.*}} : i1
# CHECK: %{{.*}} = constant 1 : i1
# CHECK: %{{.*}} = subi %{{.*}}, %{{.*}} : i1
def testBr(self):
self.setUp()
with self.module.function_context("foo", [], []) as fun:
with E.BlockContext() as b:
blk = b
E.ret()
E.br(blk)
printWithCurrentFunctionName(str(fun))
# CHECK-LABEL: testBr
# CHECK: br ^bb
# CHECK: ^bb
# CHECK: return
def testBrArgs(self):
self.setUp()
with self.module.function_context("foo", [], []) as fun:
# Create an infinite loop.
with E.BlockContext([self.indexType, self.indexType]) as b:
E.br(b, [b.arg(1), b.arg(0)])
E.br(b, [E.constant_index(0), E.constant_index(1)])
printWithCurrentFunctionName(str(fun))
# CHECK-LABEL: testBrArgs
# CHECK: %{{.*}} = constant 0 : index
# CHECK: %{{.*}} = constant 1 : index
# CHECK: br ^bb{{.*}}(%{{.*}}, %{{.*}} : index, index)
# CHECK: ^bb{{.*}}(%{{.*}}: index, %{{.*}}: index):
# CHECK: br ^bb{{.*}}(%{{.*}}, %{{.*}} : index, index)
def testBrDeclaration(self):
self.setUp()
with self.module.function_context("foo", [], []) as fun:
blk = E.BlockContext()
E.br(blk.handle())
with blk:
E.ret()
printWithCurrentFunctionName(str(fun))
# CHECK-LABEL: testBrDeclaration
# CHECK: br ^bb
# CHECK: ^bb
# CHECK: return
def testCallOp(self):
self.setUp()
callee = self.module.declare_function("sqrtf", [self.f32Type],
[self.f32Type])
with self.module.function_context("call", [self.f32Type], []) as fun:
funCst = E.constant_function(callee)
funCst([fun.arg(0)]) + E.constant_float(42., self.f32Type)
printWithCurrentFunctionName(str(self.module))
# CHECK-LABEL: testCallOp
# CHECK: func @sqrtf(f32) -> f32
# CHECK: %{{.*}} = constant @sqrtf : (f32) -> f32
# CHECK: %{{.*}} = call_indirect %{{.*}}(%{{.*}}) : (f32) -> f32
def testCondBr(self):
self.setUp()
with self.module.function_context("foo", [self.boolType], []) as fun:
with E.BlockContext() as blk1:
E.ret([])
with E.BlockContext([self.indexType]) as blk2:
E.ret([])
cst = E.constant_index(0)
E.cond_br(fun.arg(0), blk1, [], blk2, [cst])
printWithCurrentFunctionName(str(fun))
# CHECK-LABEL: testCondBr
# CHECK: cond_br %{{.*}}, ^bb{{.*}}, ^bb{{.*}}(%{{.*}} : index)
def testConstants(self):
self.setUp()
with self.module.function_context("constants", [], []) as fun:
E.constant_float(1.23, self.module.make_type("bf16"))
E.constant_float(1.23, self.module.make_type("f16"))
E.constant_float(1.23, self.module.make_type("f32"))
E.constant_float(1.23, self.module.make_type("f64"))
E.constant_int(1, 1)
E.constant_int(123, 8)
E.constant_int(123, 16)
E.constant_int(123, 32)
E.constant_int(123, 64)
E.constant_index(123)
E.constant_function(fun)
printWithCurrentFunctionName(str(fun))
# CHECK-LABEL: testConstants
# CHECK: constant 1.230000e+00 : bf16
# CHECK: constant 1.230470e+00 : f16
# CHECK: constant 1.230000e+00 : f32
# CHECK: constant 1.230000e+00 : f64
# CHECK: constant 1 : i1
# CHECK: constant 123 : i8
# CHECK: constant 123 : i16
# CHECK: constant 123 : i32
# CHECK: constant 123 : index
# CHECK: constant @constants : () -> ()
def testCustom(self):
self.setUp()
with self.module.function_context("custom", [self.indexType, self.f32Type],
[]) as fun:
E.op("foo", [fun.arg(0)], [self.f32Type]) + fun.arg(1)
printWithCurrentFunctionName(str(fun))
# CHECK-LABEL: testCustom
# CHECK: %{{.*}} = "foo"(%{{.*}}) : (index) -> f32
# CHECK: %{{.*}} = addf %{{.*}}, %{{.*}} : f32
# Create 'addi' using the generic Op interface. We need an operation known
# to the execution engine so that the engine can compile it.
def testCustomOpCompilation(self):
self.setUp()
with self.module.function_context("adder", [self.i32Type], []) as f:
c1 = E.op(
"std.constant", [], [self.i32Type],
value=self.module.integerAttr(self.i32Type, 42))
E.op("std.addi", [c1, f.arg(0)], [self.i32Type])
E.ret([])
self.module.compile()
printWithCurrentFunctionName(str(self.module.get_engine_address() == 0))
# CHECK-LABEL: testCustomOpCompilation
# CHECK: False
def testDivisions(self):
self.setUp()
with self.module.function_context(
"division", [self.indexType, self.i32Type, self.i32Type], []) as fun:
# indices only support floor division
fun.arg(0) // E.constant_index(42)
# regular values only support regular division
fun.arg(1) / fun.arg(2)
printWithCurrentFunctionName(str(self.module))
# CHECK-LABEL: testDivisions
# CHECK: floordiv 42
# CHECK: divis %{{.*}}, %{{.*}} : i32
def testFunctionArgs(self):
self.setUp()
with self.module.function_context("foo", [self.f32Type, self.f32Type],
[self.indexType]) as fun:
pass
printWithCurrentFunctionName(str(fun))
# CHECK-LABEL: testFunctionArgs
# CHECK: func @foo(%{{.*}}: f32, %{{.*}}: f32) -> index
def testFunctionContext(self):
self.setUp()
with self.module.function_context("foo", [], []):
pass
printWithCurrentFunctionName(self.module.get_function("foo"))
# CHECK-LABEL: testFunctionContext
# CHECK: func @foo() {
def testFunctionDeclaration(self):
self.setUp()
boolAttr = self.module.boolAttr(True)
t = self.module.make_memref_type(self.f32Type, [10])
t_llvm_noalias = t({"llvm.noalias": boolAttr})
t_readonly = t({"readonly": boolAttr})
f = self.module.declare_function("foo", [t, t_llvm_noalias, t_readonly], [])
printWithCurrentFunctionName(str(self.module))
# CHECK-LABEL: testFunctionDeclaration
# CHECK: func @foo(memref<10xf32>, memref<10xf32> {llvm.noalias = true}, memref<10xf32> {readonly = true})
def testFunctionMultiple(self):
self.setUp()
with self.module.function_context("foo", [], []):
pass
with self.module.function_context("foo", [], []):
E.constant_index(0)
printWithCurrentFunctionName(str(self.module))
# CHECK-LABEL: testFunctionMultiple
# CHECK: func @foo()
# CHECK: func @foo_0()
# CHECK: %{{.*}} = constant 0 : index
def testIndexCast(self):
self.setUp()
with self.module.function_context("testIndexCast", [], []):
index = E.constant_index(0)
E.index_cast(index, self.i32Type)
printWithCurrentFunctionName(str(self.module))
# CHECK-LABEL: testIndexCast
# CHECK: index_cast %{{.*}} : index to i32
def testIndexedValue(self):
self.setUp()
memrefType = self.module.make_memref_type(self.f32Type, [10, 42])
with self.module.function_context("indexed", [memrefType],
[memrefType]) as fun:
A = E.IndexedValue(fun.arg(0))
cst = E.constant_float(1., self.f32Type)
with E.LoopNestContext(
[E.constant_index(0), E.constant_index(0)],
[E.constant_index(10), E.constant_index(42)], [1, 1]) as (i, j):
A.store([i, j], A.load([i, j]) + cst)
E.ret([fun.arg(0)])
printWithCurrentFunctionName(str(fun))
# CHECK-LABEL: testIndexedValue
# CHECK: "affine.for"()
# CHECK: "affine.for"()
# CHECK: "affine.load"
# CHECK-SAME: memref<10x42xf32>
# CHECK: %{{.*}} = addf %{{.*}}, %{{.*}} : f32
# CHECK: "affine.store"
# CHECK-SAME: memref<10x42xf32>
# CHECK: {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (42)}
# CHECK: {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (10)}
def testLoopContext(self):
self.setUp()
with self.module.function_context("foo", [], []) as fun:
lhs = E.constant_index(0)
rhs = E.constant_index(42)
with E.LoopContext(lhs, rhs, 1) as i:
lhs + rhs + i
with E.LoopContext(rhs, rhs + rhs, 2) as j:
x = i + j
printWithCurrentFunctionName(str(fun))
# CHECK-LABEL: testLoopContext
# CHECK: "affine.for"() (
# CHECK: ^bb{{.*}}(%{{.*}}: index):
# CHECK: "affine.for"(%{{.*}}, %{{.*}}) (
# CHECK: ^bb{{.*}}(%{{.*}}: index):
# CHECK: "affine.apply"(%{{.*}}, %{{.*}}) {map = (d0, d1) -> (d0 + d1)} : (index, index) -> index
# CHECK: {lower_bound = (d0) -> (d0), step = 2 : index, upper_bound = (d0) -> (d0)} : (index, index) -> ()
# CHECK: {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (42)}
def testLoopNestContext(self):
self.setUp()
with self.module.function_context("foo", [], []) as fun:
lbs = [E.constant_index(i) for i in range(4)]
ubs = [E.constant_index(10 * i + 5) for i in range(4)]
with E.LoopNestContext(lbs, ubs, [1, 3, 5, 7]) as (i, j, k, l):
i + j + k + l
printWithCurrentFunctionName(str(fun))
# CHECK-LABEL: testLoopNestContext
# CHECK: "affine.for"() (
# CHECK: ^bb{{.*}}(%{{.*}}: index):
# CHECK: "affine.for"() (
# CHECK: ^bb{{.*}}(%{{.*}}: index):
# CHECK: "affine.for"() (
# CHECK: ^bb{{.*}}(%{{.*}}: index):
# CHECK: "affine.for"() (
# CHECK: ^bb{{.*}}(%{{.*}}: index):
# CHECK: %{{.*}} = "affine.apply"(%{{.*}}, %{{.*}}, %{{.*}}, %{{.*}}) {map = (d0, d1, d2, d3) -> (d0 + d1 + d2 + d3)} : (index, index, index, index) -> index
def testMLIRBooleanCompilation(self):
self.setUp()
m = self.module.make_memref_type(self.boolType, [10]) # i1 tensor
with self.module.function_context("mkbooltensor", [m, m], []) as f:
input = E.IndexedValue(f.arg(0))
output = E.IndexedValue(f.arg(1))
zero = E.constant_index(0)
ten = E.constant_index(10)
with E.LoopNestContext([zero] * 3, [ten] * 3, [1] * 3) as (i, j, k):
b1 = (i < j) & (j < k)
b2 = ~b1
b3 = b2 | (k < j)
output.store([i], input.load([i]) & b3)
E.ret([])
self.module.compile()
printWithCurrentFunctionName(str(self.module.get_engine_address() == 0))
# CHECK-LABEL: testMLIRBooleanCompilation
# CHECK: False
def testMLIRFunctionCreation(self):
self.setUp()
module = E.MLIRModule()
t = module.make_type("f32")
m = module.make_memref_type(t, [3, 4, -1, 5])
printWithCurrentFunctionName(str(t))
print(str(m))
print(str(module.make_function("copy", [m, m], [])))
print(str(module.make_function("sqrtf", [t], [t])))
# CHECK-LABEL: testMLIRFunctionCreation
# CHECK: f32
# CHECK: memref<3x4x?x5xf32>
# CHECK: func @copy(%{{.*}}: memref<3x4x?x5xf32>, %{{.*}}: memref<3x4x?x5xf32>) {
# CHECK: func @sqrtf(%{{.*}}: f32) -> f32
def testMLIRScalarTypes(self):
self.setUp()
module = E.MLIRModule()
printWithCurrentFunctionName(str(module.make_type("bf16")))
print(str(module.make_type("f16")))
print(str(module.make_type("f32")))
print(str(module.make_type("f64")))
print(str(module.make_type("i1")))
print(str(module.make_type("i8")))
print(str(module.make_type("i32")))
print(str(module.make_type("i123")))
print(str(module.make_type("index")))
# CHECK-LABEL: testMLIRScalarTypes
# CHECK: bf16
# CHECK: f16
# CHECK: f32
# CHECK: f64
# CHECK: i1
# CHECK: i8
# CHECK: i32
# CHECK: i123
# CHECK: index
def testMatrixMultiply(self):
self.setUp()
memrefType = self.module.make_memref_type(self.f32Type, [32, 32])
with self.module.function_context(
"matmul", [memrefType, memrefType, memrefType], []) as fun:
A = E.IndexedValue(fun.arg(0))
B = E.IndexedValue(fun.arg(1))
C = E.IndexedValue(fun.arg(2))
c0 = E.constant_index(0)
c32 = E.constant_index(32)
with E.LoopNestContext([c0, c0, c0], [c32, c32, c32], [1, 1, 1]) as (i, j,
k):
C.store([i, j], A.load([i, k]) * B.load([k, j]))
E.ret([])
printWithCurrentFunctionName(str(fun))
# CHECK-LABEL: testMatrixMultiply
# CHECK: "affine.for"()
# CHECK: "affine.for"()
# CHECK: "affine.for"()
# CHECK-DAG: %{{.*}} = "affine.load"
# CHECK-DAG: %{{.*}} = "affine.load"
# CHECK: %{{.*}} = mulf %{{.*}}, %{{.*}} : f32
# CHECK: "affine.store"
# CHECK-SAME: memref<32x32xf32>
# CHECK: {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (32)} : () -> ()
# CHECK: {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (32)} : () -> ()
# CHECK: {lower_bound = () -> (0), step = 1 : index, upper_bound = () -> (32)} : () -> ()
def testRet(self):
self.setUp()
with self.module.function_context("foo", [],
[self.indexType, self.indexType]) as fun:
c42 = E.constant_index(42)
c0 = E.constant_index(0)
E.ret([c42, c0])
printWithCurrentFunctionName(str(fun))
# CHECK-LABEL: testRet
# CHECK: %{{.*}} = constant 42 : index
# CHECK: %{{.*}} = constant 0 : index
# CHECK: return %{{.*}}, %{{.*}} : index, index
def testSelectOp(self):
self.setUp()
with self.module.function_context("foo", [self.boolType],
[self.i32Type]) as fun:
a = E.constant_int(42, 32)
b = E.constant_int(0, 32)
E.ret([E.select(fun.arg(0), a, b)])
printWithCurrentFunctionName(str(fun))
# CHECK-LABEL: testSelectOp
# CHECK: %{{.*}} = select %{{.*}}, %{{.*}}, %{{.*}} : i32
# Until python 3.6 this cannot be used because the order in the dict is not the
# order of method declaration.
def runTests():
def isTest(attr):
return inspect.ismethod(attr) and "EdscTest.setUp " not in str(attr)
edscTest = EdscTest()
tests = sorted(filter(isTest,
(getattr(edscTest, attr) for attr in dir(edscTest))),
key = lambda x : str(x))
for test in tests:
test()
if __name__ == '__main__':
runTests()
| |
# Copyright 2011 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 Filter Scheduler.
"""
import mock
from nova import exception
from nova import objects
from nova.scheduler import client
from nova.scheduler.client import report
from nova.scheduler import filter_scheduler
from nova.scheduler import host_manager
from nova.scheduler import utils as scheduler_utils
from nova.scheduler import weights
from nova import test # noqa
from nova.tests.unit.scheduler import test_scheduler
from nova.tests import uuidsentinel as uuids
class FilterSchedulerTestCase(test_scheduler.SchedulerTestCase):
"""Test case for Filter Scheduler."""
driver_cls = filter_scheduler.FilterScheduler
@mock.patch('nova.scheduler.client.SchedulerClient')
def setUp(self, mock_client):
pc_client = mock.Mock(spec=report.SchedulerReportClient)
sched_client = mock.Mock(spec=client.SchedulerClient)
sched_client.reportclient = pc_client
mock_client.return_value = sched_client
self.placement_client = pc_client
super(FilterSchedulerTestCase, self).setUp()
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_claim_resources')
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_get_all_host_states')
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_get_sorted_hosts')
def test_schedule_placement_bad_comms(self, mock_get_hosts,
mock_get_all_states, mock_claim):
"""If there was a problem communicating with the Placement service,
alloc_reqs_by_rp_uuid will be None and we need to avoid trying to claim
in the Placement API.
"""
spec_obj = objects.RequestSpec(
num_instances=1,
flavor=objects.Flavor(memory_mb=512,
root_gb=512,
ephemeral_gb=0,
swap=0,
vcpus=1),
project_id=uuids.project_id,
instance_group=None)
host_state = mock.Mock(spec=host_manager.HostState,
host=mock.sentinel.host, uuid=uuids.cn1)
all_host_states = [host_state]
mock_get_all_states.return_value = all_host_states
mock_get_hosts.return_value = all_host_states
instance_uuids = None
ctx = mock.Mock()
selected_hosts = self.driver._schedule(ctx, spec_obj,
instance_uuids, None, mock.sentinel.provider_summaries)
mock_get_all_states.assert_called_once_with(
ctx.elevated.return_value, spec_obj,
mock.sentinel.provider_summaries)
mock_get_hosts.assert_called_once_with(spec_obj, all_host_states, 0)
self.assertEqual(len(selected_hosts), 1)
self.assertEqual([host_state], selected_hosts)
# Ensure that we have consumed the resources on the chosen host states
host_state.consume_from_request.assert_called_once_with(spec_obj)
# And ensure we never called _claim_resources()
self.assertFalse(mock_claim.called)
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_claim_resources')
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_get_all_host_states')
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_get_sorted_hosts')
def test_schedule_old_conductor(self, mock_get_hosts,
mock_get_all_states, mock_claim):
"""Old conductor can call scheduler without the instance_uuids
parameter. When this happens, we need to ensure we do not attempt to
claim resources in the placement API since obviously we need instance
UUIDs to perform those claims.
"""
spec_obj = objects.RequestSpec(
num_instances=1,
flavor=objects.Flavor(memory_mb=512,
root_gb=512,
ephemeral_gb=0,
swap=0,
vcpus=1),
project_id=uuids.project_id,
instance_group=None)
host_state = mock.Mock(spec=host_manager.HostState,
host=mock.sentinel.host, uuid=uuids.cn1)
all_host_states = [host_state]
mock_get_all_states.return_value = all_host_states
mock_get_hosts.return_value = all_host_states
instance_uuids = None
ctx = mock.Mock()
selected_hosts = self.driver._schedule(ctx, spec_obj,
instance_uuids, mock.sentinel.alloc_reqs_by_rp_uuid,
mock.sentinel.provider_summaries)
mock_get_all_states.assert_called_once_with(
ctx.elevated.return_value, spec_obj,
mock.sentinel.provider_summaries)
mock_get_hosts.assert_called_once_with(spec_obj, all_host_states, 0)
self.assertEqual(len(selected_hosts), 1)
self.assertEqual([host_state], selected_hosts)
# Ensure that we have consumed the resources on the chosen host states
host_state.consume_from_request.assert_called_once_with(spec_obj)
# And ensure we never called _claim_resources()
self.assertFalse(mock_claim.called)
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_claim_resources')
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_get_all_host_states')
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_get_sorted_hosts')
def _test_schedule_successful_claim(self, mock_get_hosts,
mock_get_all_states, mock_claim, num_instances=1):
spec_obj = objects.RequestSpec(
num_instances=num_instances,
flavor=objects.Flavor(memory_mb=512,
root_gb=512,
ephemeral_gb=0,
swap=0,
vcpus=1),
project_id=uuids.project_id,
instance_group=None)
host_state = mock.Mock(spec=host_manager.HostState,
host=mock.sentinel.host, uuid=uuids.cn1)
all_host_states = [host_state]
mock_get_all_states.return_value = all_host_states
mock_get_hosts.return_value = all_host_states
mock_claim.return_value = True
instance_uuids = [uuids.instance]
alloc_reqs_by_rp_uuid = {
uuids.cn1: [mock.sentinel.alloc_req],
}
ctx = mock.Mock()
selected_hosts = self.driver._schedule(ctx, spec_obj,
instance_uuids, alloc_reqs_by_rp_uuid,
mock.sentinel.provider_summaries)
mock_get_all_states.assert_called_once_with(
ctx.elevated.return_value, spec_obj,
mock.sentinel.provider_summaries)
mock_get_hosts.assert_called_once_with(spec_obj, all_host_states, 0)
mock_claim.assert_called_once_with(ctx.elevated.return_value, spec_obj,
uuids.instance, [mock.sentinel.alloc_req])
self.assertEqual(len(selected_hosts), 1)
self.assertEqual([host_state], selected_hosts)
# Ensure that we have consumed the resources on the chosen host states
host_state.consume_from_request.assert_called_once_with(spec_obj)
def test_schedule_successful_claim(self):
self._test_schedule_successful_claim()
def test_schedule_old_reqspec_and_move_operation(self):
"""This test is for verifying that in case of a move operation with an
original RequestSpec created for 3 concurrent instances, we only verify
the instance that is moved.
"""
self._test_schedule_successful_claim(num_instances=3)
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_cleanup_allocations')
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_claim_resources')
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_get_all_host_states')
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_get_sorted_hosts')
def test_schedule_unsuccessful_claim(self, mock_get_hosts,
mock_get_all_states, mock_claim, mock_cleanup):
"""Tests that we return an empty list if we are unable to successfully
claim resources for the instance
"""
spec_obj = objects.RequestSpec(
num_instances=1,
flavor=objects.Flavor(memory_mb=512,
root_gb=512,
ephemeral_gb=0,
swap=0,
vcpus=1),
project_id=uuids.project_id,
instance_group=None)
host_state = mock.Mock(spec=host_manager.HostState,
host=mock.sentinel.host, uuid=uuids.cn1)
all_host_states = [host_state]
mock_get_all_states.return_value = all_host_states
mock_get_hosts.return_value = all_host_states
mock_claim.return_value = False
instance_uuids = [uuids.instance]
alloc_reqs_by_rp_uuid = {
uuids.cn1: [mock.sentinel.alloc_req],
}
ctx = mock.Mock()
selected_hosts = self.driver._schedule(ctx, spec_obj,
instance_uuids, alloc_reqs_by_rp_uuid,
mock.sentinel.provider_summaries)
mock_get_all_states.assert_called_once_with(
ctx.elevated.return_value, spec_obj,
mock.sentinel.provider_summaries)
mock_get_hosts.assert_called_once_with(spec_obj, all_host_states, 0)
mock_claim.assert_called_once_with(ctx.elevated.return_value, spec_obj,
uuids.instance, [mock.sentinel.alloc_req])
self.assertEqual([], selected_hosts)
mock_cleanup.assert_called_once_with([])
# Ensure that we have consumed the resources on the chosen host states
self.assertFalse(host_state.consume_from_request.called)
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_cleanup_allocations')
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_claim_resources')
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_get_all_host_states')
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_get_sorted_hosts')
def test_schedule_not_all_instance_clean_claimed(self, mock_get_hosts,
mock_get_all_states, mock_claim, mock_cleanup):
"""Tests that we clean up previously-allocated instances if not all
instances could be scheduled
"""
spec_obj = objects.RequestSpec(
num_instances=2,
flavor=objects.Flavor(memory_mb=512,
root_gb=512,
ephemeral_gb=0,
swap=0,
vcpus=1),
project_id=uuids.project_id,
instance_group=None)
host_state = mock.Mock(spec=host_manager.HostState,
host=mock.sentinel.host, uuid=uuids.cn1)
all_host_states = [host_state]
mock_get_all_states.return_value = all_host_states
mock_get_hosts.side_effect = [
all_host_states, # first return all the hosts (only one)
[], # then act as if no more hosts were found that meet criteria
]
mock_claim.return_value = True
instance_uuids = [uuids.instance1, uuids.instance2]
alloc_reqs_by_rp_uuid = {
uuids.cn1: [mock.sentinel.alloc_req],
}
ctx = mock.Mock()
self.driver._schedule(ctx, spec_obj, instance_uuids,
alloc_reqs_by_rp_uuid, mock.sentinel.provider_summaries)
# Ensure we cleaned up the first successfully-claimed instance
mock_cleanup.assert_called_once_with([uuids.instance1])
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_claim_resources')
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_get_all_host_states')
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_get_sorted_hosts')
def test_schedule_instance_group(self, mock_get_hosts,
mock_get_all_states, mock_claim):
"""Test that since the request spec object contains an instance group
object, that upon choosing a host in the primary schedule loop,
that we update the request spec's instance group information
"""
num_instances = 2
ig = objects.InstanceGroup(hosts=[])
spec_obj = objects.RequestSpec(
num_instances=num_instances,
flavor=objects.Flavor(memory_mb=512,
root_gb=512,
ephemeral_gb=0,
swap=0,
vcpus=1),
project_id=uuids.project_id,
instance_group=ig)
hs1 = mock.Mock(spec=host_manager.HostState, host='host1',
uuid=uuids.cn1)
hs2 = mock.Mock(spec=host_manager.HostState, host='host2',
uuid=uuids.cn2)
all_host_states = [hs1, hs2]
mock_get_all_states.return_value = all_host_states
mock_claim.return_value = True
alloc_reqs_by_rp_uuid = {
uuids.cn1: [mock.sentinel.alloc_req_cn1],
uuids.cn2: [mock.sentinel.alloc_req_cn2],
}
# Simulate host 1 and host 2 being randomly returned first by
# _get_sorted_hosts() in the two iterations for each instance in
# num_instances
mock_get_hosts.side_effect = ([hs2, hs1], [hs1, hs2])
instance_uuids = [
getattr(uuids, 'instance%d' % x) for x in range(num_instances)
]
ctx = mock.Mock()
self.driver._schedule(ctx, spec_obj, instance_uuids,
alloc_reqs_by_rp_uuid, mock.sentinel.provider_summaries)
# Check that we called _claim_resources() for both the first and second
# host state
claim_calls = [
mock.call(ctx.elevated.return_value, spec_obj,
uuids.instance0, [mock.sentinel.alloc_req_cn2]),
mock.call(ctx.elevated.return_value, spec_obj,
uuids.instance1, [mock.sentinel.alloc_req_cn1]),
]
mock_claim.assert_has_calls(claim_calls)
# Check that _get_sorted_hosts() is called twice and that the
# second time, we pass it the hosts that were returned from
# _get_sorted_hosts() the first time
sorted_host_calls = [
mock.call(spec_obj, all_host_states, 0),
mock.call(spec_obj, [hs2, hs1], 1),
]
mock_get_hosts.assert_has_calls(sorted_host_calls)
# The instance group object should have both host1 and host2 in its
# instance group hosts list and there should not be any "changes" to
# save in the instance group object
self.assertEqual(['host2', 'host1'], ig.hosts)
self.assertEqual({}, ig.obj_get_changes())
@mock.patch('random.choice', side_effect=lambda x: x[1])
@mock.patch('nova.scheduler.host_manager.HostManager.get_weighed_hosts')
@mock.patch('nova.scheduler.host_manager.HostManager.get_filtered_hosts')
def test_get_sorted_hosts(self, mock_filt, mock_weighed, mock_rand):
"""Tests the call that returns a sorted list of hosts by calling the
host manager's filtering and weighing routines
"""
self.flags(host_subset_size=2, group='filter_scheduler')
hs1 = mock.Mock(spec=host_manager.HostState, host='host1')
hs2 = mock.Mock(spec=host_manager.HostState, host='host2')
all_host_states = [hs1, hs2]
mock_weighed.return_value = [
weights.WeighedHost(hs1, 1.0), weights.WeighedHost(hs2, 1.0),
]
results = self.driver._get_sorted_hosts(mock.sentinel.spec,
all_host_states, mock.sentinel.index)
mock_filt.assert_called_once_with(all_host_states, mock.sentinel.spec,
mock.sentinel.index)
mock_weighed.assert_called_once_with(mock_filt.return_value,
mock.sentinel.spec)
# We override random.choice() to pick the **second** element of the
# returned weighed hosts list, which is the host state #2. This tests
# the code path that combines the randomly-chosen host with the
# remaining list of weighed host state objects
self.assertEqual([hs2, hs1], results)
@mock.patch('random.choice', side_effect=lambda x: x[0])
@mock.patch('nova.scheduler.host_manager.HostManager.get_weighed_hosts')
@mock.patch('nova.scheduler.host_manager.HostManager.get_filtered_hosts')
def test_get_sorted_hosts_subset_less_than_num_weighed(self, mock_filt,
mock_weighed, mock_rand):
"""Tests that when we have >1 weighed hosts but a host subset size of
1, that we always pick the first host in the weighed host
"""
self.flags(host_subset_size=1, group='filter_scheduler')
hs1 = mock.Mock(spec=host_manager.HostState, host='host1')
hs2 = mock.Mock(spec=host_manager.HostState, host='host2')
all_host_states = [hs1, hs2]
mock_weighed.return_value = [
weights.WeighedHost(hs1, 1.0), weights.WeighedHost(hs2, 1.0),
]
results = self.driver._get_sorted_hosts(mock.sentinel.spec,
all_host_states, mock.sentinel.index)
mock_filt.assert_called_once_with(all_host_states, mock.sentinel.spec,
mock.sentinel.index)
mock_weighed.assert_called_once_with(mock_filt.return_value,
mock.sentinel.spec)
# We should be randomly selecting only from a list of one host state
mock_rand.assert_called_once_with([hs1])
self.assertEqual([hs1, hs2], results)
@mock.patch('random.choice', side_effect=lambda x: x[0])
@mock.patch('nova.scheduler.host_manager.HostManager.get_weighed_hosts')
@mock.patch('nova.scheduler.host_manager.HostManager.get_filtered_hosts')
def test_get_sorted_hosts_subset_greater_than_num_weighed(self, mock_filt,
mock_weighed, mock_rand):
"""Hosts should still be chosen if host subset size is larger than
number of weighed hosts.
"""
self.flags(host_subset_size=20, group='filter_scheduler')
hs1 = mock.Mock(spec=host_manager.HostState, host='host1')
hs2 = mock.Mock(spec=host_manager.HostState, host='host2')
all_host_states = [hs1, hs2]
mock_weighed.return_value = [
weights.WeighedHost(hs1, 1.0), weights.WeighedHost(hs2, 1.0),
]
results = self.driver._get_sorted_hosts(mock.sentinel.spec,
all_host_states, mock.sentinel.index)
mock_filt.assert_called_once_with(all_host_states, mock.sentinel.spec,
mock.sentinel.index)
mock_weighed.assert_called_once_with(mock_filt.return_value,
mock.sentinel.spec)
# We overrode random.choice() to return the first element in the list,
# so even though we had a host_subset_size greater than the number of
# weighed hosts (2), we just random.choice() on the entire set of
# weighed hosts and thus return [hs1, hs2]
self.assertEqual([hs1, hs2], results)
def test_cleanup_allocations(self):
instance_uuids = []
# Check we don't do anything if there's no instance UUIDs to cleanup
# allocations for
pc = self.placement_client
self.driver._cleanup_allocations(instance_uuids)
self.assertFalse(pc.delete_allocation_for_instance.called)
instance_uuids = [uuids.instance1, uuids.instance2]
self.driver._cleanup_allocations(instance_uuids)
exp_calls = [mock.call(uuids.instance1), mock.call(uuids.instance2)]
pc.delete_allocation_for_instance.assert_has_calls(exp_calls)
def test_claim_resources(self):
"""Tests that when _schedule() calls _claim_resources(), that we
appropriately call the placement client to claim resources for the
instance.
"""
ctx = mock.Mock(user_id=uuids.user_id)
spec_obj = mock.Mock(project_id=uuids.project_id)
instance_uuid = uuids.instance
alloc_reqs = [mock.sentinel.alloc_req]
res = self.driver._claim_resources(ctx, spec_obj, instance_uuid,
alloc_reqs)
pc = self.placement_client
pc.claim_resources.return_value = True
pc.claim_resources.assert_called_once_with(uuids.instance,
mock.sentinel.alloc_req, uuids.project_id, uuids.user_id)
self.assertTrue(res)
def test_add_retry_host(self):
retry = dict(num_attempts=1, hosts=[])
filter_properties = dict(retry=retry)
host = "fakehost"
node = "fakenode"
scheduler_utils._add_retry_host(filter_properties, host, node)
hosts = filter_properties['retry']['hosts']
self.assertEqual(1, len(hosts))
self.assertEqual([host, node], hosts[0])
def test_post_select_populate(self):
# Test addition of certain filter props after a node is selected.
retry = {'hosts': [], 'num_attempts': 1}
filter_properties = {'retry': retry}
host_state = host_manager.HostState('host', 'node', uuids.cell)
host_state.limits['vcpu'] = 5
scheduler_utils.populate_filter_properties(filter_properties,
host_state)
self.assertEqual(['host', 'node'],
filter_properties['retry']['hosts'][0])
self.assertEqual({'vcpu': 5}, host_state.limits)
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_schedule')
def test_select_destinations_match_num_instances(self, mock_schedule):
"""Tests that the select_destinations() method returns the list of
hosts from the _schedule() method when the number of returned hosts
equals the num_instances on the spec object
"""
spec_obj = objects.RequestSpec(
flavor=objects.Flavor(memory_mb=512,
root_gb=512,
ephemeral_gb=0,
swap=0,
vcpus=1),
project_id=uuids.project_id,
num_instances=1)
mock_schedule.return_value = [mock.sentinel.hs1]
dests = self.driver.select_destinations(self.context, spec_obj,
mock.sentinel.instance_uuids, mock.sentinel.alloc_reqs_by_rp_uuid,
mock.sentinel.p_sums)
mock_schedule.assert_called_once_with(self.context, spec_obj,
mock.sentinel.instance_uuids, mock.sentinel.alloc_reqs_by_rp_uuid,
mock.sentinel.p_sums)
self.assertEqual([mock.sentinel.hs1], dests)
@mock.patch('nova.scheduler.filter_scheduler.FilterScheduler.'
'_schedule')
def test_select_destinations_fewer_num_instances(self, mock_schedule):
"""Tests that the select_destinations() method properly handles
resetting host state objects and raising NoValidHost when the
_schedule() method returns no host matches.
"""
spec_obj = objects.RequestSpec(
flavor=objects.Flavor(memory_mb=512,
root_gb=512,
ephemeral_gb=0,
swap=0,
vcpus=1),
project_id=uuids.project_id,
num_instances=2)
host_state = mock.Mock(spec=host_manager.HostState)
mock_schedule.return_value = [host_state]
self.assertRaises(exception.NoValidHost,
self.driver.select_destinations, self.context, spec_obj,
mock.sentinel.instance_uuids, mock.sentinel.alloc_reqs_by_rp_uuid,
mock.sentinel.p_sums)
# Verify that the host state object has been marked as not updated so
# it's picked up in the next pull from the DB for compute node objects
self.assertIsNone(host_state.updated)
@mock.patch.object(filter_scheduler.FilterScheduler, '_schedule')
def test_select_destinations_notifications(self, mock_schedule):
mock_schedule.return_value = [mock.Mock()]
with mock.patch.object(self.driver.notifier, 'info') as mock_info:
expected = {'num_instances': 1,
'instance_properties': {'uuid': uuids.instance},
'instance_type': {},
'image': {}}
spec_obj = objects.RequestSpec(num_instances=1,
instance_uuid=uuids.instance)
self.driver.select_destinations(self.context, spec_obj,
[uuids.instance], {}, None)
expected = [
mock.call(self.context, 'scheduler.select_destinations.start',
dict(request_spec=expected)),
mock.call(self.context, 'scheduler.select_destinations.end',
dict(request_spec=expected))]
self.assertEqual(expected, mock_info.call_args_list)
| |
# coding: utf-8
####################### To Do list ##################################
#TODO remove all methods which involve writing , or the feature part. after pickling the data.
__author__ = 'kobi_luria'
import requests
import json
import objects
import os
import tools
import pickle
################## END_POINTS #################################:
NOMINATIM = 'http://nominatim.openstreetmap.org/search?accept-language=en-us&q='
NOMINATIM_FORMAT = '&format=json&polygon_geojson=1&addressdetails=1'
API = 'http://api.dev.openmuni.org.il/'
VERSION = 'v1/'
ENTITIES = 'entities/'
DIR_PROJECT = '/home/kobi/projects/open_gis'
DIR = '/home/kobi/projects/open_gis/jsonp/maps'
GEO_JSON = '.geojson'
#################################################################
def write_to_file(parent_path, name_en, json_object):
"""
write a polygon object which is a muni or district to file. this method will produce all
the folders and file for the single muni and district files.
:param parent_path: the parent path to write this file
:param name_en: the name of the file or object.
:param json_object: the json object which is written to file.
:return:
"""
dir_path = os.path.join(DIR, parent_path).rstrip(name_en).replace(' ', '_').lower()
if not os.path.exists(dir_path):
os.makedirs(dir_path)
path = os.path.join(dir_path, name_en + GEO_JSON).replace(' ', '_').lower()
f = open(path, 'w+')
f.write('map_func(')
json.dump(json_object, f)
f.write(')')
f.close()
def make_feature(json_polygon, json_properties):
"""
make a feature geojson from a json-polygon object.
this function just wrappes the polygon and the feature properties
into the the json feature. the properties can then be viewed in any map!
:param json_polygon: the polygon of a muni or district.
:param json_properties: the properties which are added on to the coordinate polygon.
:return: the feature which is a coordinates and properties.
"""
feature = {'type': 'Feature', 'geometry': json_polygon, 'properties': json_properties}
return feature
def get_geojson_for_muni(search_string):
"""
this funcction gets the geo GIS coordinate for each entity.
the function currently calles the NOMINATIM server with a search string.
The only case which a result is picked is if the osm-type is a relation i.e its
a entity in the open street map system.
:param search_string: the search string that the nominatim server should run.
:return: if a entity is found a polygon json is returned else None.
"""
#TODO i think we can run a for loop in the results in case their is more then one.
url = NOMINATIM + search_string + NOMINATIM_FORMAT
result = requests.get(url)
data = json.loads(result.text)
if len(data) == 0:
return None # their were no results from the nominatim server.
data = data[0]
if data['geojson'] and data['osm_type'] == 'relation':
polygon = data['geojson']
return polygon # found a hit
else:
return None # the search results didn't come up with a entity.
def get_entity_polygon(entity):
"""
this is a caller function which sends a search request to the muni finder. and iterates on all search strings.
if found a match it will return a entity geojson feature. o
this funciton will print the search results which were found and not found.
A file with all entitys not found will be proccesed in the higher level.
:param entity: the entity which is searched for in the GIS databases
:return: True if found and added the feature to the object , False otherwise.
"""
for name in entity.search_list:
polygon = get_geojson_for_muni(name)
if polygon:
print '****************** found : ' + name + '*********************************'
entity.add_polygon(polygon)
return True
else:
print '******************** did not find ************ ' + name + ' ********** '
return False
def create_features_for_entites(entity_list):
for entity in entity_list:
properties = {'name_en': entity.name_en, 'id': entity.id, 'code': entity.code,
'division_id' : entity.division_id,
'copyright': 'ODBL , http://www.openstreetmap.org/copyright'}
feature = make_feature(entity.polygon, properties)
entity.add_geojson_feature(feature)
def create_empty_list(entity_list):
for entity in entity_list:
print entity.name_en, entity.code
def get_district_and_muni(url, entity_list):
"""
This is the district and muni finder main() . it searchs a url from the open-muni API for all results and finds all
Gis data it can find using these results.
:param url: the url which is the lookup for all muni's in the open-muni API
:param entity_list: the entity_list this is mostly here because of the recursive behivior of the function.
:return: returns a entity dictionary which has all entity's found and all which aren't.
"""
print url
data = tools.get_data_as_dict(url)
next_page = ''
if data['next']:
next_page = data['next']
results_list = data['results']
for result in results_list:
if not result['name_en']:
#TODO add support for results with no english keyword
continue # if their is no name in english. i can't store the files for now so continue.
entity = objects.entity(result)
if get_entity_polygon(entity):
entity_list['found'].append(entity) # if found add to the entity list
else:
entity_list['not_found'].append(entity)
if next_page:
get_district_and_muni(next_page, entity_list)
return entity_list
def write_entities_to_file(entity_list):
"""
Write all entites from a list of entity objects to file.
the file which the entity will be writen to is depended on the file path and parent's name of the entity.
i.e each muni , if the muni has a district the muni will be placed under the district.
:param entity_list: the entity list to add to folders and files.
"""
print 'writing ' + str(len(entity_list)) + ' to file'
for entity in entity_list:
write_to_file(entity.parent_path, entity.name_en, entity.geojson)
def colorEntitybyTax(entity_geojson):
def write_entities_to_israel_map(entity_list):
#todo don't write the district info or maybe write a different function for this use case.
"""
write all entities which belong to israel into a big Map of israel.
:param entity_list: the entity list to add to the big map.
"""
geojson = {'type': 'FeatureCollection', 'features': []}
for entity in entity_list:
if entity.geojson['properties']['id'] == 11:
continue
entity.geojson = colorEntityByTax(entity.geojson)
geojson['features'].append(entity.geojson)
f = open('/home/kobi/projects/open_gis/the_map/yogevMap.geojson', 'w+')
json.dump(geojson, f)
############################### driver : ####################################
# i pickle the information since i don't want all data to be lost i their is an I.O Error.
# this is mostly because i wanted to get the GIS , and then write to file as a different proccess
# could be changed in the future.
#entity_list = get_district_and_muni(API + VERSION + ENTITIES + '?domains=1', {'found': [], 'not_found': []})
#pickle.dump(entity_list, open('/home/kobi/projects/open_gis/testing/entity_list_pickle2', 'wb'))
entity_list = pickle.load(open('/home/kobi/projects/open_gis/testing/entity_list_pickle2', 'rb'))
create_features_for_entites(entity_list['found']) # create features for all the entites found.
print 'amount found : ' + str(len(entity_list['found']))
print 'amount not found : ' + str(len(entity_list['not_found']))
write_entities_to_israel_map(entity_list['found'])
write_entities_to_file(entity_list['found'])
| |
# PyAlgoTrade
#
# Copyright 2011-2015 Gabriel Martin Becedillas Ruiz
#
# 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.
"""
.. moduleauthor:: Gabriel Martin Becedillas Ruiz <gabriel.becedillas@gmail.com>
"""
import abc
from pyalgotrade import broker
from pyalgotrade.broker import fillstrategy
from pyalgotrade import warninghelpers
from pyalgotrade import logger
import pyalgotrade.bar
######################################################################
# Commission models
class Commission(object):
"""Base class for implementing different commission schemes.
.. note::
This is a base class and should not be used directly.
"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def calculate(self, order, price, quantity):
"""Calculates the commission for an order execution.
:param order: The order being executed.
:type order: :class:`pyalgotrade.broker.Order`.
:param price: The price for each share.
:type price: float.
:param quantity: The order size.
:type quantity: float.
:rtype: float.
"""
raise NotImplementedError()
class NoCommission(Commission):
"""A :class:`Commission` class that always returns 0."""
def calculate(self, order, price, quantity):
return 0
class FixedPerTrade(Commission):
"""A :class:`Commission` class that charges a fixed amount for the whole trade.
:param amount: The commission for an order.
:type amount: float.
"""
def __init__(self, amount):
self.__amount = amount
def calculate(self, order, price, quantity):
ret = 0
# Only charge the first fill.
if order.getExecutionInfo() is None:
ret = self.__amount
return ret
class TradePercentage(Commission):
"""A :class:`Commission` class that charges a percentage of the whole trade.
:param percentage: The percentage to charge. 0.01 means 1%, and so on. It must be smaller than 1.
:type percentage: float.
"""
def __init__(self, percentage):
assert(percentage < 1)
self.__percentage = percentage
def calculate(self, order, price, quantity):
return price * quantity * self.__percentage
######################################################################
# Orders
class BacktestingOrder(object):
def __init__(self):
self.__accepted = None
def setAcceptedDateTime(self, dateTime):
self.__accepted = dateTime
def getAcceptedDateTime(self):
return self.__accepted
# Override to call the fill strategy using the concrete order type.
# return FillInfo or None if the order should not be filled.
def process(self, broker_, bar_):
raise NotImplementedError()
class MarketOrder(broker.MarketOrder, BacktestingOrder):
def __init__(self, action, instrument, quantity, onClose, instrumentTraits):
broker.MarketOrder.__init__(self, action, instrument, quantity, onClose, instrumentTraits)
BacktestingOrder.__init__(self)
def process(self, broker_, bar_):
return broker_.getFillStrategy().fillMarketOrder(broker_, self, bar_)
class LimitOrder(broker.LimitOrder, BacktestingOrder):
def __init__(self, action, instrument, limitPrice, quantity, instrumentTraits):
broker.LimitOrder.__init__(self, action, instrument, limitPrice, quantity, instrumentTraits)
BacktestingOrder.__init__(self)
def process(self, broker_, bar_):
return broker_.getFillStrategy().fillLimitOrder(broker_, self, bar_)
class StopOrder(broker.StopOrder, BacktestingOrder):
def __init__(self, action, instrument, stopPrice, quantity, instrumentTraits):
broker.StopOrder.__init__(self, action, instrument, stopPrice, quantity, instrumentTraits)
BacktestingOrder.__init__(self)
self.__stopHit = False
def process(self, broker_, bar_):
return broker_.getFillStrategy().fillStopOrder(broker_, self, bar_)
def setStopHit(self, stopHit):
self.__stopHit = stopHit
def getStopHit(self):
return self.__stopHit
# http://www.sec.gov/answers/stoplim.htm
# http://www.interactivebrokers.com/en/trading/orders/stopLimit.php
class StopLimitOrder(broker.StopLimitOrder, BacktestingOrder):
def __init__(self, action, instrument, stopPrice, limitPrice, quantity, instrumentTraits):
broker.StopLimitOrder.__init__(self, action, instrument, stopPrice, limitPrice, quantity, instrumentTraits)
BacktestingOrder.__init__(self)
self.__stopHit = False # Set to true when the limit order is activated (stop price is hit)
def setStopHit(self, stopHit):
self.__stopHit = stopHit
def getStopHit(self):
return self.__stopHit
def isLimitOrderActive(self):
# TODO: Deprecated since v0.15. Use getStopHit instead.
return self.__stopHit
def process(self, broker_, bar_):
return broker_.getFillStrategy().fillStopLimitOrder(broker_, self, bar_)
######################################################################
# Broker
class Broker(broker.Broker):
"""Backtesting broker.
:param cash: The initial amount of cash.
:type cash: int/float.
:param barFeed: The bar feed that will provide the bars.
:type barFeed: :class:`pyalgotrade.barfeed.BarFeed`
:param commission: An object responsible for calculating order commissions.
:type commission: :class:`Commission`
"""
LOGGER_NAME = "broker.backtesting"
def __init__(self, cash, barFeed, commission=None):
broker.Broker.__init__(self)
assert(cash >= 0)
self.__cash = cash
if commission is None:
self.__commission = NoCommission()
else:
self.__commission = commission
self.__shares = {}
self.__activeOrders = {}
self.__useAdjustedValues = False
self.__fillStrategy = fillstrategy.DefaultStrategy()
self.__logger = logger.getLogger(Broker.LOGGER_NAME)
# It is VERY important that the broker subscribes to barfeed events before the strategy.
barFeed.getNewValuesEvent().subscribe(self.onBars)
self.__barFeed = barFeed
self.__allowNegativeCash = False
self.__nextOrderId = 1
def _getNextOrderId(self):
ret = self.__nextOrderId
self.__nextOrderId += 1
return ret
def _getBar(self, bars, instrument):
ret = bars.getBar(instrument)
if ret is None:
ret = self.__barFeed.getLastBar(instrument)
return ret
def _registerOrder(self, order):
assert(order.getId() not in self.__activeOrders)
assert(order.getId() is not None)
self.__activeOrders[order.getId()] = order
def _unregisterOrder(self, order):
assert(order.getId() in self.__activeOrders)
assert(order.getId() is not None)
del self.__activeOrders[order.getId()]
def getLogger(self):
return self.__logger
def setAllowNegativeCash(self, allowNegativeCash):
self.__allowNegativeCash = allowNegativeCash
def getCash(self, includeShort=True):
ret = self.__cash
if not includeShort and self.__barFeed.getCurrentBars() is not None:
bars = self.__barFeed.getCurrentBars()
for instrument, shares in self.__shares.iteritems():
if shares < 0:
instrumentPrice = self._getBar(bars, instrument).getClose(self.getUseAdjustedValues())
ret += instrumentPrice * shares
return ret
def setCash(self, cash):
self.__cash = cash
def getCommission(self):
"""Returns the strategy used to calculate order commissions.
:rtype: :class:`Commission`.
"""
return self.__commission
def setCommission(self, commission):
"""Sets the strategy to use to calculate order commissions.
:param commission: An object responsible for calculating order commissions.
:type commission: :class:`Commission`.
"""
self.__commission = commission
def setFillStrategy(self, strategy):
"""Sets the :class:`pyalgotrade.broker.fillstrategy.FillStrategy` to use."""
self.__fillStrategy = strategy
def getFillStrategy(self):
"""Returns the :class:`pyalgotrade.broker.fillstrategy.FillStrategy` currently set."""
return self.__fillStrategy
def getUseAdjustedValues(self):
return self.__useAdjustedValues
def setUseAdjustedValues(self, useAdjusted, deprecationCheck=None):
# Deprecated since v0.15
if not self.__barFeed.barsHaveAdjClose():
raise Exception("The barfeed doesn't support adjusted close values")
if deprecationCheck is None:
warninghelpers.deprecation_warning(
"setUseAdjustedValues will be deprecated in the next version. Please use setUseAdjustedValues on the strategy instead.",
stacklevel=2
)
self.__useAdjustedValues = useAdjusted
def getActiveOrders(self, instrument=None):
if instrument is None:
ret = self.__activeOrders.values()
else:
ret = [order for order in self.__activeOrders.values() if order.getInstrument() == instrument]
return ret
def getPendingOrders(self):
warninghelpers.deprecation_warning(
"getPendingOrders will be deprecated in the next version. Please use getActiveOrders instead.",
stacklevel=2
)
return self.getActiveOrders()
def _getCurrentDateTime(self):
return self.__barFeed.getCurrentDateTime()
def getInstrumentTraits(self, instrument):
return broker.IntegerTraits()
def getShares(self, instrument):
return self.__shares.get(instrument, 0)
def getPositions(self):
return self.__shares
def getActiveInstruments(self):
return [instrument for instrument, shares in self.__shares.iteritems() if shares != 0]
def __getEquityWithBars(self, bars):
ret = self.getCash()
if bars is not None:
for instrument, shares in self.__shares.iteritems():
instrumentPrice = self._getBar(bars, instrument).getClose(self.getUseAdjustedValues())
ret += instrumentPrice * shares
return ret
def getEquity(self):
"""Returns the portfolio value (cash + shares)."""
return self.__getEquityWithBars(self.__barFeed.getCurrentBars())
# Tries to commit an order execution.
def commitOrderExecution(self, order, dateTime, fillInfo):
price = fillInfo.getPrice()
quantity = fillInfo.getQuantity()
if order.isBuy():
cost = price * quantity * -1
assert(cost < 0)
sharesDelta = quantity
elif order.isSell():
cost = price * quantity
assert(cost > 0)
sharesDelta = quantity * -1
else: # Unknown action
assert(False)
commission = self.getCommission().calculate(order, price, quantity)
cost -= commission
resultingCash = self.getCash() + cost
# Check that we're ok on cash after the commission.
if resultingCash >= 0 or self.__allowNegativeCash:
# Update the order before updating internal state since addExecutionInfo may raise.
# addExecutionInfo should switch the order state.
orderExecutionInfo = broker.OrderExecutionInfo(price, quantity, commission, dateTime)
order.addExecutionInfo(orderExecutionInfo)
# Commit the order execution.
self.__cash = resultingCash
updatedShares = order.getInstrumentTraits().roundQuantity(
self.getShares(order.getInstrument()) + sharesDelta
)
if updatedShares == 0:
del self.__shares[order.getInstrument()]
else:
self.__shares[order.getInstrument()] = updatedShares
# Let the strategy know that the order was filled.
self.__fillStrategy.onOrderFilled(self, order)
# Notify the order update
if order.isFilled():
self._unregisterOrder(order)
self.notifyOrderEvent(broker.OrderEvent(order, broker.OrderEvent.Type.FILLED, orderExecutionInfo))
elif order.isPartiallyFilled():
self.notifyOrderEvent(
broker.OrderEvent(order, broker.OrderEvent.Type.PARTIALLY_FILLED, orderExecutionInfo)
)
else:
assert(False)
else:
self.__logger.debug("Not enough cash to fill %s order [%s] for %d share/s" % (
order.getInstrument(),
order.getId(),
order.getRemaining()
))
def submitOrder(self, order):
if order.isInitial():
order.setSubmitted(self._getNextOrderId(), self._getCurrentDateTime())
self._registerOrder(order)
# Switch from INITIAL -> SUBMITTED
# IMPORTANT: Do not emit an event for this switch because when using the position interface
# the order is not yet mapped to the position and Position.onOrderUpdated will get called.
order.switchState(broker.Order.State.SUBMITTED)
else:
raise Exception("The order was already processed")
# Return True if further processing is needed.
def __preProcessOrder(self, order, bar_):
ret = True
# For non-GTC orders we need to check if the order has expired.
if not order.getGoodTillCanceled():
expired = bar_.getDateTime().date() > order.getAcceptedDateTime().date()
# Cancel the order if it is expired.
if expired:
ret = False
self._unregisterOrder(order)
order.switchState(broker.Order.State.CANCELED)
self.notifyOrderEvent(broker.OrderEvent(order, broker.OrderEvent.Type.CANCELED, "Expired"))
return ret
def __postProcessOrder(self, order, bar_):
# For non-GTC orders and daily (or greater) bars we need to check if orders should expire right now
# before waiting for the next bar.
if not order.getGoodTillCanceled():
expired = False
if self.__barFeed.getFrequency() >= pyalgotrade.bar.Frequency.DAY:
expired = bar_.getDateTime().date() >= order.getAcceptedDateTime().date()
# Cancel the order if it will expire in the next bar.
if expired:
self._unregisterOrder(order)
order.switchState(broker.Order.State.CANCELED)
self.notifyOrderEvent(broker.OrderEvent(order, broker.OrderEvent.Type.CANCELED, "Expired"))
def __processOrder(self, order, bar_):
if not self.__preProcessOrder(order, bar_):
return
# Double dispatch to the fill strategy using the concrete order type.
fillInfo = order.process(self, bar_)
if fillInfo is not None:
self.commitOrderExecution(order, bar_.getDateTime(), fillInfo)
if order.isActive():
self.__postProcessOrder(order, bar_)
def __onBarsImpl(self, order, bars):
# IF WE'RE DEALING WITH MULTIPLE INSTRUMENTS WE SKIP ORDER PROCESSING IF THERE IS NO BAR FOR THE ORDER'S
# INSTRUMENT TO GET THE SAME BEHAVIOUR AS IF WERE BE PROCESSING ONLY ONE INSTRUMENT.
bar_ = bars.getBar(order.getInstrument())
if bar_ is not None:
# Switch from SUBMITTED -> ACCEPTED
if order.isSubmitted():
order.setAcceptedDateTime(bar_.getDateTime())
order.switchState(broker.Order.State.ACCEPTED)
self.notifyOrderEvent(broker.OrderEvent(order, broker.OrderEvent.Type.ACCEPTED, None))
if order.isActive():
# This may trigger orders to be added/removed from __activeOrders.
self.__processOrder(order, bar_)
else:
# If an order is not active it should be because it was canceled in this same loop and it should
# have been removed.
assert(order.isCanceled())
assert(order not in self.__activeOrders)
def onBars(self, dateTime, bars):
# Let the fill strategy know that new bars are being processed.
self.__fillStrategy.onBars(self, bars)
# This is to froze the orders that will be processed in this event, to avoid new getting orders introduced
# and processed on this very same event.
ordersToProcess = self.__activeOrders.values()
for order in ordersToProcess:
# This may trigger orders to be added/removed from __activeOrders.
self.__onBarsImpl(order, bars)
def start(self):
pass
def stop(self):
pass
def join(self):
pass
def eof(self):
# If there are no more events in the barfeed, then there is nothing left for us to do since all processing took
# place while processing barfeed events.
return self.__barFeed.eof()
def dispatch(self):
# All events were already emitted while handling barfeed events.
pass
def peekDateTime(self):
return None
def createMarketOrder(self, action, instrument, quantity, onClose=False):
# In order to properly support market-on-close with intraday feeds I'd need to know about different
# exchange/market trading hours and support specifying routing an order to a specific exchange/market.
# Even if I had all this in place it would be a problem while paper-trading with a live feed since
# I can't tell if the next bar will be the last bar of the market session or not.
if onClose is True and self.__barFeed.isIntraday():
raise Exception("Market-on-close not supported with intraday feeds")
return MarketOrder(action, instrument, quantity, onClose, self.getInstrumentTraits(instrument))
def createLimitOrder(self, action, instrument, limitPrice, quantity):
return LimitOrder(action, instrument, limitPrice, quantity, self.getInstrumentTraits(instrument))
def createStopOrder(self, action, instrument, stopPrice, quantity):
return StopOrder(action, instrument, stopPrice, quantity, self.getInstrumentTraits(instrument))
def createStopLimitOrder(self, action, instrument, stopPrice, limitPrice, quantity):
return StopLimitOrder(action, instrument, stopPrice, limitPrice, quantity, self.getInstrumentTraits(instrument))
def cancelOrder(self, order):
activeOrder = self.__activeOrders.get(order.getId())
if activeOrder is None:
raise Exception("The order is not active anymore")
if activeOrder.isFilled():
raise Exception("Can't cancel order that has already been filled")
self._unregisterOrder(activeOrder)
activeOrder.switchState(broker.Order.State.CANCELED)
self.notifyOrderEvent(
broker.OrderEvent(activeOrder, broker.OrderEvent.Type.CANCELED, "User requested cancellation")
)
| |
from collections import OrderedDict as odict
from ruamel import yaml
import copy
from .named_item import NamedItem
from .err import FlagAliasNotFound
from . import util
def get_name_for_flags(compiler):
if isinstance(compiler, str):
return compiler
sn = compiler.name_for_flags
if compiler.is_msvc:
if compiler.vs.is_clang:
sn = 'clang'
else:
sn = 'vs'
return sn
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
class FlagAliases:
def __init__(self, **kwargs):
if kwargs.get('txt') is not None:
raise Exception("not implemented")
# self.compilers, self.flags = load_txt(kwargs.get('txt'))
elif kwargs.get('yml') is not None:
self.compilers, self.flags = load_yml(kwargs.get('yml'))
else:
self.flags = odict(**kwargs)
self.compilers = get_all_compilers(self.flags)
def merge_from(self, other):
self.flags = merge(self.flags, other.flags)
self.compilers = get_all_compilers(self.flags)
def get(self, name, compiler=None):
opt = self.flags.get(name)
if opt is None:
raise FlagAliasNotFound(name, self.flags.keys())
if compiler is not None:
return opt.get(compiler)
return opt
def as_flags(self, spec, compiler=None):
out = []
for s in spec:
if isinstance(s, CFlag):
out.append(s)
else:
f = self.flags.get(s)
if f is not None:
out.append(f)
else:
ft = CFlag(name=s, desc=s)
ft.set(compiler, s)
out.append(ft)
if compiler is not None:
out = [f.get(compiler) for f in out]
return out
def as_defines(self, spec, compiler=None):
out = []
wf = '/D' if get_name_for_flags(compiler) == 'vs' else '-D'
prev = None
for s in spec:
if prev != wf and not s.startswith(wf):
out.append(wf)
out.append(s)
prev = s
return out
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
class CFlag(NamedItem):
def __init__(self, name, desc='', **kwargs):
super().__init__(name)
self.desc = desc
self.compilers = []
for k, v in kwargs.items():
self.set(k, v)
def get(self, compiler):
compseq = (compiler, 'gcc', 'g++', 'vs') # not really sure about this
s = None
for c in compseq:
sn = get_name_for_flags(c)
if hasattr(self, sn):
s = getattr(self, sn)
break
if s is None:
util.logwarn('compiler not found: ', compiler, self.__dict__)
s = ''
# print(self, sn, s)
return s
def set(self, compiler, val=''):
sn = get_name_for_flags(compiler)
setattr(self, sn, val)
if sn not in self.compilers:
self.compilers.append(sn)
def add_compiler(self, compiler):
sn = get_name_for_flags(compiler)
if not hasattr(self, sn):
self.set(sn)
if sn not in self.compilers:
self.compilers.append(sn)
def merge_from(self, that):
for k, v in that.__dict__.items():
if not __class__.is_compiler_name(k):
continue
v = that.get(k)
self.set(k, v)
@staticmethod
def is_compiler_name(s):
return not (s.startswith('__') or s == 'name' or s == 'desc'
or s == 'compilers')
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
def dump_yml(comps, flags):
"""dump the given compilers and flags pair into a yml string"""
txt = ""
for n, f in flags.items():
txt += n + ':\n'
if f.desc:
txt += ' desc: ' + f.desc + '\n'
# join equal flag values into comma-separated keys:
# eg compiler1,compiler2,compiler3: flag value
rd = odict()
dr = odict()
done = odict()
# store reverse information: flag: compiler1,compiler2,compiler3
for comp in comps:
v = getattr(f, comp)
if not rd.get(v):
rd[v] = ''
else:
rd[v] += ','
rd[v] += comp
dr[comp] = v
# make sure compilers are not repeated
for comp in comps:
done[comp] = False
# now lookup, write and mark
for comp in comps:
if done[comp]:
continue
val = dr[comp]
key = rd[val]
if val:
txt += ' ' + key + ': ' + val + '\n'
for ccomp in key.split(','):
done[ccomp] = True
return txt
def load_txt(yml_txt):
"""load a yml txt into a compilers, flags pair"""
YAML = yaml.YAML()
dump = YAML.load(yml_txt)
fa = dump.get('flag_aliases', dump)
return load_yml(fa)
def load_yml(dump):
fd = odict(dump)
# gather the list of compilers
comps = []
for n, yf in fd.items():
for c in yf:
c = str(c)
if CFlag.is_compiler_name(c):
for cc in c.split(','):
if cc not in comps:
comps.append(cc)
# now load flags, making sure that all have the same compiler names
flags = odict()
for n, yf in fd.items():
f = CFlag(n)
for c in comps:
f.add_compiler(c)
for comp_, val in yf.items():
for comp in comp_.split(','):
if comp == 'desc':
f.desc = val
else:
f.set(comp, val)
#print("load yml: flag value for", comp, ":", val, "--------->", f.get(comp))
flags[n] = f
return comps, flags
def merge(flags, into_flags=None):
"""merge flags into the previously existing flags"""
into_flags = into_flags if into_flags is not None else known_flags
comps = get_all_compilers(flags, into_flags)
result_flags = copy.deepcopy(into_flags)
for k, v in flags.items():
if k in result_flags:
result_flags[k].merge_from(v)
else:
result_flags[k] = copy.deepcopy(v)
for f in result_flags:
for c in comps:
result_flags[f].add_compiler(c)
return result_flags
def get_all_compilers(*flag_dicts):
comps = []
for f in flag_dicts:
for k, v in f.items():
for c in v.compilers:
if c not in comps:
comps.append(c)
return comps
| |
#!/usr/bin/env python3
"""
ruledxml.core
-------------
Core implementation for application of rules to XML files.
It covers the following steps:
1. Read rules file
2. Retrieve source XML file
3. Do required elements exist?
4. Apply rules
5. Write resulting XML to file
(C) 2015, meisterluk, BSD 3-clause license
"""
import re
import sys
import os.path
import logging
import pathlib
import argparse
import importlib.machinery
import collections
import lxml.etree
from . import fs
from . import xml
from . import exceptions
def unique_function(filepath: str):
"""Quick&dirty check that every python rule function has a unique name.
:param filepath: Filepath to a python file
:type filepath: str
:raises RuledXmlException: if a function name is defined twice
"""
pattern = re.compile("def\s+(rule\w+)")
functions = {}
errmsg = ("Function name {} is defined multiple times "
"in file {} (lines {} and {})")
with open(filepath) as fp:
for lineno, line in enumerate(fp):
m = pattern.match(line)
if not m:
continue
name = m.group(1)
if name in functions:
first = functions[name]
msg = errmsg.format(name, filepath, first, lineno)
raise exceptions.RuledXmlException(msg)
functions[name] = lineno
logging.info("Found {} at line {}".format(name, lineno))
def required_exists(dom: lxml.etree.Element, nonempty=None, required=None, *, filepath=''):
"""Validate `required` and `nonempty` fields.
ie. raise InvalidPathException if path does not exist in `dom`.
:param dom: the root element of a DOM to validate
:type dom: lxml.etree.Element
:param nonempty: set of paths with nonempty values
:type nonempty: set
:param required: set of required paths
:type required: set
:param filepath: filepath (additional info for error message)
:type filepath: str
:raises InvalidPathException: some required path does not exist / is empty
"""
if not required:
required = set()
if not nonempty:
nonempty = set()
suffix = ""
if filepath:
suffix = " in XML file '{}'".format(filepath)
for req in required:
if not dom.xpath(req):
errmsg = 'Path {} does not exist{}'.format(req, suffix)
raise exceptions.InvalidPathException(errmsg.format(req))
for req in nonempty:
if xml.read_source(dom, req) == '':
errmsg = 'Path {} is empty{}; must contain value'.format(req, suffix)
raise exceptions.InvalidPathException(errmsg.format(req))
def read_rulesfile(filepath: str) -> tuple([dict, set]):
"""Given a `filepath`, return its contained rules and required attributes.
Raises a exceptions.RuledXmlException if file does not contain any rule.
:param filepath: A filepath in the filesystem
:type filepath: str
:return: rules (associates name to implementation) and metadata
such as required attributes, xml namespaces and encoding
:rtype: tuple(dict, dict)
"""
def modulename(path: str) -> str:
"""Return module name for a rule file in given path"""
return os.path.splitext(os.path.basename(path))[0]
logging.info('Reading rules from %s', filepath)
loader = importlib.machinery.SourceFileLoader(modulename(filepath), filepath)
rulesfile = loader.load_module()
rules = {}
metadata = {
'input_required': set(),
'input_nonempty': set(),
'input_xml_namespaces': {},
'output_encoding': 'utf-8',
'output_xml_namespaces': {}
}
tmpl = "Found %s attribute with %d elements"
for member in dir(rulesfile):
if member.startswith("rule"):
rules[member] = getattr(rulesfile, member)
logging.info("Found %s", member)
elif member in {"input_required", "input_nonempty",
"output_required", "output_nonempty"}:
metadata[member] = set(getattr(rulesfile, member))
logging.info(tmpl, member, len(metadata[member]))
elif member == "input_namespaces":
metadata['input_xml_namespaces'] = getattr(rulesfile, member)
logging.info(tmpl, "input_namespaces", len(metadata['input_xml_namespaces']))
elif member == "output_namespaces":
metadata['output_xml_namespaces'] = getattr(rulesfile, member)
logging.info(tmpl, 'output_namespaces', len(metadata['output_xml_namespaces']))
elif member == "output_encoding":
metadata['output_encoding'] = getattr(rulesfile, member)
logging.info('Attribute %s found. Is set to %s', 'output_encoding',
metadata['output_encoding'])
if not rules:
msg = "Expected at least one rule definition, none given in {}"
raise exceptions.RuledXmlException(msg.format(filepath))
logging.debug('metadata found: %s', str(metadata))
return rules, metadata
def validate_rules(rules: dict):
"""Validate rules. Test whether decorator setup is fine for all of them.
:param rules: rule names associated to their implementation
:type rules: dict(str: function)
:raises RuledXmlException: a decorator is set up wrongfully
"""
for rulename, rule in rules.items():
# a rule must have @source, @destination or @foreach applied
if not hasattr(rule, 'metadata'):
msg = ("Function {} is considered to be a rule, but it "
"requires at least a @destination declaration")
raise exceptions.InvalidRuleDestination(msg.format(rulename))
# a rule must have at least one @destination
dst = rule.metadata.get('dst', {})
dst_len = len(dst.get('dests', []))
if dst_len != 1:
msg = "A rule must have exactly 1 @destination. {} has {}"
raise exceptions.TooManyRuleDestinations(msg.format(rulename, dst_len))
# distinguish: foreach, no-foreach
if 'each' in rule.metadata:
each_len = len(rule.metadata['each'])
if each_len == 0:
msg = "A @foreach rule requires at least 2 arguments. {} has 0"
raise exceptions.InvalidRuleForeach(msg.format(rulename))
each_arg_len = len(rule.metadata['each'][0])
if each_arg_len != 2:
msg = "@foreach must have exactly two arguments. {} has {}"
raise exceptions.InvalidRuleForeach(msg.format(rulename, each_arg_len))
each_dst_len = len(rule.metadata.get('dst', {}).get('dsts', []))
if each_dst_len > 1:
msg = ("@foreach rules must have at most "
"1 @destination. {} has {}")
raise exceptions.InvalidRuleForeach(msg.format(rulename, each_dst_len))
# outer @foreach[0] must be prefix of innner @foreach[0]
destination = rule.metadata['dst']['dests'][0]
for source in rule.metadata.get('src', []):
prev_base_src = None
for base_src, base_dst in rule.metadata['each']:
if prev_base_src is not None and not base_src.startswith(prev_base_src):
msg = ("Outer first @foreach argument '{}' must be prefix of "
"inner first @foreach argument '{}'")
raise exceptions.InvalidRuleForeach(msg.format(prev_base_src, base_src))
prev_base_src = base_src
else:
pass # no further checks
def build_recursive_structure(rules: list) -> list:
"""Build a recursive structure based on foreach-sources of the given rules.
>>> rule1 = {
... 'foreach': [('a', 'x'), ('ab', 'xy')],
... 'source': ['1', 'a2', 'ab3', 'ab4'],
... 'destination': ['xy5']
... }
>>> rule2 = {
... 'foreach': [('a', 'x'), ('ac', 'xz')],
... 'source': ['6'],
... 'destination': ['xz7']
... }
>>> build_recursive_structure([rule1, rule2])
[{
'class': 'iteration',
'dstbase': 'x',
'srcbase': 'a',
'children': [
{ 'class': 'iteration',
'dstbase': 'xy',
'srcbase': 'ab',
'children': []
}, {'class': 'iteration',
'dstbase': 'xz',
'srcbase': 'ac',
'children': []
}]
}]
:param rules: a set of rules to read @foreach attributes from
:type rules: list
:return: a list of (potentially nested) dictionaries
:rtype: list
"""
all_each_bases = set()
for rule in rules:
for each in rule['foreach']:
all_each_bases.add(each)
all_each_bases = list(all_each_bases)
all_each_bases.sort(key=lambda e: e[0])
structure = []
for base in all_each_bases:
current = structure
added = False
while not added:
for element in current:
if base[0].startswith(element['srcbase']):
current = element['children']
break
else:
childs = []
current.append({
'class': 'iteration',
'srcbase': base[0],
'dstbase': base[1],
'children': childs
})
current = childs
added = True
return structure
def classify_rules(rules: dict):
"""Classify rules. Represent rules as dictionary with associated metadata.
Returns a data structure with is nicely structured to perform the @source
and @destination algorithms with respect to @foreach semantics.
:param rules: rule names associated to their implementation
:type rules: dict(str: function)
:return: a list of dictionaries containing rules with metadata;
might be recursive (dicts contain lists of dicts)
:rtype: [dict(), dict(), ...]
"""
classified = []
max_user_dorder = None
# add basic rules
each_found = False
for rulename, rule in rules.items():
if 'each' in rule.metadata:
each_found = True
continue
user_dorder = rule.metadata.get('dst', {}).get('order')
if user_dorder is not None:
user_dorder = int(user_dorder)
if max_user_dorder is None or (user_dorder is not None and user_dorder > max_user_dorder):
max_user_dorder = user_dorder
classified.append({
'name': rulename,
'class': 'basicrule',
'rule': rule,
'each': [],
'src': rule.metadata.get('src', []),
'dst': rule.metadata.get('dst', {}).get('dests', []),
'dorder': user_dorder
})
if max_user_dorder is None:
max_user_dorder = 0
# assign destination orders not defined by user
for ruledata in classified:
if ruledata['dorder'] is None:
max_user_dorder += 1
ruledata['dorder'] = max_user_dorder
if not each_found:
return classified
# collect the set of all @foreach base sources
foreach_rules = []
for rulename, rule in rules.items():
if 'each' not in rule.metadata:
continue
dorder = rule.metadata.get('dst', {}).get('dorder')
if dorder is None:
max_user_dorder += 1
dorder = max_user_dorder
foreach_rules.append({
'foreach': rule.metadata.get('each', []),
'source': rule.metadata.get('src', []),
'destination': rule.metadata.get('dst', {}).get('dests', []),
'dorder': dorder
})
# build recursive structure for @foreach entries
# node tell when an ambiguous element has to be iterated
recursive_structure = build_recursive_structure(foreach_rules)
# annotate rules to it
def traverse(tree, xpath):
# Assumption. xpath exists as base in tree.
assert xpath
current = tree
found = False
while not found:
for element in current:
if xpath == element['srcbase']:
return element['children']
if xpath.startswith(element['srcbase']):
current = element['children']
# add the rules to the recursive structure
for rulename, rule in rules.items():
if 'each' not in rule.metadata:
continue
dorder = rule.metadata.get('dst', {}).get('dorder')
if dorder is None:
max_user_dorder += 1
dorder = max_user_dorder
most_nested = rule.metadata['each'][-1]
lst = traverse(recursive_structure, most_nested[0])
lst.append({
'class': 'foreach-rule',
'name': rulename,
'src': rule.metadata.get('src', []),
'dst': rule.metadata.get('dst', {}).get('dests', []),
'dorder': dorder,
'rule': rule
})
for struct in recursive_structure:
classified.append(struct)
return classified
def reorder_rules(rules: dict):
"""Take `rules` and reorder rules such that rule
with low orders are executed first.
:param rules: a recursive structure representing rules to be executed
:type rules: dict(str: function)
:return: a list of dictionaries containing rules with metadata;
might be recursive (dicts contain lists of dicts)
:rtype: [dict(), dict(), ...]
"""
def sorting_traverse(node):
node.sort(key=lambda v: v.get('dorder', float('inf')))
for d in node:
if 'children' in d:
sorting_traverse(d['children'])
sorting_traverse(rules)
return rules
def run_rules(src_dom: lxml.etree.Element, target_dom: lxml.etree.Element,
classified: list, xmlmap=None):
"""Actually apply the classified rules to a target DOM.
:param src_dom: the root element of a DOM to retrieve source data from
:type src_dom: lxml.etree.Element
:param target_dom: the root element of a DOM to write destination data to
:type target_dom: lxml.etree.Element
:param classified: a list of dictionaries containing rules with metadata;
might be recursive (dicts contain lists of dicts)
:type classified: [dict(), dict(), ...]
:param xmlmap: association of XML namespace name to URI
:type xmlmap: dict
:param bases: Base elements (created for source @foreach elements)
:type bases: list
:return: the root element of a new DOM
:rtype: lxml.etree.Element
"""
def finish_a_tree(src_dom, target_dom, node, src_bases, dst_bases):
if node['class'] == 'iteration':
for src_base in xml.read_ambiguous_element(src_dom, node['srcbase'], src_bases):
dst_base = xml.write_new_ambiguous_element(target_dom,
node['dstbase'], dst_bases, xmlmap)
for child in node['children']:
target_dom = finish_a_tree(src_dom, target_dom, child,
src_bases.copy() + [src_base], dst_bases.copy() + [dst_base])
return target_dom
elif node['class'] == 'foreach-rule':
args = []
for src in node['src']:
args.append(xml.read_base_source(src_dom, src, bases=src_bases))
output = node['rule'](*args)
if output is None:
return target_dom
return xml.write_base_destination(target_dom, node['dst'][0],
output, bases=dst_bases, xmlmap=xmlmap)
for obj in classified:
if obj['class'] == 'basicrule':
logging.info("Applying %s", obj['name'])
args = []
for src in obj['src']:
args.append(xml.read_source(src_dom, src))
logging.debug("Applying %s with arguments %s", obj['name'], str(args))
output = obj['rule'](*args)
if output is None:
continue
dst = obj['dst'][0]
target_dom = xml.write_destination(target_dom, dst, output, xmlmap=xmlmap)
elif obj['class'] in ('iteration', 'foreach-rule'):
target_dom = finish_a_tree(src_dom, target_dom, obj, [], [])
return target_dom
def apply_rules(dom: lxml.etree.Element, rules: dict, *, xmlmap=None):
"""Apply given rules to the given DOM.
:param dom: the root element of a DOM
:type dom: lxml.etree.Element
:param rules: rule names associated to their implementation
:type rules: dict(str : function)
:param xmlmap: association of XML namespace name to URI
:type xmlmap: dict
:return: root element of a new DOM
:rtype: lxml.etree.Element
:raises RuledXmlException: some rule is invalid
"""
validate_rules(rules)
classified = classify_rules(rules)
ordered = reorder_rules(classified)
return run_rules(dom, None, ordered, xmlmap)
def run(in_fd, rules_filepath: str, out_fd, *, infile='', outfile='') -> int:
"""Process one file.
:param in_fd: File descriptor to one input XML file
:type in_fd: _io.TextIOWrapper
:param rules_filepath: Filepath to a rulesfile
:type rules_filepath: str
:param out_fd: File descriptor to an output XML file
:type out_fd: _io.TextIOWrapper
:param infile: original XML input file path for debugging purposes
:type infile: str
:param outfile: output XML file path for debugging purposes
:type outfile: str
:return: exit code 0
:rtype: int
"""
# read rules file
unique_function(rules_filepath)
rules, meta = read_rulesfile(rules_filepath)
# retrieve source xmlfile
src_dom = xml.read(in_fd)
# test: required elements exist?
required_exists(src_dom, meta['input_nonempty'], meta['input_required'], filepath=infile)
# apply rules
target_dom = apply_rules(src_dom, rules, xmlmap=meta['output_xml_namespaces'])
# write target XML to file
xml.write(target_dom, out_fd, encoding=meta['output_encoding'])
return 0
def batch_run(in_fd, rules_filepath: str, out_filepaths: list([str]),
base: str, *, infile='') -> int:
"""Process one file. Apply rules for some base path.
Create several target DOMs.
:param in_fd: File descriptor to one input XML file
:type in_fd: _io.TextIOWrapper
:param rules_filepath: Filepath to a rulesfile
:type rules_filepath: str
:param out_filepaths: File descriptor to an output XML file
:type out_filepaths: _io.TextIOWrapper
:param base: A base XPath, all rules are applied relative to this path
:type base: str
:param infile: original XML input file path for debugging purposes
:type infile: str
:return: exit code 0
:rtype: int
"""
# read rules file
unique_function(rules_filepath)
rules, meta = read_rulesfile(rules_filepath)
# retrieve source xmlfile
src_dom = xml.read(in_fd)
count = 0
for element in src_dom.xpath(base):
# test: required elements exist?
required_exists(element, meta['input_nonempty'],
meta['input_required'], filepath=infile)
# apply rules
target_dom = apply_rules(element, rules,
xmlmap=meta['output_xml_namespaces'])
# test: required elements exist?
required_exists(target_dom, meta['output_nonempty'], meta['output_required'])
# write target XML to file
fs.create_base_directories(out_filepaths[count])
with open(out_filepaths[count], 'wb') as out_fd:
xml.write(target_dom, out_fd, encoding=meta['output_encoding'])
count += 1
if count < len(out_filepaths):
msg = "Number of output filepaths was {}; expected {}"
logging.warn(msg.format(count, len(out_filepaths)))
return 0
| |
# -*- coding: utf-8 -*-
"""
pygments.lexers.webmisc
~~~~~~~~~~~~~~~~~~~~~~~
Lexers for misc. web stuff.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, ExtendedRegexLexer, include, bygroups, \
default, using
from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
Number, Punctuation, Literal
from pygments.util import unirange
from pygments.lexers.css import _indentation, _starts_block
from pygments.lexers.html import HtmlLexer
from pygments.lexers.javascript import JavascriptLexer
from pygments.lexers.ruby import RubyLexer
__all__ = ['DuelLexer', 'SlimLexer', 'XQueryLexer', 'QmlLexer', 'CirruLexer']
class DuelLexer(RegexLexer):
"""
Lexer for Duel Views Engine (formerly JBST) markup with JavaScript code blocks.
See http://duelengine.org/.
See http://jsonml.org/jbst/.
.. versionadded:: 1.4
"""
name = 'Duel'
aliases = ['duel', 'jbst', 'jsonml+bst']
filenames = ['*.duel', '*.jbst']
mimetypes = ['text/x-duel', 'text/x-jbst']
flags = re.DOTALL
tokens = {
'root': [
(r'(<%[@=#!:]?)(.*?)(%>)',
bygroups(Name.Tag, using(JavascriptLexer), Name.Tag)),
(r'(<%\$)(.*?)(:)(.*?)(%>)',
bygroups(Name.Tag, Name.Function, Punctuation, String, Name.Tag)),
(r'(<%--)(.*?)(--%>)',
bygroups(Name.Tag, Comment.Multiline, Name.Tag)),
(r'(<script.*?>)(.*?)(</script>)',
bygroups(using(HtmlLexer),
using(JavascriptLexer), using(HtmlLexer))),
(r'(.+?)(?=<)', using(HtmlLexer)),
(r'.+', using(HtmlLexer)),
],
}
class XQueryLexer(ExtendedRegexLexer):
"""
An XQuery lexer, parsing a stream and outputting the tokens needed to
highlight xquery code.
.. versionadded:: 1.4
"""
name = 'XQuery'
aliases = ['xquery', 'xqy', 'xq', 'xql', 'xqm']
filenames = ['*.xqy', '*.xquery', '*.xq', '*.xql', '*.xqm']
mimetypes = ['text/xquery', 'application/xquery']
xquery_parse_state = []
# FIX UNICODE LATER
# ncnamestartchar = (
# ur"[A-Z]|_|[a-z]|[\u00C0-\u00D6]|[\u00D8-\u00F6]|[\u00F8-\u02FF]|"
# ur"[\u0370-\u037D]|[\u037F-\u1FFF]|[\u200C-\u200D]|[\u2070-\u218F]|"
# ur"[\u2C00-\u2FEF]|[\u3001-\uD7FF]|[\uF900-\uFDCF]|[\uFDF0-\uFFFD]|"
# ur"[\u10000-\uEFFFF]"
# )
ncnamestartchar = r"(?:[A-Z]|_|[a-z])"
# FIX UNICODE LATER
# ncnamechar = ncnamestartchar + (ur"|-|\.|[0-9]|\u00B7|[\u0300-\u036F]|"
# ur"[\u203F-\u2040]")
ncnamechar = r"(?:" + ncnamestartchar + r"|-|\.|[0-9])"
ncname = "(?:%s+%s*)" % (ncnamestartchar, ncnamechar)
pitarget_namestartchar = r"(?:[A-KN-WY-Z]|_|:|[a-kn-wy-z])"
pitarget_namechar = r"(?:" + pitarget_namestartchar + r"|-|\.|[0-9])"
pitarget = "%s+%s*" % (pitarget_namestartchar, pitarget_namechar)
prefixedname = "%s:%s" % (ncname, ncname)
unprefixedname = ncname
qname = "(?:%s|%s)" % (prefixedname, unprefixedname)
entityref = r'(?:&(?:lt|gt|amp|quot|apos|nbsp);)'
charref = r'(?:&#[0-9]+;|&#x[0-9a-fA-F]+;)'
stringdouble = r'(?:"(?:' + entityref + r'|' + charref + r'|""|[^&"])*")'
stringsingle = r"(?:'(?:" + entityref + r"|" + charref + r"|''|[^&'])*')"
# FIX UNICODE LATER
# elementcontentchar = (ur'\t|\r|\n|[\u0020-\u0025]|[\u0028-\u003b]|'
# ur'[\u003d-\u007a]|\u007c|[\u007e-\u007F]')
elementcontentchar = r'[A-Za-z]|\s|\d|[!"#$%\(\)\*\+,\-\./\:;=\?\@\[\\\]^_\'`\|~]'
# quotattrcontentchar = (ur'\t|\r|\n|[\u0020-\u0021]|[\u0023-\u0025]|'
# ur'[\u0027-\u003b]|[\u003d-\u007a]|\u007c|[\u007e-\u007F]')
quotattrcontentchar = r'[A-Za-z]|\s|\d|[!#$%\(\)\*\+,\-\./\:;=\?\@\[\\\]^_\'`\|~]'
# aposattrcontentchar = (ur'\t|\r|\n|[\u0020-\u0025]|[\u0028-\u003b]|'
# ur'[\u003d-\u007a]|\u007c|[\u007e-\u007F]')
aposattrcontentchar = r'[A-Za-z]|\s|\d|[!"#$%\(\)\*\+,\-\./\:;=\?\@\[\\\]^_`\|~]'
# CHAR elements - fix the above elementcontentchar, quotattrcontentchar,
# aposattrcontentchar
# x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
flags = re.DOTALL | re.MULTILINE | re.UNICODE
def punctuation_root_callback(lexer, match, ctx):
yield match.start(), Punctuation, match.group(1)
# transition to root always - don't pop off stack
ctx.stack = ['root']
ctx.pos = match.end()
def operator_root_callback(lexer, match, ctx):
yield match.start(), Operator, match.group(1)
# transition to root always - don't pop off stack
ctx.stack = ['root']
ctx.pos = match.end()
def popstate_tag_callback(lexer, match, ctx):
yield match.start(), Name.Tag, match.group(1)
ctx.stack.append(lexer.xquery_parse_state.pop())
ctx.pos = match.end()
def popstate_xmlcomment_callback(lexer, match, ctx):
yield match.start(), String.Doc, match.group(1)
ctx.stack.append(lexer.xquery_parse_state.pop())
ctx.pos = match.end()
def popstate_kindtest_callback(lexer, match, ctx):
yield match.start(), Punctuation, match.group(1)
next_state = lexer.xquery_parse_state.pop()
if next_state == 'occurrenceindicator':
if re.match("[?*+]+", match.group(2)):
yield match.start(), Punctuation, match.group(2)
ctx.stack.append('operator')
ctx.pos = match.end()
else:
ctx.stack.append('operator')
ctx.pos = match.end(1)
else:
ctx.stack.append(next_state)
ctx.pos = match.end(1)
def popstate_callback(lexer, match, ctx):
yield match.start(), Punctuation, match.group(1)
# if we have run out of our state stack, pop whatever is on the pygments
# state stack
if len(lexer.xquery_parse_state) == 0:
ctx.stack.pop()
elif len(ctx.stack) > 1:
ctx.stack.append(lexer.xquery_parse_state.pop())
else:
# i don't know if i'll need this, but in case, default back to root
ctx.stack = ['root']
ctx.pos = match.end()
def pushstate_element_content_starttag_callback(lexer, match, ctx):
yield match.start(), Name.Tag, match.group(1)
lexer.xquery_parse_state.append('element_content')
ctx.stack.append('start_tag')
ctx.pos = match.end()
def pushstate_cdata_section_callback(lexer, match, ctx):
yield match.start(), String.Doc, match.group(1)
ctx.stack.append('cdata_section')
lexer.xquery_parse_state.append(ctx.state.pop)
ctx.pos = match.end()
def pushstate_starttag_callback(lexer, match, ctx):
yield match.start(), Name.Tag, match.group(1)
lexer.xquery_parse_state.append(ctx.state.pop)
ctx.stack.append('start_tag')
ctx.pos = match.end()
def pushstate_operator_order_callback(lexer, match, ctx):
yield match.start(), Keyword, match.group(1)
yield match.start(), Text, match.group(2)
yield match.start(), Punctuation, match.group(3)
ctx.stack = ['root']
lexer.xquery_parse_state.append('operator')
ctx.pos = match.end()
def pushstate_operator_root_validate(lexer, match, ctx):
yield match.start(), Keyword, match.group(1)
yield match.start(), Text, match.group(2)
yield match.start(), Punctuation, match.group(3)
ctx.stack = ['root']
lexer.xquery_parse_state.append('operator')
ctx.pos = match.end()
def pushstate_operator_root_validate_withmode(lexer, match, ctx):
yield match.start(), Keyword, match.group(1)
yield match.start(), Text, match.group(2)
yield match.start(), Keyword, match.group(3)
ctx.stack = ['root']
lexer.xquery_parse_state.append('operator')
ctx.pos = match.end()
def pushstate_operator_processing_instruction_callback(lexer, match, ctx):
yield match.start(), String.Doc, match.group(1)
ctx.stack.append('processing_instruction')
lexer.xquery_parse_state.append('operator')
ctx.pos = match.end()
def pushstate_element_content_processing_instruction_callback(lexer, match, ctx):
yield match.start(), String.Doc, match.group(1)
ctx.stack.append('processing_instruction')
lexer.xquery_parse_state.append('element_content')
ctx.pos = match.end()
def pushstate_element_content_cdata_section_callback(lexer, match, ctx):
yield match.start(), String.Doc, match.group(1)
ctx.stack.append('cdata_section')
lexer.xquery_parse_state.append('element_content')
ctx.pos = match.end()
def pushstate_operator_cdata_section_callback(lexer, match, ctx):
yield match.start(), String.Doc, match.group(1)
ctx.stack.append('cdata_section')
lexer.xquery_parse_state.append('operator')
ctx.pos = match.end()
def pushstate_element_content_xmlcomment_callback(lexer, match, ctx):
yield match.start(), String.Doc, match.group(1)
ctx.stack.append('xml_comment')
lexer.xquery_parse_state.append('element_content')
ctx.pos = match.end()
def pushstate_operator_xmlcomment_callback(lexer, match, ctx):
yield match.start(), String.Doc, match.group(1)
ctx.stack.append('xml_comment')
lexer.xquery_parse_state.append('operator')
ctx.pos = match.end()
def pushstate_kindtest_callback(lexer, match, ctx):
yield match.start(), Keyword, match.group(1)
yield match.start(), Text, match.group(2)
yield match.start(), Punctuation, match.group(3)
lexer.xquery_parse_state.append('kindtest')
ctx.stack.append('kindtest')
ctx.pos = match.end()
def pushstate_operator_kindtestforpi_callback(lexer, match, ctx):
yield match.start(), Keyword, match.group(1)
yield match.start(), Text, match.group(2)
yield match.start(), Punctuation, match.group(3)
lexer.xquery_parse_state.append('operator')
ctx.stack.append('kindtestforpi')
ctx.pos = match.end()
def pushstate_operator_kindtest_callback(lexer, match, ctx):
yield match.start(), Keyword, match.group(1)
yield match.start(), Text, match.group(2)
yield match.start(), Punctuation, match.group(3)
lexer.xquery_parse_state.append('operator')
ctx.stack.append('kindtest')
ctx.pos = match.end()
def pushstate_occurrenceindicator_kindtest_callback(lexer, match, ctx):
yield match.start(), Name.Tag, match.group(1)
yield match.start(), Text, match.group(2)
yield match.start(), Punctuation, match.group(3)
lexer.xquery_parse_state.append('occurrenceindicator')
ctx.stack.append('kindtest')
ctx.pos = match.end()
def pushstate_operator_starttag_callback(lexer, match, ctx):
yield match.start(), Name.Tag, match.group(1)
lexer.xquery_parse_state.append('operator')
ctx.stack.append('start_tag')
ctx.pos = match.end()
def pushstate_operator_root_callback(lexer, match, ctx):
yield match.start(), Punctuation, match.group(1)
lexer.xquery_parse_state.append('operator')
ctx.stack = ['root']
ctx.pos = match.end()
def pushstate_operator_root_construct_callback(lexer, match, ctx):
yield match.start(), Keyword, match.group(1)
yield match.start(), Text, match.group(2)
yield match.start(), Punctuation, match.group(3)
lexer.xquery_parse_state.append('operator')
ctx.stack = ['root']
ctx.pos = match.end()
def pushstate_root_callback(lexer, match, ctx):
yield match.start(), Punctuation, match.group(1)
cur_state = ctx.stack.pop()
lexer.xquery_parse_state.append(cur_state)
ctx.stack = ['root']
ctx.pos = match.end()
def pushstate_operator_attribute_callback(lexer, match, ctx):
yield match.start(), Name.Attribute, match.group(1)
ctx.stack.append('operator')
ctx.pos = match.end()
def pushstate_operator_callback(lexer, match, ctx):
yield match.start(), Keyword, match.group(1)
yield match.start(), Text, match.group(2)
yield match.start(), Punctuation, match.group(3)
lexer.xquery_parse_state.append('operator')
ctx.pos = match.end()
tokens = {
'comment': [
# xquery comments
(r'(:\))', Comment, '#pop'),
(r'(\(:)', Comment, '#push'),
(r'[^:)]', Comment),
(r'([^:)]|:|\))', Comment),
],
'whitespace': [
(r'\s+', Text),
],
'operator': [
include('whitespace'),
(r'(\})', popstate_callback),
(r'\(:', Comment, 'comment'),
(r'(\{)', pushstate_root_callback),
(r'then|else|external|at|div|except', Keyword, 'root'),
(r'order by', Keyword, 'root'),
(r'is|mod|order\s+by|stable\s+order\s+by', Keyword, 'root'),
(r'and|or', Operator.Word, 'root'),
(r'(eq|ge|gt|le|lt|ne|idiv|intersect|in)(?=\b)',
Operator.Word, 'root'),
(r'return|satisfies|to|union|where|preserve\s+strip',
Keyword, 'root'),
(r'(>=|>>|>|<=|<<|<|-|\*|!=|\+|\||:=|=)',
operator_root_callback),
(r'(::|;|\[|//|/|,)',
punctuation_root_callback),
(r'(castable|cast)(\s+)(as)\b',
bygroups(Keyword, Text, Keyword), 'singletype'),
(r'(instance)(\s+)(of)\b',
bygroups(Keyword, Text, Keyword), 'itemtype'),
(r'(treat)(\s+)(as)\b',
bygroups(Keyword, Text, Keyword), 'itemtype'),
(r'(case|as)\b', Keyword, 'itemtype'),
(r'(\))(\s*)(as)',
bygroups(Punctuation, Text, Keyword), 'itemtype'),
(r'\$', Name.Variable, 'varname'),
(r'(for|let)(\s+)(\$)',
bygroups(Keyword, Text, Name.Variable), 'varname'),
# (r'\)|\?|\]', Punctuation, '#push'),
(r'\)|\?|\]', Punctuation),
(r'(empty)(\s+)(greatest|least)', bygroups(Keyword, Text, Keyword)),
(r'ascending|descending|default', Keyword, '#push'),
(r'external', Keyword),
(r'collation', Keyword, 'uritooperator'),
# finally catch all string literals and stay in operator state
(stringdouble, String.Double),
(stringsingle, String.Single),
(r'(catch)(\s*)', bygroups(Keyword, Text), 'root'),
],
'uritooperator': [
(stringdouble, String.Double, '#pop'),
(stringsingle, String.Single, '#pop'),
],
'namespacedecl': [
include('whitespace'),
(r'\(:', Comment, 'comment'),
(r'(at)(\s+)('+stringdouble+')', bygroups(Keyword, Text, String.Double)),
(r"(at)(\s+)("+stringsingle+')', bygroups(Keyword, Text, String.Single)),
(stringdouble, String.Double),
(stringsingle, String.Single),
(r',', Punctuation),
(r'=', Operator),
(r';', Punctuation, 'root'),
(ncname, Name.Namespace),
],
'namespacekeyword': [
include('whitespace'),
(r'\(:', Comment, 'comment'),
(stringdouble, String.Double, 'namespacedecl'),
(stringsingle, String.Single, 'namespacedecl'),
(r'inherit|no-inherit', Keyword, 'root'),
(r'namespace', Keyword, 'namespacedecl'),
(r'(default)(\s+)(element)', bygroups(Keyword, Text, Keyword)),
(r'preserve|no-preserve', Keyword),
(r',', Punctuation),
],
'varname': [
(r'\(:', Comment, 'comment'),
(qname, Name.Variable, 'operator'),
],
'singletype': [
(r'\(:', Comment, 'comment'),
(ncname + r'(:\*)', Name.Variable, 'operator'),
(qname, Name.Variable, 'operator'),
],
'itemtype': [
include('whitespace'),
(r'\(:', Comment, 'comment'),
(r'\$', Punctuation, 'varname'),
(r'(void)(\s*)(\()(\s*)(\))',
bygroups(Keyword, Text, Punctuation, Text, Punctuation), 'operator'),
(r'(element|attribute|schema-element|schema-attribute|comment|text|'
r'node|binary|document-node|empty-sequence)(\s*)(\()',
pushstate_occurrenceindicator_kindtest_callback),
# Marklogic specific type?
(r'(processing-instruction)(\s*)(\()',
bygroups(Keyword, Text, Punctuation),
('occurrenceindicator', 'kindtestforpi')),
(r'(item)(\s*)(\()(\s*)(\))(?=[*+?])',
bygroups(Keyword, Text, Punctuation, Text, Punctuation),
'occurrenceindicator'),
(r'\(\#', Punctuation, 'pragma'),
(r';', Punctuation, '#pop'),
(r'then|else', Keyword, '#pop'),
(r'(at)(\s+)(' + stringdouble + ')',
bygroups(Keyword, Text, String.Double), 'namespacedecl'),
(r'(at)(\s+)(' + stringsingle + ')',
bygroups(Keyword, Text, String.Single), 'namespacedecl'),
(r'except|intersect|in|is|return|satisfies|to|union|where',
Keyword, 'root'),
(r'and|div|eq|ge|gt|le|lt|ne|idiv|mod|or', Operator.Word, 'root'),
(r':=|=|,|>=|>>|>|\[|\(|<=|<<|<|-|!=|\|', Operator, 'root'),
(r'external|at', Keyword, 'root'),
(r'(stable)(\s+)(order)(\s+)(by)',
bygroups(Keyword, Text, Keyword, Text, Keyword), 'root'),
(r'(castable|cast)(\s+)(as)',
bygroups(Keyword, Text, Keyword), 'singletype'),
(r'(treat)(\s+)(as)', bygroups(Keyword, Text, Keyword)),
(r'(instance)(\s+)(of)', bygroups(Keyword, Text, Keyword)),
(r'case|as', Keyword, 'itemtype'),
(r'(\))(\s*)(as)', bygroups(Operator, Text, Keyword), 'itemtype'),
(ncname + r':\*', Keyword.Type, 'operator'),
(qname, Keyword.Type, 'occurrenceindicator'),
],
'kindtest': [
(r'\(:', Comment, 'comment'),
(r'{', Punctuation, 'root'),
(r'(\))([*+?]?)', popstate_kindtest_callback),
(r'\*', Name, 'closekindtest'),
(qname, Name, 'closekindtest'),
(r'(element|schema-element)(\s*)(\()', pushstate_kindtest_callback),
],
'kindtestforpi': [
(r'\(:', Comment, 'comment'),
(r'\)', Punctuation, '#pop'),
(ncname, Name.Variable),
(stringdouble, String.Double),
(stringsingle, String.Single),
],
'closekindtest': [
(r'\(:', Comment, 'comment'),
(r'(\))', popstate_callback),
(r',', Punctuation),
(r'(\{)', pushstate_operator_root_callback),
(r'\?', Punctuation),
],
'xml_comment': [
(r'(-->)', popstate_xmlcomment_callback),
(r'[^-]{1,2}', Literal),
(u'\\t|\\r|\\n|[\u0020-\uD7FF]|[\uE000-\uFFFD]|' +
unirange(0x10000, 0x10ffff), Literal),
],
'processing_instruction': [
(r'\s+', Text, 'processing_instruction_content'),
(r'\?>', String.Doc, '#pop'),
(pitarget, Name),
],
'processing_instruction_content': [
(r'\?>', String.Doc, '#pop'),
(u'\\t|\\r|\\n|[\u0020-\uD7FF]|[\uE000-\uFFFD]|' +
unirange(0x10000, 0x10ffff), Literal),
],
'cdata_section': [
(r']]>', String.Doc, '#pop'),
(u'\\t|\\r|\\n|[\u0020-\uD7FF]|[\uE000-\uFFFD]|' +
unirange(0x10000, 0x10ffff), Literal),
],
'start_tag': [
include('whitespace'),
(r'(/>)', popstate_tag_callback),
(r'>', Name.Tag, 'element_content'),
(r'"', Punctuation, 'quot_attribute_content'),
(r"'", Punctuation, 'apos_attribute_content'),
(r'=', Operator),
(qname, Name.Tag),
],
'quot_attribute_content': [
(r'"', Punctuation, 'start_tag'),
(r'(\{)', pushstate_root_callback),
(r'""', Name.Attribute),
(quotattrcontentchar, Name.Attribute),
(entityref, Name.Attribute),
(charref, Name.Attribute),
(r'\{\{|\}\}', Name.Attribute),
],
'apos_attribute_content': [
(r"'", Punctuation, 'start_tag'),
(r'\{', Punctuation, 'root'),
(r"''", Name.Attribute),
(aposattrcontentchar, Name.Attribute),
(entityref, Name.Attribute),
(charref, Name.Attribute),
(r'\{\{|\}\}', Name.Attribute),
],
'element_content': [
(r'</', Name.Tag, 'end_tag'),
(r'(\{)', pushstate_root_callback),
(r'(<!--)', pushstate_element_content_xmlcomment_callback),
(r'(<\?)', pushstate_element_content_processing_instruction_callback),
(r'(<!\[CDATA\[)', pushstate_element_content_cdata_section_callback),
(r'(<)', pushstate_element_content_starttag_callback),
(elementcontentchar, Literal),
(entityref, Literal),
(charref, Literal),
(r'\{\{|\}\}', Literal),
],
'end_tag': [
include('whitespace'),
(r'(>)', popstate_tag_callback),
(qname, Name.Tag),
],
'xmlspace_decl': [
(r'\(:', Comment, 'comment'),
(r'preserve|strip', Keyword, '#pop'),
],
'declareordering': [
(r'\(:', Comment, 'comment'),
include('whitespace'),
(r'ordered|unordered', Keyword, '#pop'),
],
'xqueryversion': [
include('whitespace'),
(r'\(:', Comment, 'comment'),
(stringdouble, String.Double),
(stringsingle, String.Single),
(r'encoding', Keyword),
(r';', Punctuation, '#pop'),
],
'pragma': [
(qname, Name.Variable, 'pragmacontents'),
],
'pragmacontents': [
(r'#\)', Punctuation, 'operator'),
(u'\\t|\\r|\\n|[\u0020-\uD7FF]|[\uE000-\uFFFD]|' +
unirange(0x10000, 0x10ffff), Literal),
(r'(\s+)', Text),
],
'occurrenceindicator': [
include('whitespace'),
(r'\(:', Comment, 'comment'),
(r'\*|\?|\+', Operator, 'operator'),
(r':=', Operator, 'root'),
default('operator'),
],
'option': [
include('whitespace'),
(qname, Name.Variable, '#pop'),
],
'qname_braren': [
include('whitespace'),
(r'(\{)', pushstate_operator_root_callback),
(r'(\()', Punctuation, 'root'),
],
'element_qname': [
(qname, Name.Variable, 'root'),
],
'attribute_qname': [
(qname, Name.Variable, 'root'),
],
'root': [
include('whitespace'),
(r'\(:', Comment, 'comment'),
# handle operator state
# order on numbers matters - handle most complex first
(r'\d+(\.\d*)?[eE][\+\-]?\d+', Number.Float, 'operator'),
(r'(\.\d+)[eE][\+\-]?\d+', Number.Float, 'operator'),
(r'(\.\d+|\d+\.\d*)', Number.Float, 'operator'),
(r'(\d+)', Number.Integer, 'operator'),
(r'(\.\.|\.|\))', Punctuation, 'operator'),
(r'(declare)(\s+)(construction)',
bygroups(Keyword, Text, Keyword), 'operator'),
(r'(declare)(\s+)(default)(\s+)(order)',
bygroups(Keyword, Text, Keyword, Text, Keyword), 'operator'),
(ncname + ':\*', Name, 'operator'),
('\*:'+ncname, Name.Tag, 'operator'),
('\*', Name.Tag, 'operator'),
(stringdouble, String.Double, 'operator'),
(stringsingle, String.Single, 'operator'),
(r'(\})', popstate_callback),
# NAMESPACE DECL
(r'(declare)(\s+)(default)(\s+)(collation)',
bygroups(Keyword, Text, Keyword, Text, Keyword)),
(r'(module|declare)(\s+)(namespace)',
bygroups(Keyword, Text, Keyword), 'namespacedecl'),
(r'(declare)(\s+)(base-uri)',
bygroups(Keyword, Text, Keyword), 'namespacedecl'),
# NAMESPACE KEYWORD
(r'(declare)(\s+)(default)(\s+)(element|function)',
bygroups(Keyword, Text, Keyword, Text, Keyword), 'namespacekeyword'),
(r'(import)(\s+)(schema|module)',
bygroups(Keyword.Pseudo, Text, Keyword.Pseudo), 'namespacekeyword'),
(r'(declare)(\s+)(copy-namespaces)',
bygroups(Keyword, Text, Keyword), 'namespacekeyword'),
# VARNAMEs
(r'(for|let|some|every)(\s+)(\$)',
bygroups(Keyword, Text, Name.Variable), 'varname'),
(r'\$', Name.Variable, 'varname'),
(r'(declare)(\s+)(variable)(\s+)(\$)',
bygroups(Keyword, Text, Keyword, Text, Name.Variable), 'varname'),
# ITEMTYPE
(r'(\))(\s+)(as)', bygroups(Operator, Text, Keyword), 'itemtype'),
(r'(element|attribute|schema-element|schema-attribute|comment|'
r'text|node|document-node|empty-sequence)(\s+)(\()',
pushstate_operator_kindtest_callback),
(r'(processing-instruction)(\s+)(\()',
pushstate_operator_kindtestforpi_callback),
(r'(<!--)', pushstate_operator_xmlcomment_callback),
(r'(<\?)', pushstate_operator_processing_instruction_callback),
(r'(<!\[CDATA\[)', pushstate_operator_cdata_section_callback),
# (r'</', Name.Tag, 'end_tag'),
(r'(<)', pushstate_operator_starttag_callback),
(r'(declare)(\s+)(boundary-space)',
bygroups(Keyword, Text, Keyword), 'xmlspace_decl'),
(r'(validate)(\s+)(lax|strict)',
pushstate_operator_root_validate_withmode),
(r'(validate)(\s*)(\{)', pushstate_operator_root_validate),
(r'(typeswitch)(\s*)(\()', bygroups(Keyword, Text, Punctuation)),
(r'(element|attribute)(\s*)(\{)',
pushstate_operator_root_construct_callback),
(r'(document|text|processing-instruction|comment)(\s*)(\{)',
pushstate_operator_root_construct_callback),
# ATTRIBUTE
(r'(attribute)(\s+)(?=' + qname + r')',
bygroups(Keyword, Text), 'attribute_qname'),
# ELEMENT
(r'(element)(\s+)(?=' + qname + r')',
bygroups(Keyword, Text), 'element_qname'),
# PROCESSING_INSTRUCTION
(r'(processing-instruction)(\s+)(' + ncname + r')(\s*)(\{)',
bygroups(Keyword, Text, Name.Variable, Text, Punctuation),
'operator'),
(r'(declare|define)(\s+)(function)',
bygroups(Keyword, Text, Keyword)),
(r'(\{)', pushstate_operator_root_callback),
(r'(unordered|ordered)(\s*)(\{)',
pushstate_operator_order_callback),
(r'(declare)(\s+)(ordering)',
bygroups(Keyword, Text, Keyword), 'declareordering'),
(r'(xquery)(\s+)(version)',
bygroups(Keyword.Pseudo, Text, Keyword.Pseudo), 'xqueryversion'),
(r'(\(#)', Punctuation, 'pragma'),
# sometimes return can occur in root state
(r'return', Keyword),
(r'(declare)(\s+)(option)', bygroups(Keyword, Text, Keyword),
'option'),
# URI LITERALS - single and double quoted
(r'(at)(\s+)('+stringdouble+')', String.Double, 'namespacedecl'),
(r'(at)(\s+)('+stringsingle+')', String.Single, 'namespacedecl'),
(r'(ancestor-or-self|ancestor|attribute|child|descendant-or-self)(::)',
bygroups(Keyword, Punctuation)),
(r'(descendant|following-sibling|following|parent|preceding-sibling'
r'|preceding|self)(::)', bygroups(Keyword, Punctuation)),
(r'(if)(\s*)(\()', bygroups(Keyword, Text, Punctuation)),
(r'then|else', Keyword),
# ML specific
(r'(try)(\s*)', bygroups(Keyword, Text), 'root'),
(r'(catch)(\s*)(\()(\$)',
bygroups(Keyword, Text, Punctuation, Name.Variable), 'varname'),
(r'(@'+qname+')', Name.Attribute),
(r'(@'+ncname+')', Name.Attribute),
(r'@\*:'+ncname, Name.Attribute),
(r'(@)', Name.Attribute),
(r'//|/|\+|-|;|,|\(|\)', Punctuation),
# STANDALONE QNAMES
(qname + r'(?=\s*{)', Name.Tag, 'qname_braren'),
(qname + r'(?=\s*\([^:])', Name.Function, 'qname_braren'),
(qname, Name.Tag, 'operator'),
]
}
class QmlLexer(RegexLexer):
"""
For QML files. See http://doc.qt.digia.com/4.7/qdeclarativeintroduction.html.
.. versionadded:: 1.6
"""
# QML is based on javascript, so much of this is taken from the
# JavascriptLexer above.
name = 'QML'
aliases = ['qml']
filenames = ['*.qml']
mimetypes = ['application/x-qml']
# pasted from JavascriptLexer, with some additions
flags = re.DOTALL
tokens = {
'commentsandwhitespace': [
(r'\s+', Text),
(r'<!--', Comment),
(r'//.*?\n', Comment.Single),
(r'/\*.*?\*/', Comment.Multiline)
],
'slashstartsregex': [
include('commentsandwhitespace'),
(r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/'
r'([gim]+\b|\B)', String.Regex, '#pop'),
(r'(?=/)', Text, ('#pop', 'badregex')),
default('#pop')
],
'badregex': [
(r'\n', Text, '#pop')
],
'root': [
(r'^(?=\s|/|<!--)', Text, 'slashstartsregex'),
include('commentsandwhitespace'),
(r'\+\+|--|~|&&|\?|:|\|\||\\(?=\n)|'
r'(<<|>>>?|==?|!=?|[-<>+*%&\|\^/])=?', Operator, 'slashstartsregex'),
(r'[{(\[;,]', Punctuation, 'slashstartsregex'),
(r'[})\].]', Punctuation),
# QML insertions
(r'\bid\s*:\s*[A-Za-z][_A-Za-z.0-9]*', Keyword.Declaration,
'slashstartsregex'),
(r'\b[A-Za-z][_A-Za-z.0-9]*\s*:', Keyword, 'slashstartsregex'),
# the rest from JavascriptLexer
(r'(for|in|while|do|break|return|continue|switch|case|default|if|else|'
r'throw|try|catch|finally|new|delete|typeof|instanceof|void|'
r'this)\b', Keyword, 'slashstartsregex'),
(r'(var|let|with|function)\b', Keyword.Declaration, 'slashstartsregex'),
(r'(abstract|boolean|byte|char|class|const|debugger|double|enum|export|'
r'extends|final|float|goto|implements|import|int|interface|long|native|'
r'package|private|protected|public|short|static|super|synchronized|throws|'
r'transient|volatile)\b', Keyword.Reserved),
(r'(true|false|null|NaN|Infinity|undefined)\b', Keyword.Constant),
(r'(Array|Boolean|Date|Error|Function|Math|netscape|'
r'Number|Object|Packages|RegExp|String|sun|decodeURI|'
r'decodeURIComponent|encodeURI|encodeURIComponent|'
r'Error|eval|isFinite|isNaN|parseFloat|parseInt|document|this|'
r'window)\b', Name.Builtin),
(r'[$a-zA-Z_]\w*', Name.Other),
(r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float),
(r'0x[0-9a-fA-F]+', Number.Hex),
(r'[0-9]+', Number.Integer),
(r'"(\\\\|\\"|[^"])*"', String.Double),
(r"'(\\\\|\\'|[^'])*'", String.Single),
]
}
class CirruLexer(RegexLexer):
"""
Syntax rules of Cirru can be found at:
http://grammar.cirru.org/
* using ``()`` to markup blocks, but limited in the same line
* using ``""`` to markup strings, allow ``\`` to escape
* using ``$`` as a shorthand for ``()`` till indentation end or ``)``
* using indentations for create nesting
.. versionadded:: 2.0
"""
name = 'Cirru'
aliases = ['cirru']
filenames = ['*.cirru', '*.cr']
mimetypes = ['text/x-cirru']
flags = re.MULTILINE
tokens = {
'string': [
(r'[^"\\\n]', String),
(r'\\', String.Escape, 'escape'),
(r'"', String, '#pop'),
],
'escape': [
(r'.', String.Escape, '#pop'),
],
'function': [
(r'[\w-][^\s\(\)\"]*', Name.Function, '#pop'),
(r'\)', Operator, '#pop'),
(r'(?=\n)', Text, '#pop'),
(r'\(', Operator, '#push'),
(r'"', String, ('#pop', 'string')),
(r'\s+', Text.Whitespace),
(r'\,', Operator, '#pop'),
],
'line': [
(r'^\B', Text.Whitespace, 'function'),
(r'\$', Operator, 'function'),
(r'\(', Operator, 'function'),
(r'\)', Operator),
(r'(?=\n)', Text, '#pop'),
(r'\n', Text, '#pop'),
(r'"', String, 'string'),
(r'\s+', Text.Whitespace),
(r'[\d\.]+', Number),
(r'[\w-][^\"\(\)\s]*', Name.Variable),
(r'--', Comment.Single)
],
'root': [
(r'^\s*', Text.Whitespace, ('line', 'function')),
(r'^\s+$', Text.Whitespace),
]
}
class SlimLexer(ExtendedRegexLexer):
"""
For Slim markup.
.. versionadded:: 2.0
"""
name = 'Slim'
aliases = ['slim']
filenames = ['*.slim']
mimetypes = ['text/x-slim']
flags = re.IGNORECASE
_dot = r'(?: \|\n(?=.* \|)|.)'
tokens = {
'root': [
(r'[ \t]*\n', Text),
(r'[ \t]*', _indentation),
],
'css': [
(r'\.[\w:-]+', Name.Class, 'tag'),
(r'\#[\w:-]+', Name.Function, 'tag'),
],
'eval-or-plain': [
(r'([ \t]*==?)(.*\n)',
bygroups(Punctuation, using(RubyLexer)),
'root'),
(r'[ \t]+[\w:-]+(?=[=])', Name.Attribute, 'html-attributes'),
(r'', Text, 'plain'),
],
'content': [
include('css'),
(r'[\w:-]+:[ \t]*\n', Text, 'plain'),
(r'(-)(.*\n)',
bygroups(Punctuation, using(RubyLexer)),
'#pop'),
(r'\|' + _dot + r'*\n', _starts_block(Text, 'plain'), '#pop'),
(r'/' + _dot + r'*\n', _starts_block(Comment.Preproc, 'slim-comment-block'), '#pop'),
(r'[\w:-]+', Name.Tag, 'tag'),
include('eval-or-plain'),
],
'tag': [
include('css'),
(r'[<>]{1,2}(?=[ \t=])', Punctuation),
(r'[ \t]+\n', Punctuation, '#pop:2'),
include('eval-or-plain'),
],
'plain': [
(r'([^#\n]|#[^{\n]|(\\\\)*\\#\{)+', Text),
(r'(#\{)(.*?)(\})',
bygroups(String.Interpol, using(RubyLexer), String.Interpol)),
(r'\n', Text, 'root'),
],
'html-attributes': [
(r'=', Punctuation),
(r'"[^\"]+"', using(RubyLexer), 'tag'),
(r'\'[^\']+\'', using(RubyLexer), 'tag'),
(r'[\w]+', Text, 'tag'),
],
'slim-comment-block': [
(_dot + '+', Comment.Preproc),
(r'\n', Text, 'root'),
],
}
| |
# Copyright (c) 2014, Fundacion Dr. Manuel Sadosky
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
This module contains all the classes that handle the ARM instruction
representation.
"""
from barf.arch import ARCH_ARM_MODE_ARM
from barf.arch import ARCH_ARM_MODE_THUMB
from barf.arch import ArchitectureInformation
# Used in CS->BARF translator
arm_alias_reg_map = {
"a1" : "r0",
"a2" : "r1",
"a3" : "r2",
"a4" : "r3",
"v1" : "r4",
"v2" : "r5",
"v3" : "r6",
"v4" : "r7",
"v5" : "r8",
"v6" : "r9",
"v7" : "r10",
"v8" : "r11",
"sb" : "r9",
"sl" : "r10",
"fp" : "r11",
"ip" : "r12",
"sp" : "r13",
"lr" : "r14",
"pc" : "r15",
}
ARM_COND_CODE_EQ = 0
ARM_COND_CODE_NE = 1
ARM_COND_CODE_CS = 2
ARM_COND_CODE_CC = 3
ARM_COND_CODE_MI = 4
ARM_COND_CODE_PL = 5
ARM_COND_CODE_VS = 6
ARM_COND_CODE_VC = 7
ARM_COND_CODE_HI = 8
ARM_COND_CODE_LS = 9
ARM_COND_CODE_GE = 10
ARM_COND_CODE_LT = 11
ARM_COND_CODE_GT = 12
ARM_COND_CODE_LE = 13
ARM_COND_CODE_AL = 14
ARM_COND_CODE_HS = 15
ARM_COND_CODE_LO = 16
cc_mapper = {
"eq" : ARM_COND_CODE_EQ,
"ne" : ARM_COND_CODE_NE,
"cs" : ARM_COND_CODE_CS,
"hs" : ARM_COND_CODE_HS,
"cc" : ARM_COND_CODE_CC,
"lo" : ARM_COND_CODE_LO,
"mi" : ARM_COND_CODE_MI,
"pl" : ARM_COND_CODE_PL,
"vs" : ARM_COND_CODE_VS,
"vc" : ARM_COND_CODE_VC,
"hi" : ARM_COND_CODE_HI,
"ls" : ARM_COND_CODE_LS,
"ge" : ARM_COND_CODE_GE,
"lt" : ARM_COND_CODE_LT,
"gt" : ARM_COND_CODE_GT,
"le" : ARM_COND_CODE_LE,
"al" : ARM_COND_CODE_AL,
}
cc_inverse_mapper = {v: k for k, v in cc_mapper.items()}
ARM_LDM_STM_IA = 0
ARM_LDM_STM_IB = 1
ARM_LDM_STM_DA = 2
ARM_LDM_STM_DB = 3
ARM_LDM_STM_FD = 4
ARM_LDM_STM_FA = 5
ARM_LDM_STM_ED = 6
ARM_LDM_STM_EA = 7
ldm_stm_am_mapper = {
"ia" : ARM_LDM_STM_IA,
"ib" : ARM_LDM_STM_IB,
"da" : ARM_LDM_STM_DA,
"db" : ARM_LDM_STM_DB,
"fd" : ARM_LDM_STM_FD,
"fa" : ARM_LDM_STM_FA,
"ed" : ARM_LDM_STM_ED,
"ea" : ARM_LDM_STM_EA,
}
ldm_stm_am_inverse_mapper = {v: k for k, v in ldm_stm_am_mapper.items()}
ldm_stack_am_to_non_stack_am = {
ARM_LDM_STM_FA : ARM_LDM_STM_DA,
ARM_LDM_STM_FD : ARM_LDM_STM_IA,
ARM_LDM_STM_EA : ARM_LDM_STM_DB,
ARM_LDM_STM_ED : ARM_LDM_STM_IB,
}
stm_stack_am_to_non_stack_am = {
ARM_LDM_STM_ED : ARM_LDM_STM_DA,
ARM_LDM_STM_EA : ARM_LDM_STM_IA,
ARM_LDM_STM_FD : ARM_LDM_STM_DB,
ARM_LDM_STM_FA : ARM_LDM_STM_IB,
}
ARM_MEMORY_INDEX_OFFSET = 0
ARM_MEMORY_INDEX_PRE = 1
ARM_MEMORY_INDEX_POST = 2
class ArmArchitectureInformation(ArchitectureInformation):
"""This class describe the ARM architecture."""
regs_32 = [
("r0", 32),
("r1", 32),
("r2", 32),
("r3", 32),
("r4", 32),
("r5", 32),
("r6", 32),
("r7", 32),
("r8", 32),
("r9", 32),
("r10", 32),
("r11", 32),
("r12", 32),
("r13", 32),
("r14", 32),
("r15", 32),
("apsr", 32),
]
regs_32_alias = [
("sp", 32),
("lr", 32),
("pc", 32),
("fp", 32),
]
regs_flags = [
("nf", 1),
("zf", 1),
("cf", 1),
("vf", 1),
]
def __init__(self, architecture_mode):
self._arch_mode = architecture_mode
self._registers_all = []
self._registers_gp_all = []
self._registers_gp_base = []
self._registers_flags = []
self._registers_size = {}
self._alias_mapper = {}
self._load_registers()
self._load_alias_mapper()
@property
def architecture_mode(self):
return self._arch_mode
@property
def architecture_size(self):
arch_size_map = {
ARCH_ARM_MODE_ARM : 32,
ARCH_ARM_MODE_THUMB : 32,
}
return arch_size_map[self._arch_mode]
@property
def operand_size(self):
operand_size_map = {
ARCH_ARM_MODE_ARM : 32,
ARCH_ARM_MODE_THUMB : 32,
}
return operand_size_map[self._arch_mode]
@property
def address_size(self):
address_size_map = {
ARCH_ARM_MODE_ARM : 32,
ARCH_ARM_MODE_THUMB : 32,
}
return address_size_map[self._arch_mode]
@property
def registers_all(self):
"""Return all registers.
"""
return self._registers_all
@property
def registers_gp_all(self):
"""Return all general purpose registers.
"""
return self._registers_gp_all
@property
def registers_gp_base(self):
"""Return base general purpose registers.
"""
return self._registers_gp_base
@property
def registers_flags(self):
"""Return flag registers.
"""
return self._registers_flags
@property
def registers_size(self):
"""Return the size of all registers.
"""
return self._registers_size
@property
def alias_mapper(self):
"""Return registers alias mapper.
"""
return self._alias_mapper
@property
def max_instruction_size(self):
"""Return the maximum instruction size in bytes.
"""
instruction_size_map = {
ARCH_ARM_MODE_ARM : 4,
ARCH_ARM_MODE_THUMB : 2,
}
return instruction_size_map[self._arch_mode]
def instr_is_ret(self, instruction):
is_ret = False
# ARM: "POP reg, {reg*, pc}" instr.
if instruction.mnemonic == "pop" and \
("pc" in str(instruction.operands[1]) or \
"r15" in str(instruction.operands[1])):
is_ret = True
# ARM: "LDR pc, *" instr.
if instruction.mnemonic == "ldr" and \
("pc" in str(instruction.operands[0]) or \
"r15" in str(instruction.operands[0])):
is_ret = True
return is_ret
def instr_is_call(self, instruction):
return instruction.mnemonic == "bl"
def instr_is_halt(self, instruction):
return False
def instr_is_branch(self, instruction):
branch_instr = [
"b", "bx", "bne", "beq", "bpl", "ble", "bcs", "bhs", "blt", "bge",
"bhi", "blo", "bls"
]
return instruction.mnemonic_full in branch_instr
def instr_is_branch_cond(self, instruction):
branch_instr = [
"bne", "beq", "bpl", "ble", "bcs", "bhs", "blt", "bge",
"bhi", "blo", "bls"
]
return instruction.mnemonic_full in branch_instr
def _load_alias_mapper(self):
alias_mapper = {
"fp" : ("r11", 0),
"sp" : ("r13", 0),
"lr" : ("r14", 0),
"pc" : ("r15", 0),
}
flags_reg = "apsr"
flags_mapper = {
"nf": (flags_reg, 31),
"zf": (flags_reg, 30),
"cf": (flags_reg, 29),
"vf": (flags_reg, 28),
}
alias_mapper.update(flags_mapper)
self._alias_mapper = alias_mapper
def _load_registers(self):
registers_all = self.regs_flags + self.regs_32 + self.regs_32_alias
registers_gp_all = self.regs_32 + self.regs_32_alias
registers_gp_base = self.regs_32
for name, size in registers_all:
self._registers_all.append(name)
self._registers_size[name] = size
for name, size in registers_gp_all:
self._registers_gp_all.append(name)
self._registers_size[name] = size
for name, size in registers_gp_base:
self._registers_gp_base.append(name)
self._registers_size[name] = size
self._registers_flags = [name for name, _ in self.regs_flags]
def registers(self):
return []
class ArmInstruction(object):
"""Representation of ARM instruction."""
__slots__ = [
'_orig_instr',
'_mnemonic',
'_operands',
'_bytes',
'_size',
'_address',
'_arch_mode',
'_condition_code',
'_update_flags',
'_ldm_stm_addr_mode',
]
def __init__(self, orig_instr, mnemonic, operands, arch_mode):
self._orig_instr = orig_instr
self._mnemonic = mnemonic
self._operands = operands
self._bytes = ""
self._size = 4 # TODO: Thumb
self._address = None
self._arch_mode = arch_mode
self._condition_code = None
self._update_flags = False
self._ldm_stm_addr_mode = None
@property
def orig_instr(self):
"""Get instruction string before parsing."""
return self._orig_instr
@property
def mnemonic(self):
"""Get instruction mnemonic."""
return self._mnemonic
@property
def mnemonic_full(self):
"""Get instruction mnemonic with condition code."""
return self._mnemonic + cc_inverse_mapper[self.condition_code]
@property
def operands(self):
"""Get instruction operands."""
return self._operands
@operands.setter
def operands(self, value):
"""Set instruction operands."""
self._operands = value
@property
def bytes(self):
"""Get instruction byte representation."""
return self._bytes
@bytes.setter
def bytes(self, value):
"""Set instruction byte representation."""
self._bytes = value
@property
def size(self):
"""Get instruction size."""
return self._size
@size.setter
def size(self, value):
"""Set instruction size."""
self._size = value
@property
def address(self):
"""Get instruction address."""
return self._address
@address.setter
def address(self, value):
"""Set instruction address."""
self._address = value
@property
def condition_code(self):
return self._condition_code
@condition_code.setter
def condition_code(self, value):
self._condition_code = value
@property
def update_flags(self):
return self._update_flags
@update_flags.setter
def update_flags(self, value):
self._update_flags = value
@property
def ldm_stm_addr_mode(self):
return self._ldm_stm_addr_mode
@ldm_stm_addr_mode.setter
def ldm_stm_addr_mode(self, value):
self._ldm_stm_addr_mode = value
def __str__(self):
operands_str = ", ".join([str(oprnd) for oprnd in self._operands])
string = self.mnemonic
if self.condition_code is not None:
string += cc_inverse_mapper[self.condition_code]
if self.ldm_stm_addr_mode is not None:
string += ldm_stm_am_inverse_mapper[self.ldm_stm_addr_mode]
string += " " + operands_str if operands_str else ""
return string
def __eq__(self, other):
return self.prefix == other.prefix and \
self.mnemonic == other.mnemonic and \
self.operands == other.operands and \
self.bytes == other.bytes and \
self.size == other.size and \
self.address == other.address
def __ne__(self, other):
return not self.__eq__(other)
@property
def prefix(self):
return ""
class ArmOperand(object):
"""Representation of ARM operand."""
__slots__ = [
'_modifier',
'_size',
]
def __init__(self, modifier):
self._modifier = modifier
self._size = None
@property
def modifier(self):
"""Get operand modifier."""
return self._modifier
@modifier.setter
def modifier(self, value):
"""Set operand modifier."""
self._modifier = value
@property
def size(self):
"""Get operand size."""
return self._size
@size.setter
def size(self, value):
"""Set operand size."""
self._size = value
def to_string(self, **kwargs):
return self.__str__()
class ArmImmediateOperand(ArmOperand):
"""Representation of ARM immediate operand."""
__slots__ = [
'_immediate',
'_base_hex',
'_size',
]
def __init__(self, immediate, size=None):
super(ArmImmediateOperand, self).__init__("")
self._base_hex = True
if type(immediate) == str:
immediate = immediate.replace("#", "")
if '0x' in immediate:
immediate = int(immediate, 16)
else:
immediate = int(immediate)
self._base_hex = False
assert type(immediate) in [int, long], "Invalid immediate value type."
self._immediate = immediate
self._size = size
@property
def immediate(self):
"""Get immediate."""
if not self._size:
raise Exception("Operand size missing.")
return self._immediate
def to_string(self, **kwargs):
if not self._size:
raise Exception("Operand size missing.")
immediate_format = kwargs.get("immediate_format", "hex")
if immediate_format == "hex":
# string = "#" + hex(self._immediate)
string = hex(self._immediate)
elif immediate_format == "dec":
string = str(self._immediate)
else:
raise Exception("Invalid immediate format: {}".format(imm_fmt))
return string[:-1] if string[-1] == 'L' else string
def __str__(self):
if not self._size:
raise Exception("Operand size missing.")
string = '#' + (hex(self._immediate) if self._base_hex else str(self._immediate))
return string[:-1] if string[-1] == 'L' else string
def __eq__(self, other):
return self.immediate == other.immediate
def __ne__(self, other):
return not self.__eq__(other)
class ArmRegisterOperand(ArmOperand):
"""Representation of ARM register operand."""
__slots__ = [
'_name',
'_size',
'_wb',
]
def __init__(self, name, size=None):
super(ArmRegisterOperand, self).__init__("")
self._name = name
self._size = size
self._wb = False
@property
def name(self):
"""Get register name."""
if not self._size:
raise Exception("Operand size missing.")
return self._name
@property
def wb(self):
return self._wb
@wb.setter
def wb(self, value):
self._wb = value
def __str__(self):
if not self._size:
raise Exception("Operand size missing.")
string = self._modifier + " " if self._modifier else ""
string += self._name
return string
def __eq__(self, other):
return self.modifier == other.modifier and \
self.size == other.size and \
self.name == other.name
def __ne__(self, other):
return not self.__eq__(other)
class ArmRegisterListOperand(ArmOperand):
"""Representation of ARM register operand."""
__slots__ = [
'_reg_list',
'_size',
]
def __init__(self, reg_list, size=None):
super(ArmRegisterListOperand, self).__init__("")
self._reg_list = reg_list
self._size = size
@property
def reg_list(self):
"""Get register list."""
if not self._size:
raise Exception("Operand size missing.")
return self._reg_list
def __str__(self):
if not self._size:
raise Exception("Operand size missing.")
string = "{"
for i in range(len(self._reg_list)):
if i > 0:
string += ", "
reg_range = self._reg_list[i]
string += str(reg_range[0])
if len(reg_range) > 1:
string += " - " + str(reg_range[1])
string += "}"
return string
def __eq__(self, other):
return self._reg_list == other._reg_list and \
self.size == other.size
def __ne__(self, other):
return not self.__eq__(other)
class ArmShiftedRegisterOperand(ArmOperand):
"""Representation of ARM register operand."""
__slots__ = [
'_base_reg',
'_shift_type',
'_shift_amount',
'_size',
]
def __init__(self, base_reg, shift_type, shift_amount, size=None):
super(ArmShiftedRegisterOperand, self).__init__("")
self._base_reg = base_reg
self._shift_type = shift_type
self._shift_amount = shift_amount
self._size = size
@property
def base_reg(self):
"""Get base register."""
if not self._size:
raise Exception("Operand size missing.")
return self._base_reg
@property
def shift_type(self):
"""Get shift type."""
if not self._size:
raise Exception("Operand size missing.")
return self._shift_type
@property
def shift_amount(self):
"""Get shift amount."""
if not self._size:
raise Exception("Operand size missing.")
return self._shift_amount
def __str__(self):
if not self._size:
raise Exception("Operand size missing.")
string = str(self._base_reg) + ", " + str(self._shift_type)
if self._shift_amount:
string += " " + str(self._shift_amount)
return string
def __eq__(self, other):
return self._base_reg == other._base_reg and \
self._shift_type == other._shift_type and \
self._shift_amount == other._shift_amount
def __ne__(self, other):
return not self.__eq__(other)
class ArmMemoryOperand(ArmOperand):
"""Representation of ARM memory operand."""
__slots__ = [
'_base_reg',
'_index_type',
'_displacement',
'_disp_minus',
'_size',
]
def __init__(self, base_reg, index_type, displacement, disp_minus = False, size=None):
super(ArmMemoryOperand, self).__init__("")
self._base_reg = base_reg
self._index_type = index_type
self._displacement = displacement
self._disp_minus = disp_minus
self._size = size
@property
def base_reg(self):
"""Get base register."""
if not self._size:
raise Exception("Operand size missing.")
return self._base_reg
@property
def displacement(self):
"""Get displacement to the base register."""
if not self._size:
raise Exception("Operand size missing.")
return self._displacement
@property
def index_type(self):
"""Get type of memory indexing."""
if not self._size:
raise Exception("Operand size missing.")
return self._index_type
@property
def disp_minus(self):
"""Get sign of displacemnt."""
if not self._size:
raise Exception("Operand size missing.")
return self._disp_minus
def __str__(self):
if not self._size:
raise Exception("Operand size missing.")
disp_str = "-" if self._disp_minus else ""
disp_str += str(self._displacement)
string = "[" + str(self._base_reg)
if (self._index_type == ARM_MEMORY_INDEX_OFFSET):
if self._displacement:
string += ", " + disp_str
string += "]"
elif (self._index_type == ARM_MEMORY_INDEX_PRE):
string += ", " + disp_str + "]!"
elif (self._index_type == ARM_MEMORY_INDEX_POST):
string += "], " + disp_str
else:
raise Exception("Unknown memory index type.")
return string
def __eq__(self, other):
return self._base_reg == other._base_reg and \
self._index_type == other._index_type and \
self._displacement == other._displacement
def __ne__(self, other):
return not self.__eq__(other)
| |
import numpy as np
import numpy.matlib as matlib
import random
from math import sin, sqrt
''' Problem Definition'''
def MOP2(x):
n=len(x)
z1=1-np.exp(-np.sum(np.power((x-1/sqrt(n)),2))) #ckeck exp for single
z2=1-np.exp(-np.sum((x+1/sqrt(n))**2))
z=np.array([z1,z2])
return z
def MOP4(x):
a=0.8
b=3
z1=np.sum(-10*exp(-0.2*sqrt(np.power(x[0:-1],2)+np.power(x[1:],2))))
z2=np.sum(np.power(np.absolute(x),a)+5*(np.power((np.sin(x)),b)))
z=np.array([z1,z2])
return z
def RouletteWheelSelection(P):
r=random.random()
C=np.cumsum(P)
i=(np.array([np.nonzero(r<=C)]))[0][0][0]
return i
def CostFunction(x):
n=len(x)
f1=x[0]
den = (n-1)*np.sum(x[1:])
g= 1+9/den
h=1-sqrt(f1/g)
f2=g*h
z=np.array([f1,f2])
return z
class mty_grid:
pass
def CreateGrid(pop,nGrid,alpha):
c=[]
for p in pop:
c.append(p.Cost)
c=np.array([c])
cmin=np.amin(c, axis=1)
cmax=np.amax(c, axis=1)
dc=cmax-cmin
cmin=cmin-alpha*dc
cmax=cmax+alpha*dc
nObj=list(np.shape(c))[2]
GridLB=np.zeros((nObj, 2,nGrid+1))
GridUB=np.zeros((nObj, 2,nGrid+1)) # change range(1.+1) to 0,+0
inf_arr =np.array([ float('inf') for i in range(nGrid+1) ])
for j in range(nObj):
cj=np.linspace(cmin[0][j],cmax[0][j],num = nGrid+1)
GridLB[j]=[-(inf_arr),cj]
GridUB[j]=[cj,inf_arr]
return GridLB,GridUB
def FindGridIndex(particle,GridLB,GridUB):
nObj=len(particle.Cost)
nGrid=len(GridLB[0])
particle.GridSubIndex=np.zeros((1,nObj))
for j in range(0,nObj):
particle.GridSubIndex[0][j]= (np.array([np.nonzero(particle.Cost[j]<GridUB[0][j])])[0][0][:])[0]
particle.GridIndex=particle.GridSubIndex[0][0]
for j in range(0,nObj):
particle.GridIndex=particle.GridIndex-1
particle.GridIndex=nGrid*particle.GridIndex
particle.GridIndex=particle.GridIndex+particle.GridSubIndex[0][j]
return particle
def Mutate(x,pm,VarMin,VarMax):
nVar=len(x)
j=np.random.randint(0, high=nVar)
dx=pm*(VarMax-VarMin)
lb=x[j]-dx
if lb<VarMin:
lb=VarMin
ub = x[j]+dx
if ub>VarMax:
ub=VarMax
xnew = x
xnew[j]=np.random.uniform(lb,ub)
return xnew
def Dominates(x,y):
x=x.Cost
y=y.Cost #ckeck again
b=np.all(x<=y) and np.any(x<y)
return b
def SelectLeader(rep,beta):
# Grid Index of All Repository Members
GI=np.array([re.GridIndex for re in rep])
# Occupied Cells
OC = np.unique(GI)
# Number of Particles in Occupied Cells
N=np.zeros(list(np.shape(OC)))
for k in range(len(OC)):
ind = np.array([np.nonzero(GI==OC[k])])[0][0]
indx = [i for i in ind]
N[k]=len(indx)
# Selection Probabilities
P=np.exp(-beta*N)
P=P/np.sum(P)
# Selected Cell Index
sci=RouletteWheelSelection(P)
# Selected Cell
sc=OC[sci]
# Selected Cell Members
SCM=np.array([np.nonzero(GI==sc)])[0][0][:]
# Selected Member Index
if len(SCM) == 0:
smi = 0
else:
smi=np.random.randint(0,high = len(SCM))
# Selected Member
sm=SCM[smi]
# Leader
leader=rep[sm]
return leader
def DeleteOneRepMemebr(rep,gamma):
#Grid Index of All Repository Members
GI=np.array([re.GridIndex for re in rep])
# Occupied Cells
OC=np.unique(GI)
# Number of Particles in Occupied Cells
N=np.zeros(list(np.shape(OC)))
for k in range(len(OC)):
N[k]=len(np.array([np.nonzero(GI==OC[k])])[0][0][:])
# Selection Probabilities
P=np.exp(gamma*N)
# Selected Cell Index
sci=RouletteWheelSelection(P)
# Selected Cell
sc=OC[sci]
# Selected Cell Members
SCM=np.array([np.nonzero(GI==OC[k])])[0][0][:]
# Selected Member Index
smi=np.random.randini(1,high = len(SCM))
# Selected Member
sm=SCM[smi]
# Delete Selected Member
rep[sm]=np.array([])
return rep
def DetermineDomination(particles):
nPop = len (particles)
for p in particles:
p.IsDominated=False
for i in range(nPop-1):
for j in range(i,nPop):
if Dominates(particles[i],particles[j]):
particles[j].IsDominated=True
if Dominates(particles[j],particles[i]):
particles[i].IsDominated=True
return particles
nVar=2 #Number of Decision Variables
VarSize=np.array([1,nVar]) # Size of Decision Variables Matrix
VarMin=0 # Lower Bound of Variables
VarMax=1 # Upper Bound of Variables
MaxIt=100 # Maximum Number of Iterations
nPop=20 # Population Size
nRep=100 # Repository Size
w=0.5 # Inertia Weight
wdamp=0.99 # Intertia Weight Damping Rate
c1=1 # Personal Learning Coefficient
c2=2 # Global Learning Coefficient
nGrid=7 # Number of Grids per Dimension
alpha=0.1 # Inflation Rate
beta=2 # Leader Selection Pressure
gamma=2 # Deletion Selection Pressure
mu=0.1 # Mutation Rate
class Particle:
pass
''' Initialization '''
particles = []
for i in range(nPop):
p = Particle()
p.Position=np.array([])
p.Best = Particle()
p.Best.Position=np.array([])
p.Velocity=np.array([])
p.Best.Cost = np.array([])
p.Cost = np.array([])
p.IsDominated =np.array([])
p.GridIndex = np.array([])
p.GridSubIndex =np.array([])
particles.append(p)
for p in particles:
p.Position=np.array([random.random() for _ in range(nVar)] )
p.Velocity=np.array([0 for _ in range(nVar)])
p.Cost=CostFunction(p.Position)
# Update Personal Best
p.Best.Position=p.Position
p.Best.Cost=p.Cost
# Determine Domination
particles=DetermineDomination(particles)
pre_rep = []
for p in particles:
pre_rep.append(not p.IsDominated)
particle_array = np.array(particles)
rep=particle_array[np.array(pre_rep)]
GridLB,GridUB=CreateGrid(rep,nGrid,alpha)
for i in range(len(rep)):
rep[i]=FindGridIndex(rep[i],GridLB,GridUB)
# MOPSO Main Loop
for it in range(1,MaxIt+1):
for i in range(nPop):
leader=SelectLeader(rep,beta)
particles[i].Velocity = w*particles[i].Velocity \
+np.multiply(c1*np.random.rand(1,nVar),(particles[i].Best.Position-particles[i].Position)) \
+np.multiply(c2*np.random.rand(1,nVar),(leader.Position-particles[i].Position))
particles[i].Position = particles[i].Position + particles[i].Velocity[0]
particles[i].Position = np.maximum(particles[i].Position, VarMin)
particles[i].Position = np.minimum(particles[i].Position, VarMax)
particles[i].Cost = CostFunction(particles[i].Position)
NewSol = Particle()
# Apply Mutation
pm=(1-(it-1)/(MaxIt-1))**(1/mu)
if random.random()<pm:
NewSol.Position=Mutate(particles[i].Position,pm,VarMin,VarMax)
NewSol.Cost=CostFunction(NewSol.Position)
if Dominates(NewSol,particles[i]):
particles[i].Position=NewSol.Position
particles[i].Cost=NewSol.Cost
elif Dominates(particles[i],NewSol):
pass
else:
if random.random()<0.5:
particles[i].Position=NewSol.Position
particles[i].Cost=NewSol.Cost
if Dominates(particles[i],particles[i].Best):
particles[i].Best.Position=particles[i].Position
particles[i].Best.Cost=particles[i].Cost
elif Dominates(particles[i].Best,particles[i]):
pass
else:
if random.random()<0.5:
particles[i].Best.Position=particles[i].Position
particles[i].Best.Cost=particles[i].Cost
DetermineDomination(particles)
dom_particles = np.array([ not p.IsDominated for p in particles])
# Add Non-Dominated Particles to REPOSITORY
parray = np.array(particles)
rep=np.array([rep,parray[dom_particles]]) #ok
# Determine Domination of New Resository Members
rep=DetermineDomination(rep[0])
# Keep only Non-Dminated Memebrs in the Repository
pre_rep1 = []
for p in rep:
pre_rep1.append(not p.IsDominated)
rep=rep[pre_rep1]
# Update Grid
GridLB,GridUB=CreateGrid(rep,nGrid,alpha)
# Update Grid Indices
for i in range(0,len(rep)):
rep[i]=FindGridIndex(rep[i],GridLB,GridUB)
# Check if Repository is Full
if len(rep)>nRep:
Extra=len(rep)-nRep
for e in range(1,Extra+1):
rep=DeleteOneRepMemebr(rep,gamma)
# Plot Costs
# Show Iteration Information
print 'Iteration ',str(it),': Number of Rep Members = ',str(len(rep)),leader.Cost
# Damping Inertia Weight
w= w*wdamp
| |
import itertools
from datetime import datetime, timedelta
from subprocess import Popen, PIPE
from django.conf import settings
from django.db import connection
import cronjobs
import commonware.log
import waffle
from olympia import amo
from olympia.amo.utils import chunked
from olympia.amo.helpers import user_media_path
from olympia.bandwagon.models import Collection
from olympia.constants.base import VALID_STATUSES
from olympia.devhub.models import ActivityLog
from olympia.lib.es.utils import raise_if_reindex_in_progress
from olympia.stats.models import Contribution
from . import tasks
log = commonware.log.getLogger('z.cron')
@cronjobs.register
def gc(test_result=True):
"""Site-wide garbage collections."""
def days_ago(days):
return datetime.today() - timedelta(days=days)
log.debug('Collecting data to delete')
logs = (ActivityLog.objects.filter(created__lt=days_ago(90))
.exclude(action__in=amo.LOG_KEEP).values_list('id', flat=True))
# Paypal only keeps retrying to verify transactions for up to 3 days. If we
# still have an unverified transaction after 6 days, we might as well get
# rid of it.
contributions_to_delete = (
Contribution.objects
.filter(transaction_id__isnull=True, created__lt=days_ago(6))
.values_list('id', flat=True))
collections_to_delete = (
Collection.objects.filter(created__lt=days_ago(2),
type=amo.COLLECTION_ANONYMOUS)
.values_list('id', flat=True))
for chunk in chunked(logs, 100):
tasks.delete_logs.delay(chunk)
for chunk in chunked(contributions_to_delete, 100):
tasks.delete_stale_contributions.delay(chunk)
for chunk in chunked(collections_to_delete, 100):
tasks.delete_anonymous_collections.delay(chunk)
# Incomplete addons cannot be deleted here because when an addon is
# rejected during a review it is marked as incomplete. See bug 670295.
log.debug('Cleaning up test results extraction cache.')
# lol at check for '/'
if settings.MEDIA_ROOT and settings.MEDIA_ROOT != '/':
cmd = ('find', settings.MEDIA_ROOT, '-maxdepth', '1', '-name',
'validate-*', '-mtime', '+7', '-type', 'd',
'-exec', 'rm', '-rf', "{}", ';')
output = Popen(cmd, stdout=PIPE).communicate()[0]
for line in output.split("\n"):
log.debug(line)
else:
log.warning('MEDIA_ROOT not defined.')
if user_media_path('collection_icons'):
log.debug('Cleaning up uncompressed icons.')
cmd = ('find', user_media_path('collection_icons'),
'-name', '*__unconverted', '-mtime', '+1', '-type', 'f',
'-exec', 'rm', '{}', ';')
output = Popen(cmd, stdout=PIPE).communicate()[0]
for line in output.split("\n"):
log.debug(line)
USERPICS_PATH = user_media_path('userpics')
if USERPICS_PATH:
log.debug('Cleaning up uncompressed userpics.')
cmd = ('find', USERPICS_PATH,
'-name', '*__unconverted', '-mtime', '+1', '-type', 'f',
'-exec', 'rm', '{}', ';')
output = Popen(cmd, stdout=PIPE).communicate()[0]
for line in output.split("\n"):
log.debug(line)
@cronjobs.register
def category_totals():
"""
Update category counts for sidebar navigation.
"""
log.debug('Starting category counts update...')
p = ",".join(['%s'] * len(VALID_STATUSES))
cursor = connection.cursor()
cursor.execute("""
UPDATE categories AS t INNER JOIN (
SELECT at.category_id, COUNT(DISTINCT Addon.id) AS ct
FROM addons AS Addon
INNER JOIN versions AS Version ON (Addon.id = Version.addon_id)
INNER JOIN applications_versions AS av ON (av.version_id = Version.id)
INNER JOIN addons_categories AS at ON (at.addon_id = Addon.id)
INNER JOIN files AS File ON (Version.id = File.version_id
AND File.status IN (%s))
WHERE Addon.status IN (%s) AND Addon.inactive = 0
GROUP BY at.category_id)
AS j ON (t.id = j.category_id)
SET t.count = j.ct
""" % (p, p), VALID_STATUSES * 2)
@cronjobs.register
def collection_subscribers():
"""
Collection weekly and monthly subscriber counts.
"""
log.debug('Starting collection subscriber update...')
if not waffle.switch_is_active('local-statistics-processing'):
return False
cursor = connection.cursor()
cursor.execute("""
UPDATE collections SET weekly_subscribers = 0, monthly_subscribers = 0
""")
cursor.execute("""
UPDATE collections AS c
INNER JOIN (
SELECT
COUNT(collection_id) AS count,
collection_id
FROM collection_subscriptions
WHERE created >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
GROUP BY collection_id
) AS weekly ON (c.id = weekly.collection_id)
INNER JOIN (
SELECT
COUNT(collection_id) AS count,
collection_id
FROM collection_subscriptions
WHERE created >= DATE_SUB(CURDATE(), INTERVAL 31 DAY)
GROUP BY collection_id
) AS monthly ON (c.id = monthly.collection_id)
SET c.weekly_subscribers = weekly.count,
c.monthly_subscribers = monthly.count
""")
@cronjobs.register
def unconfirmed():
"""
Delete user accounts that have not been confirmed for two weeks.
"""
log.debug("Removing user accounts that haven't been confirmed "
"for two weeks...")
cursor = connection.cursor()
cursor.execute("""
DELETE users
FROM users
LEFT JOIN addons_users on users.id = addons_users.user_id
LEFT JOIN addons_collections ON users.id=addons_collections.user_id
LEFT JOIN collections_users ON users.id=collections_users.user_id
WHERE users.created < DATE_SUB(CURDATE(), INTERVAL 2 WEEK)
AND users.confirmationcode != ''
AND addons_users.user_id IS NULL
AND addons_collections.user_id IS NULL
AND collections_users.user_id IS NULL
""")
@cronjobs.register
def weekly_downloads():
"""
Update 7-day add-on download counts.
"""
if not waffle.switch_is_active('local-statistics-processing'):
return False
raise_if_reindex_in_progress('amo')
cursor = connection.cursor()
cursor.execute("""
SELECT addon_id, SUM(count) AS weekly_count
FROM download_counts
WHERE `date` >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
GROUP BY addon_id
ORDER BY addon_id""")
counts = cursor.fetchall()
addon_ids = [r[0] for r in counts]
if not addon_ids:
return
cursor.execute("""
SELECT id, 0
FROM addons
WHERE id NOT IN %s""", (addon_ids,))
counts += cursor.fetchall()
cursor.execute("""
CREATE TEMPORARY TABLE tmp_wd
(addon_id INT PRIMARY KEY, count INT)""")
cursor.execute('INSERT INTO tmp_wd VALUES %s' %
','.join(['(%s,%s)'] * len(counts)),
list(itertools.chain(*counts)))
cursor.execute("""
UPDATE addons INNER JOIN tmp_wd
ON addons.id = tmp_wd.addon_id
SET weeklydownloads = tmp_wd.count""")
cursor.execute("DROP TABLE IF EXISTS tmp_wd")
| |
# -*- coding: utf-8 -*-
"""
trueskill.mathematics
~~~~~~~~~~~~~~~~~~~~~
This module contains basic mathematics functions and objects for TrueSkill
algorithm. If you have not scipy, this module provides the fallback.
:copyright: (c) 2012-2013 by Heungsub Lee.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import copy
import math
try:
from numbers import Number
except ImportError:
Number = (int, long, float, complex)
__all__ = ['Gaussian', 'Matrix', 'inf']
inf = float('inf')
class Gaussian(object):
"""A model for the normal distribution."""
#: Precision, the inverse of the variance.
pi = 0
#: Precision adjusted mean, the precision multiplied by the mean.
tau = 0
def __init__(self, mu=None, sigma=None, pi=0, tau=0):
if mu is not None:
if sigma is None:
raise TypeError('sigma argument is needed')
elif sigma == 0:
raise ValueError('sigma**2 should be greater than 0')
pi = sigma ** -2
tau = pi * mu
self.pi = pi
self.tau = tau
@property
def mu(self):
"""A property which returns the mean."""
return self.pi and self.tau / self.pi
@property
def sigma(self):
"""A property which returns the the square root of the variance."""
return math.sqrt(1 / self.pi) if self.pi else inf
def __mul__(self, other):
pi, tau = self.pi + other.pi, self.tau + other.tau
return Gaussian(pi=pi, tau=tau)
def __truediv__(self, other):
pi, tau = self.pi - other.pi, self.tau - other.tau
return Gaussian(pi=pi, tau=tau)
__div__ = __truediv__ # for Python 2
def __eq__(self, other):
return self.pi == other.pi and self.tau == other.tau
def __lt__(self, other):
return self.mu < other.mu
def __le__(self, other):
return self.mu <= other.mu
def __gt__(self, other):
return self.mu > other.mu
def __ge__(self, other):
return self.mu >= other.mu
def __repr__(self):
return 'N(mu=%.3f, sigma=%.3f)' % (self.mu, self.sigma)
def _repr_latex_(self):
latex = r'\mathcal{ N }( %.3f, %.3f^2 )' % (self.mu, self.sigma)
return '$%s$' % latex
class Matrix(list):
"""A model for matrix."""
def __init__(self, src, height=None, width=None):
if callable(src):
f, src = src, {}
size = [height, width]
if not height:
def set_height(height):
size[0] = height
size[0] = set_height
if not width:
def set_width(width):
size[1] = width
size[1] = set_width
try:
for (r, c), val in f(*size):
src[r, c] = val
except TypeError:
raise TypeError('A callable src must return an interable '
'which generates a tuple containing '
'coordinate and value')
height, width = tuple(size)
if height is None or width is None:
raise TypeError('A callable src must call set_height and '
'set_width if the size is non-deterministic')
if isinstance(src, list):
is_number = lambda x: isinstance(x, Number)
unique_col_sizes = set(map(len, src))
everything_are_number = filter(is_number, sum(src, []))
if len(unique_col_sizes) != 1 or not everything_are_number:
raise ValueError('src must be a rectangular array of numbers')
two_dimensional_array = src
elif isinstance(src, dict):
if not height or not width:
w = h = 0
for r, c in src.iterkeys():
if not height:
h = max(h, r + 1)
if not width:
w = max(w, c + 1)
if not height:
height = h
if not width:
width = w
two_dimensional_array = []
for r in range(height):
row = []
two_dimensional_array.append(row)
for c in range(width):
row.append(src.get((r, c), 0))
else:
raise TypeError('src must be a list or dict or callable')
super(Matrix, self).__init__(two_dimensional_array)
@property
def height(self):
return len(self)
@property
def width(self):
return len(self[0])
def transpose(self):
height, width = self.height, self.width
src = {}
for c in range(width):
for r in range(height):
src[c, r] = self[r][c]
return type(self)(src, height=width, width=height)
def minor(self, row_n, col_n):
height, width = self.height, self.width
if not (0 <= row_n < height):
raise ValueError('row_n should be between 0 and %d' % height)
elif not (0 <= col_n < width):
raise ValueError('col_n should be between 0 and %d' % width)
two_dimensional_array = []
for r in range(height):
if r == row_n:
continue
row = []
two_dimensional_array.append(row)
for c in range(width):
if c == col_n:
continue
row.append(self[r][c])
return type(self)(two_dimensional_array)
def determinant(self):
height, width = self.height, self.width
if height != width:
raise ValueError('Only square matrix can calculate a determinant')
tmp, rv = copy.deepcopy(self), 1.
for c in range(width - 1, 0, -1):
pivot, r = max((abs(tmp[r][c]), r) for r in range(c + 1))
pivot = tmp[r][c]
if not pivot:
return 0.
tmp[r], tmp[c] = tmp[c], tmp[r]
if r != c:
rv = -rv
rv *= pivot
fact = -1. / pivot
for r in range(c):
f = fact * tmp[r][c]
for x in range(c):
tmp[r][x] += f * tmp[c][x]
return rv * tmp[0][0]
def adjugate(self):
height, width = self.height, self.width
if height != width:
raise ValueError('Only square matrix can be adjugated')
if height == 2:
a, b = self[0][0], self[0][1]
c, d = self[1][0], self[1][1]
return type(self)([[d, -b], [-c, a]])
src = {}
for r in range(height):
for c in range(width):
sign = -1 if (r + c) % 2 else 1
src[r, c] = self.minor(r, c).determinant() * sign
return type(self)(src, height, width)
def inverse(self):
if self.height == self.width == 1:
return type(self)([[1. / self[0][0]]])
return (1. / self.determinant()) * self.adjugate()
def __add__(self, other):
height, width = self.height, self.width
if (height, width) != (other.height, other.width):
raise ValueError('Must be same size')
src = {}
for r in range(height):
for c in range(width):
src[r, c] = self[r][c] + other[r][c]
return type(self)(src, height, width)
def __mul__(self, other):
if self.width != other.height:
raise ValueError('Bad size')
height, width = self.height, other.width
src = {}
for r in range(height):
for c in range(width):
src[r, c] = sum(self[r][x] * other[x][c]
for x in range(self.width))
return type(self)(src, height, width)
def __rmul__(self, other):
if not isinstance(other, Number):
raise TypeError('The operand should be a number')
height, width = self.height, self.width
src = {}
for r in range(height):
for c in range(width):
src[r, c] = other * self[r][c]
return type(self)(src, height, width)
def __repr__(self):
return '%s(%s)' % (type(self).__name__, super(Matrix, self).__repr__())
def _repr_latex_(self):
rows = [' && '.join(['%.3f' % cell for cell in row]) for row in self]
latex = r'\begin{matrix} %s \end{matrix}' % r'\\'.join(rows)
return '$%s$' % latex
| |
from __future__ import print_function
import os
import time
import numpy as np
import theano
import theano.tensor as T
import lasagne
import matplotlib.pyplot as plt
from tqdm import tqdm
from mpl_toolkits.axes_grid1 import make_axes_locatable
from lasagne.layers import InputLayer, Conv2DLayer, Pool2DLayer
from lasagne.regularization import regularize_network_params, l2
VERBOSE = False
GRID_SEARCH = True
def bootstrap(data, labels, boot_type="downsample"):
print("Bootstrapping data...")
ot_class = 0
mw_class = 1
ot_idx = np.where(labels == ot_class)
mw_idx = np.where(labels == mw_class)
# Get OT examples
ot_data = data[ot_idx]
ot_labels = labels[ot_idx]
print(" - OT (class: {}) | Data: {} | Labels: {}".format(ot_class, ot_data.shape, ot_labels.shape))
# Get MW examples
mw_data = data[mw_idx]
mw_labels = labels[mw_idx]
print(" - MW (class: {}) | Data: {} | Labels: {}".format(mw_class, mw_data.shape, mw_labels.shape))
# Set majority and minority classes
if ot_data.shape[0] > mw_data.shape[0]:
maj_class, maj_data, maj_labels = ot_class, ot_data, ot_labels
min_class, min_data, min_labels = mw_class, mw_data, mw_labels
else:
maj_class, maj_data, maj_labels = mw_class, mw_data, mw_labels
min_class, min_data, min_labels = ot_class, ot_data, ot_labels
print(" - Majority class: {} (N = {}) | Minority class: {} (N = {})".format(maj_class, maj_data.shape[0],
min_class, min_data.shape[0]))
# Upsample minority class
if boot_type == "upsample":
print("Upsampling minority class...")
num_to_boot = maj_data.shape[0] - min_data.shape[0]
print(" - Number to upsample: {}".format(num_to_boot))
bootstrap_idx = np.random.randint(min_data.shape[0], size=num_to_boot)
min_data_boot = min_data[bootstrap_idx]
min_labels_boot = min_labels[bootstrap_idx]
final_data = np.concatenate((data, min_data_boot), axis=0)
final_labels = np.concatenate((labels, min_labels_boot), axis=0)
elif boot_type == "downsample":
print("Downsampling majority class...")
# Resample N = number of minority examples
num_to_boot = min_data.shape[0]
bootstrap_idx = np.random.randint(maj_data.shape[0], size=num_to_boot)
maj_data_boot = maj_data[bootstrap_idx]
maj_labels_boot = maj_labels[bootstrap_idx]
final_data = np.concatenate((maj_data_boot, min_data), axis=0)
final_labels = np.concatenate((maj_labels_boot, min_labels), axis=0)
print("Final class balance: {} ({}) - {} ({})".format(
maj_class, len(np.where(final_labels==maj_class)[0]),
min_class, len(np.where(final_labels==min_class)[0])))
return final_data, final_labels
# Load EEG data
base_dir = os.path.abspath(os.path.join(os.path.join(os.path.dirname(__file__), os.pardir), os.pardir))
data_dir = os.path.join(base_dir, "data")
data_labels = np.load(os.path.join(data_dir, 'all_data_6_2d_full_30ch_bands_labels.npy'))
data_labels = data_labels[:,1]
# Electrode Order (30 channels)
electrode_order_30 = ('Fp1','Fp2','Fz',
'F4','F8','FC6',
'C4','T8','CP6',
'P4','P8','P10',
'O2','Oz','O1',
'P9','P3','P7',
'CP5','C3','T7',
'FC5','F7','F3',
'FC1','FC2','Cz',
'CP1','CP2','Pz')
xcorr_file = os.path.join(data_dir, "eeg_xcorr_30ch.npy") # Path to xcorr data
if os.path.exists(xcorr_file):
# Load the xcorr data if it already exists
data = np.load(xcorr_file)
else:
# Load raw eeg data for processing
data = np.load(os.path.join(data_dir, 'all_data_6_2d_full_30ch_bands.npy'))
# Preallocate a (5478, 5, 30, 30) array
temp_xcorr = np.zeros((data.shape[0], data.shape[1], data.shape[2], 30)).astype('float32')
# Calculate cross-correlation matrix
print("Calculating cross-correlation matrices...")
for trial in tqdm(range(data.shape[0])):
for freq in range(data.shape[1]):
for e1 in range(data.shape[2]):
for e2 in range(e1, data.shape[2]):
signal1 = data[trial,freq,e1,:]
signal2 = data[trial,freq,e2,:]
c = np.correlate(signal1, signal2, 'full')
c /= np.sqrt(np.dot(signal1,signal1) * np.dot(signal2,signal2)) # Normalize
max_xcorr = np.max(c) # Max cross correlation across lags
temp_xcorr[trial, freq, e1, e2] = max_xcorr
temp_xcorr[trial, freq, e2, e1] = max_xcorr
data = temp_xcorr
del temp_xcorr
# Save xcorr matrix
np.save(xcorr_file, data.astype('float32'))
# Show cross correlation matrix plots for single trial (MW)
fig, axarr = plt.subplots(3, 2, figsize=(9, 9))
fig.suptitle('Mind Wandering Trial', fontsize=16, y=1.03)
axarr[0,0].imshow(data[0,1,:,:], interpolation = 'none')
axarr[0,0].set_title('Delta')
axarr[0,0].get_xaxis().set_visible(False)
axarr[0,0].get_yaxis().set_visible(False)
axarr[0,1].imshow(data[0,2,:,:], interpolation = 'none')
axarr[0,1].set_title('Theta')
axarr[0,1].get_xaxis().set_visible(False)
axarr[0,1].get_yaxis().set_visible(False)
axarr[1,0].imshow(data[0,3,:,:], interpolation = 'none')
axarr[1,0].set_title('Alpha')
axarr[1,0].get_xaxis().set_visible(False)
axarr[1,0].get_yaxis().set_visible(False)
axarr[1,1].imshow(data[0,4,:,:], interpolation = 'none')
axarr[1,1].set_title('Beta')
axarr[1,1].get_xaxis().set_visible(False)
axarr[1,1].get_yaxis().set_visible(False)
axarr[2,0].imshow(data[0,0,:,:], interpolation = 'none')
axarr[2,0].set_title('Raw')
axarr[2,0].get_xaxis().set_visible(False)
axarr[2,0].get_yaxis().set_visible(False)
axarr[2,1].axis('off')
plt.tight_layout(w_pad = -20)
plt.show()
# Standardize data per trial
# Significantly improves gradient descent
data = (data - data.mean(axis=(2,3),keepdims=1)) / data.std(axis=(2,3),keepdims=1)
# Up/downsample the data to balance classes
data, data_labels = bootstrap(data, data_labels, "downsample")
# Create train, validation, test sets
rng = np.random.RandomState(5334) # Set random seed
indices = rng.permutation(data.shape[0])
split_train, split_val, split_test = .6, .2, .2
split_train = int(round(data.shape[0]*split_train))
split_val = split_train + int(round(data.shape[0]*split_val))
train_idx = indices[:split_train]
val_idx = indices[split_train:split_val]
test_idx = indices[split_val:]
train_data = data[train_idx,:]
train_labels = data_labels[train_idx]
val_data = data[val_idx,:]
val_labels = data_labels[val_idx]
test_data = data[test_idx,:]
test_labels = data_labels[test_idx]
def build_cnn(k_height=3, k_width=3, input_var=None):
# Input layer, as usual:
l_in = InputLayer(shape=(None, 5, 30, 30), input_var=input_var)
l_conv1 = Conv2DLayer(incoming = l_in, num_filters = 8,
filter_size = (k_height, k_width),
stride = 1, pad = 'same',
W = lasagne.init.Normal(std = 0.02),
nonlinearity = lasagne.nonlinearities.very_leaky_rectify)
l_pool1 = Pool2DLayer(incoming = l_conv1, pool_size = (2,2), stride = (2,2))
l_drop1 = lasagne.layers.dropout(l_pool1, p=.75)
l_fc = lasagne.layers.DenseLayer(
l_drop1,
num_units=50,
nonlinearity=lasagne.nonlinearities.rectify)
l_drop2 = lasagne.layers.dropout(l_fc, p=.75)
l_out = lasagne.layers.DenseLayer(
l_drop2,
num_units=2,
nonlinearity=lasagne.nonlinearities.softmax)
return l_out
# ############################# Batch iterator ###############################
# This is just a simple helper function iterating over training data in
# mini-batches of a particular size, optionally in random order. It assumes
# data is available as numpy arrays. For big datasets, you could load numpy
# arrays as memory-mapped files (np.load(..., mmap_mode='r')), or write your
# own custom data iteration function. For small datasets, you can also copy
# them to GPU at once for slightly improved performance. This would involve
# several changes in the main program, though, and is not demonstrated here.
# Notice that this function returns only mini-batches of size `batchsize`.
# If the size of the data is not a multiple of `batchsize`, it will not
# return the last (remaining) mini-batch.
def iterate_minibatches(inputs, targets, batchsize, shuffle=False):
assert len(inputs) == len(targets)
if shuffle:
indices = np.arange(len(inputs))
np.random.shuffle(indices)
# tqdm() can be removed if no visual progress bar is needed
for start_idx in tqdm(range(0, len(inputs) - batchsize + 1, batchsize)):
if shuffle:
excerpt = indices[start_idx:start_idx + batchsize]
else:
excerpt = slice(start_idx, start_idx + batchsize)
yield inputs[excerpt], targets[excerpt]
def main(model='cnn', batch_size=500, num_epochs=500, k_height=3, k_width=3):
# Prepare Theano variables for inputs and targets
input_var = T.tensor4('inputs')
target_var = T.ivector('targets')
network = build_cnn(k_height, k_width, input_var)
# Create a loss expression for training, i.e., a scalar objective we want
# to minimize (for our multi-class problem, it is the cross-entropy loss):
prediction = lasagne.layers.get_output(network)
loss = lasagne.objectives.categorical_crossentropy(prediction, target_var)
loss = loss.mean()
# We could add some weight decay as well here, see lasagne.regularization.
l2_reg = regularize_network_params(network, l2)
loss += l2_reg * 0.001
train_acc = T.mean(T.eq(T.argmax(prediction, axis=1), target_var),
dtype=theano.config.floatX)
# Create update expressions for training
params = lasagne.layers.get_all_params(network, trainable=True)
updates = lasagne.updates.nesterov_momentum(loss, params, learning_rate=0.01)
#updates = lasagne.updates.adam(loss, params, learning_rate=0.1)
# Create a loss expression for validation/testing. The crucial difference
# here is that we do a deterministic forward pass through the network,
# disabling dropout layers.
test_prediction = lasagne.layers.get_output(network, deterministic=True)
test_loss = lasagne.objectives.categorical_crossentropy(test_prediction,
target_var)
test_loss = test_loss.mean()
# As a bonus, also create an expression for the classification accuracy:
test_acc = T.mean(T.eq(T.argmax(test_prediction, axis=1), target_var),
dtype=theano.config.floatX)
# Compile a function performing a training step on a mini-batch (by giving
# the updates dictionary) and returning the corresponding training loss:
train_fn = theano.function([input_var, target_var], [loss, train_acc], updates=updates)
# Compile a second function computing the validation loss and accuracy:
val_fn = theano.function([input_var, target_var], [test_loss, test_acc])
training_hist = []
val_hist = []
print("Starting training...")
# We iterate over epochs:
for epoch in range(num_epochs):
# In each epoch, we do a full pass over the training data:
print("Training epoch {}...".format(epoch+1))
train_err = 0
train_acc = 0
train_batches = 0
start_time = time.time()
for batch in iterate_minibatches(train_data, train_labels, batch_size, shuffle=True):
inputs, targets = batch
err, acc = train_fn(inputs, targets)
train_err += err
train_acc += acc
train_batches += 1
if VERBOSE:
print("Epoch: {} | Mini-batch: {}/{} | Elapsed time: {:.2f}s".format(
epoch+1,
train_batches,
train_data.shape[0]/batch_size,
time.time()-start_time))
training_hist.append(train_err / train_batches)
# And a full pass over the validation data:
print("Validating epoch...")
val_err = 0
val_acc = 0
val_batches = 0
for batch in iterate_minibatches(val_data, val_labels, batch_size, shuffle=False):
inputs, targets = batch
err, acc = val_fn(inputs, targets)
val_err += err
val_acc += acc
val_batches += 1
val_hist.append(val_err / val_batches)
# Then we print the results for this epoch:
print("Epoch {} of {} took {:.3f}s".format(
epoch + 1, num_epochs, time.time() - start_time))
print(" training loss:\t\t{:.6f}".format(train_err / train_batches))
print(" training accuracy:\t\t{:.2f} %".format(
train_acc / train_batches * 100))
print(" validation loss:\t\t{:.6f}".format(val_err / val_batches))
print(" validation accuracy:\t\t{:.2f} %".format(
val_acc / val_batches * 100))
# After training, we compute and print the test predictions/error:
test_err = 0
test_acc = 0
test_batches = 0
for batch in iterate_minibatches(test_data, test_labels, batch_size, shuffle=False):
inputs, targets = batch
err, acc = val_fn(inputs, targets)
test_err += err
test_acc += acc
test_batches += 1
test_perc = (test_acc / test_batches) * 100
print("Final results:")
print(" test loss:\t\t\t{:.6f}".format(test_err / test_batches))
print(" test accuracy:\t\t{:.2f} %".format(test_perc))
# Plot learning
plt.plot(range(1, num_epochs+1), training_hist, label="Training")
plt.plot(range(1, num_epochs+1), val_hist, label="Validation")
plt.grid(True)
plt.title("Training Curve\nKernel size: ({},{}) - Test acc: {:.2f}%".format(k_height, k_width, test_perc))
plt.xlim(1, num_epochs+1)
plt.xlabel("Epoch #")
plt.ylabel("Loss")
plt.legend(loc='best')
plt.show()
# Optionally, you could now dump the network weights to a file like this:
# np.savez('model.npz', *lasagne.layers.get_all_param_values(network))
#
# And load them again later on like this:
# with np.load('model.npz') as f:
# param_values = [f['arr_%d' % i] for i in range(len(f.files))]
# lasagne.layers.set_all_param_values(network, param_values)
return test_perc
if GRID_SEARCH:
# Set filter sizes to search across (odd size only)
search_heights = range(1, 15, 2) # Across spatial domain (electrodes)
search_widths = range(1, 15, 2) # Across temporal domain (time samples)
# Preallocate accuracy grid
grid_accuracy = np.empty((len(search_heights), len(search_widths)))
num_kernels = grid_accuracy.size
cur_kernel = 0
for i, h in enumerate(search_heights):
for j, w in enumerate(search_widths):
# Train with current kernel size
cur_kernel += 1
print("***** Kernel {}/{} | Size: ({},{}) *****".format(cur_kernel, num_kernels, h, w))
cur_test_acc = main(batch_size=200, num_epochs=50, k_height=h, k_width=w)
grid_accuracy[i, j] = cur_test_acc
# Show accuracy heatmap
fig, ax = plt.subplots(figsize=(10, 10))
heatmap = ax.imshow(grid_accuracy, cmap = plt.cm.bone, interpolation = 'mitchell')
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.2)
cb = plt.colorbar(heatmap, orientation='vertical', cax=cax)
cb.ax.set_title('Test Acc (%)', {'fontsize': 10, 'horizontalalignment': 'left'})
ax.grid(True)
ax.set_xlabel('Kernel Width', weight='bold')
ax.set_ylabel('Kernel Height', weight='bold')
ax.xaxis.set_label_position('top')
ax.xaxis.tick_top()
ax.set_xticks(range(grid_accuracy.shape[1])) # X element position
ax.set_yticks(range(grid_accuracy.shape[0])) # Y element position
ax.set_xticklabels(search_widths) # Labels for X axis
ax.set_yticklabels(search_heights) # Labels for Y axis
plt.show()
# Get highest accuracy and associated kernel size:
best_idx = np.unravel_index(grid_accuracy.argmax(), grid_accuracy.shape)
print("Highest accuracy: {:.2f}%".format(np.max(grid_accuracy)))
print("Best kernel size: ({},{})".format(search_heights[best_idx[0]],
search_widths[best_idx[1]]))
# Highest search accuracy: 59.13%
# Best kernel size: (5,13)
# Train model using ideal kernel size over more epochs
cur_test_acc = main(batch_size=200, num_epochs=400,
k_height=search_heights[best_idx[0]],
k_width=search_widths[best_idx[1]])
# Final test accuracy: 66.50%
else:
# Use best filter size
cur_test_acc = main(batch_size=200, num_epochs=400, k_height=5, k_width=13)
| |
"""
Python library for iTOP API
github.com/jonatasbaldin/itopy
"""
import json
import requests
class MyException(Exception):
"""
Handle custom exceptions
"""
pass
class Api(object):
"""
To instanciate an itopy object.
No parameter needed.
"""
def __init__(self, search_keys=None):
"""
Init
:type search_keys: dict
:param search_keys: dict of objects and the associated key.
Prevents duplicated objects.
You can use "dontcheck" value to allow duplication
"""
if search_keys is not None:
self.obj_dict = search_keys
else:
self.obj_dict = {
'VLAN': 'vlan_tag',
'IPv4Address': 'ip',
'lnkConnectableCIToNetworkDevice': 'dontcheck',
'IPv4Range': 'range',
'UserRequest': 'dontcheck'
}
self.url = None
self.version = None
self.auth_user = None
self.auth_pwd = None
self.auth = 0
def connect(self, url, version, auth_user, auth_pwd):
"""
Connect to iTOP JSON webservice.
Parameters:
:param url: url to iTOPs rest.php page
:param version: API version
:param auth_user: user to authenticate
:param auth_pwd: user password
"""
self.url = url
self.version = version
self.auth_user = auth_user
self.auth_pwd = auth_pwd
self.auth = 1
# Construct a dictionary
data = {
'operation': 'core/check_credentials',
'user': self.auth_user,
'password': self.auth_pwd
}
# Converts dict to str (json object)
json_data = json.dumps(data)
# Multiple exceptions
schema_exceptions = (requests.exceptions.MissingSchema,
requests.exceptions.InvalidSchema)
# Tries web request
try:
req = requests.post(self.url, data={'version': self.version,
'auth_user': self.auth_user,
'auth_pwd': self.auth_pwd,
'json_data': json_data})
except schema_exceptions:
return 'The http:// is missing or invalid'
except requests.exceptions.ConnectionError:
return 'The connection to iTOP was refused'
if req.status_code != 200:
return 'Could not connect. HTTP code {}'.format(req.status_code)
# The return is 'bytes', convert to string
try:
return_code = json.loads(req.content.decode('utf-8'))['code']
except ValueError:
return 'Not a valid JSON, maybe the page is returning other data'
# Authenticate
if return_code == 0:
self.auth = 0
return self.auth
try:
# If not, return custom excpetion with iTOP connection error
self.auth = 1
# Raises custom exception
raise MyException(Api.connect_error(return_code))
except MyException as exception:
# Returns just custom exception message
return exception.args[0]
def auth(func):
"""
Decorator to authenticate the functions that must be authenticated
Parameters:
:param func: function to authenticate
"""
# gets the function and all its parameters
def inner(self, *args, **kwargs):
# verify if self.auth is 0 (auththenticated) or not
if self.auth == 0:
# if it ts, return the function with normal request
return func(self, *args, **kwargs)
# if not, returns that it is not authenticated
return Api.connect_error(self.auth)
# returns the inner function
return inner
@staticmethod
def connect_error(error):
"""
Return connection error, if any.
"""
error_dict = {
0: 'OK - No issue has been encountered',
1: """UNAUTHORIZED - Missing/wrong credentials or the user does
not have enough rights to perform the requested operation""",
2: "MISSING_VERSION - The parameter 'version' is missing",
3: "MISSING_JSON - The parameter 'json_data' is missing",
4: 'INVALID_JSON - The input structure is not valid JSON string',
5: "MISSING_AUTH_USER - The parameter 'auth_user' is missing",
6: "MISSING_AUTH_PWD - The parameter 'auth_pwd' is missing",
10: """UNSUPPORTED_VERSION - No operation is available for
the specified version""",
11: """UNKNOWN_OPERATION - The requested operation is not valid
for the specelified version""",
12: """UNSAFE - The requested operation cannot be performe because
it can cause data (integrity) loss""",
100: """INTERNAL_ERROR - The operation could not be performed,
see the message for troubleshooting""",
}
if error_dict.get(error):
return error_dict[error]
return 'UNKNOW_ERROR - Not specified by ITOP'
@auth
def req(self, data, obj_class):
"""
Gereral request to iTOP API.
Handles requests for all functions.
Parameters:
:param data: JSON structure data, in dict
:param ojb_class: iTOP's device class from datamodel
"""
json_data = json.dumps(data)
# json_data = jsonpickle.encode(data)
# Multiple exceptions
schema_exceptions = (requests.exceptions.MissingSchema,
requests.exceptions.InvalidSchema)
# Tries web request
try:
req = requests.post(self.url, data={'version': self.version,
'auth_user': self.auth_user,
'auth_pwd': self.auth_pwd,
'json_data': json_data})
except schema_exceptions:
return 'The http:// is missing or invalid'
except requests.exceptions.ConnectionError:
return 'The connection to iTOP was refused'
try:
json_return = json.loads(req.content.decode('utf-8'))
except ValueError:
return 'Not a valid JSON, maybe the page is returning other data'
# The return is 'bytes', convert to string
return_code = json_return['code']
# Default return_list
return_list = {
'code': json_return['code'],
'message': json_return['message'],
}
# if there's no error, returns +objects and +item_key
if return_code == 0:
# create a dict key for the items
# useful for Get
item_key = None
temp_dict = (json_return['objects'])
item_key = list()
if temp_dict is not None:
for key in json_return['objects']:
item_key.append(json_return['objects'][key]['key'])
# old comprehension..
# item_key.append(int([objects[p]['key'] for p in objects][0]))
# adds objects and item_key do dict
return_list['objects'] = json_return['objects']
return_list['item_key'] = item_key
return return_list
def check_class(self, obj_class):
"""
Used to return the right field to be searched when an object
is being added, to check if it exists.
Created because some objects no 'name' field, so one correct must
be specified.
The default return is name, which is default for a lot of objects,
if it should not be, it's gonna return an iTOP's error
Parameters:
:param obj_class: iTOP's device class from datamodel
"""
if obj_class in self.obj_dict:
return self.obj_dict[obj_class]
return 'name'
@auth
def get(self, obj_class, key, output_fields='*'):
"""
Handles the core/get operation in iTOP.
Parameters:
:param ojb_class: iTOP's device class from datamodel
:param key: search filter in iTOP's datamodel
:param output_fields: fields to get from iTOP's response, defaults is name
"""
data = {
'operation': 'core/get',
'comment': 'Get' + obj_class,
'class': obj_class,
'key': key,
'output_fields': output_fields
}
request = self.req(data, obj_class)
return request
@auth
def delete(self, obj_class, simulate=False, key=None, **kwargs):
"""
Handles the core/delete operation in iTOP.
Parameters:
:param ojb_class: iTOP's device class from datamodel
:param simulate: False by default
:param key: search key; can be OQL filter or object id. Warning : will override any kwargs
:param **kwargs: any field from the datamodel to identify the object
"""
data = {
'operation': 'core/delete',
'comment': self.auth_user + ' (api)',
'simulate': simulate,
'class': obj_class,
'key': {
}
}
for k, value in kwargs.items():
if value:
data['key'][k] = value
if not value:
return 'Parameter not valid!'
if key is not None:
data['key'] = key
request = self.req(data, obj_class)
return request
@auth
def create(self, obj_class, output_fields='*', **kwargs):
"""
Handles the core/create operation in iTOP.
Parameters:
:param obj_class: iTOP's device class from datamodel
:param output_fields: fields to get from iTOP's response
:param **kwargs: any field to add in the object from the datamodel, note that
some fields, like brand_name is not added without its id, brand_id,
it is recommended to use just brand_id, in that case
:return dict
"""
# verifies if object exists
# filter to get the object
# unless dontcheck, those objects may have duplicates
obj_field = self.check_class(obj_class)
if obj_field == 'dontcheck':
obj = dict()
obj['message'] = 'Found: 0'
obj['code'] = 0
else:
get_filter = "SELECT {} WHERE {} = '{}'".format(obj_class, obj_field, kwargs[obj_field])
# actual request
obj = self.get(obj_class, get_filter)
# if found 0 objects, and the return code is ok
if obj['message'] == 'Found: 0' and obj['code'] == 0:
data = {
'operation': 'core/create',
'comment': self.auth_user + ' (api)',
'class': obj_class,
'output_fields': output_fields,
'fields': {
}
}
# when creating DocumentFile, file parameter is specified
# it's a reserved word, so in the request we use _file
# and translate here to a key 'file'
if '_file' in kwargs:
for item in kwargs['_file']:
kwargs['file'] = item
del kwargs['_file']
# do not allow empty values in parameters
for key, value in kwargs.items():
if value:
data['fields'][key] = value
if not value:
return 'Parameter not valid'
request = self.req(data, obj_class)
return request
# if not 'Found: 0', but found something, obj exists
elif 'Found' in obj['message']:
return {
'message': 'Object exists',
'code': 0
}
else:
# if found is not present in string, probably error
return obj
@auth
def update(self, obj_class, key, key_value, output_fields='*', **kwargs):
"""
Handles the core/update operation in iTOP.
TODO: Until now just handles objects that have 'name' field
Parameters:
:param obj_class: iTOP's device class from datamodel
:param output_fields: fields to get from iTOP's response
:param key: field to identify the the unique object
:param key_value: value to the above field
:param **kwargs: any field to update the object from the datamodel, note that
some fields, like brand_name is not added without its id, brand_id,
it is recommended to use just brand_id, in that case
"""
data = {
'operation': 'core/update',
'comment': self.auth_user + ' (api)',
'class': obj_class,
'output_fields': output_fields,
'fields': {
},
'key': {
key: key_value
}
}
if key == 'key':
data['key'] = key_value
# do not allow empty values in parameters
for kkey, kvalue in kwargs.items():
if kvalue:
data['fields'][kkey] = kvalue
if not kvalue:
return 'Parameter not valid'
request = self.req(data, obj_class)
return request
@auth
def apply_stimulus(self, obj_class, key, key_value, stimulus, output_fields='*', **kwargs):
"""
Handles the core/apply_stimulus operation in iTOP.
Parameters:
:param obj_class: iTOP's device class from datamodel
:param output_fields: fields to get from iTOP's response
:param key: field to identify the the unique object
:param key_value: value to the above field
:param stimulus: key of the stimulus
:param **kwargs: any field needed in stimulus
"""
data = {
'operation': 'core/apply_stimulus',
'comment': self.auth_user + ' (api)',
'class': obj_class,
'stimulus': stimulus,
'output_fields': output_fields,
'fields': {
},
'key': {
key: key_value
}
}
if key == 'key':
data['key'] = key_value
# do not allow empty values in parameters
for kkey, kvalue in kwargs.items():
if kvalue:
data['fields'][kkey] = kvalue
if not kvalue:
return 'Parameter not valid'
request = self.req(data, obj_class)
return request
| |
from threading import Thread
from time import sleep, time
import numpy
from couchbase.bucket import Bucket
from couchbase.n1ql import N1QLQuery
from decorator import decorator
from cbagent.collectors import Latency
from cbagent.collectors.libstats.pool import Pool
from logger import logger
from perfrunner.helpers.misc import uhex
from spring.docgen import Document, Key
@decorator
def timeit(method, *args, **kargs):
t0 = time()
method(*args, **kargs)
t1 = time()
return t0, t1
class ObserveIndexLatency(Latency):
COLLECTOR = "observe"
METRICS = "latency_observe",
NUM_THREADS = 10
MAX_POLLING_INTERVAL = 1
INITIAL_REQUEST_INTERVAL = 0.01
MAX_REQUEST_INTERVAL = 2
def __init__(self, settings):
super().__init__(settings)
self.pools = self.init_pool(settings)
def init_pool(self, settings):
pools = []
for bucket in self.get_buckets():
pool = Pool(
bucket=bucket,
host=settings.master_node,
username=bucket,
password=settings.bucket_password,
quiet=True,
)
pools.append((bucket, pool))
return pools
@timeit
def _wait_until_indexed(self, client, key):
rows = None
while not rows:
rows = tuple(client.query("A", "id_by_city", key=key))
def _create_doc(self, pool):
client = pool.get_client()
key = uhex()
client.set(key, {"city": key})
return client, key
def _post_wait_operations(self, end_time, start_time, key, client, pool):
latency = (end_time - start_time) * 1000 # s -> ms
sleep_time = max(0, self.MAX_POLLING_INTERVAL - (end_time - start_time))
client.delete(key)
pool.release_client(client)
return {"latency_observe": latency}, sleep_time
def _measure_lags(self, pool):
client, key = self._create_doc(pool)
t0, t1 = self._wait_until_indexed(client, key)
return self._post_wait_operations(end_time=t1, start_time=t0, key=key,
client=client, pool=pool)
def sample(self):
while True:
try:
for bucket, pool in self.pools:
stats, sleep_time = self._measure_lags(pool)
self.store.append(stats,
cluster=self.cluster,
bucket=bucket,
collector=self.COLLECTOR)
sleep(sleep_time)
except Exception as e:
logger.warn(e)
def collect(self):
threads = [Thread(target=self.sample) for _ in range(self.NUM_THREADS)]
for t in threads:
t.start()
for t in threads:
t.join()
class ObserveSecondaryIndexLatency(ObserveIndexLatency):
@timeit
def _wait_until_secondary_indexed(self, key, cb, query):
row = None
query.set_option("$c", key)
while not row:
row = cb.n1ql_query(query).get_single_result()
@staticmethod
def create_alt_mail_doc(pool):
client = pool.get_client()
key = uhex()
client.set(key, {"alt_email": key})
return client, key
def _measure_lags(self, pool, cb=None, query=None):
client, key = self.create_alt_mail_doc(pool)
t0, t1 = self._wait_until_secondary_indexed(key, cb, query)
return self._post_wait_operations(end_time=t1, start_time=t0, key=key,
client=client, pool=pool)
def sample(self):
connection_string = 'couchbase://{}/{}?password={}'.format(
self.master_node, self.buckets[0], self.auth[1])
cb = Bucket(connection_string)
query = N1QLQuery("select alt_email from `bucket-1` where alt_email=$c", c="abc")
query.adhoc = False
while True:
try:
for bucket, pool in self.pools:
stats, sleep_time = self._measure_lags(pool, cb=cb, query=query)
self.store.append(stats,
cluster=self.cluster,
bucket=bucket,
collector=self.COLLECTOR)
sleep(sleep_time)
except Exception as e:
logger.warn(e)
class DurabilityLatency(ObserveIndexLatency, Latency):
COLLECTOR = "durability"
METRICS = "latency_replicate_to", "latency_persist_to"
DURABILITY_TIMEOUT = 120
def __init__(self, settings, workload):
super().__init__(settings)
self.new_docs = Document(workload.size)
self.pools = self.init_pool(settings)
@staticmethod
def gen_key() -> Key:
return Key(number=numpy.random.random_integers(0, 10 ** 9),
prefix='endure',
fmtr='hex')
def endure(self, pool, metric):
client = pool.get_client()
key = self.gen_key()
doc = self.new_docs.next(key)
t0 = time()
client.upsert(key.string, doc)
if metric == "latency_persist_to":
client.endure(key.string, persist_to=1, replicate_to=0, interval=0.010,
timeout=120)
else:
client.endure(key.string, persist_to=0, replicate_to=1, interval=0.001)
latency = 1000 * (time() - t0) # Latency in ms
sleep_time = max(0, self.MAX_POLLING_INTERVAL - latency)
client.delete(key.string)
pool.release_client(client)
return {metric: latency}, sleep_time
def sample(self):
while True:
for bucket, pool in self.pools:
for metric in self.METRICS:
try:
stats, sleep_time = self.endure(pool, metric)
self.store.append(stats,
cluster=self.cluster,
bucket=bucket,
collector=self.COLLECTOR)
sleep(sleep_time)
except Exception as e:
logger.warn(e)
def collect(self):
ObserveIndexLatency.collect(self)
| |
import copy
import time
import warnings
from collections import deque
from contextlib import contextmanager
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db import DEFAULT_DB_ALIAS
from django.db.backends import utils
from django.db.backends.signals import connection_created
from django.db.transaction import TransactionManagementError
from django.db.utils import DatabaseError, DatabaseErrorWrapper
from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.six.moves import _thread as thread
try:
import pytz
except ImportError:
pytz = None
NO_DB_ALIAS = '__no_db__'
class BaseDatabaseWrapper(object):
"""
Represents a database connection.
"""
# Mapping of Field objects to their column types.
data_types = {}
# Mapping of Field objects to their SQL suffix such as AUTOINCREMENT.
data_types_suffix = {}
# Mapping of Field objects to their SQL for CHECK constraints.
data_type_check_constraints = {}
ops = None
vendor = 'unknown'
SchemaEditorClass = None
queries_limit = 9000
def __init__(self, settings_dict, alias=DEFAULT_DB_ALIAS,
allow_thread_sharing=False):
# Connection related attributes.
# The underlying database connection.
self.connection = None
# `settings_dict` should be a dictionary containing keys such as
# NAME, USER, etc. It's called `settings_dict` instead of `settings`
# to disambiguate it from Django settings modules.
self.settings_dict = settings_dict
self.alias = alias
# Query logging in debug mode or when explicitly enabled.
self.queries_log = deque(maxlen=self.queries_limit)
self.force_debug_cursor = False
# Transaction related attributes.
# Tracks if the connection is in autocommit mode. Per PEP 249, by
# default, it isn't.
self.autocommit = False
# Tracks if the connection is in a transaction managed by 'atomic'.
self.in_atomic_block = False
# Increment to generate unique savepoint ids.
self.savepoint_state = 0
# List of savepoints created by 'atomic'.
self.savepoint_ids = []
# Tracks if the outermost 'atomic' block should commit on exit,
# ie. if autocommit was active on entry.
self.commit_on_exit = True
# Tracks if the transaction should be rolled back to the next
# available savepoint because of an exception in an inner block.
self.needs_rollback = False
# Connection termination related attributes.
self.close_at = None
self.closed_in_transaction = False
self.errors_occurred = False
# Thread-safety related attributes.
self.allow_thread_sharing = allow_thread_sharing
self._thread_ident = thread.get_ident()
# A list of no-argument functions to run when the transaction commits.
# Each entry is an (sids, func) tuple, where sids is a set of the
# active savepoint IDs when this function was registered.
self.run_on_commit = []
# Should we run the on-commit hooks the next time set_autocommit(True)
# is called?
self.run_commit_hooks_on_set_autocommit_on = False
@cached_property
def timezone(self):
"""
Time zone for datetimes stored as naive values in the database.
Returns a tzinfo object or None.
This is only needed when time zone support is enabled and the database
doesn't support time zones. (When the database supports time zones,
the adapter handles aware datetimes so Django doesn't need to.)
"""
if not settings.USE_TZ:
return None
elif self.features.supports_timezones:
return None
elif self.settings_dict['TIME_ZONE'] is None:
return timezone.utc
else:
# Only this branch requires pytz.
return pytz.timezone(self.settings_dict['TIME_ZONE'])
@cached_property
def timezone_name(self):
"""
Name of the time zone of the database connection.
"""
if not settings.USE_TZ:
return settings.TIME_ZONE
elif self.settings_dict['TIME_ZONE'] is None:
return 'UTC'
else:
return self.settings_dict['TIME_ZONE']
@property
def queries_logged(self):
return self.force_debug_cursor or settings.DEBUG
@property
def queries(self):
if len(self.queries_log) == self.queries_log.maxlen:
warnings.warn(
"Limit for query logging exceeded, only the last {} queries "
"will be returned.".format(self.queries_log.maxlen))
return list(self.queries_log)
# ##### Backend-specific methods for creating connections and cursors #####
def get_connection_params(self):
"""Returns a dict of parameters suitable for get_new_connection."""
raise NotImplementedError('subclasses of BaseDatabaseWrapper may require a get_connection_params() method')
def get_new_connection(self, conn_params):
"""Opens a connection to the database."""
raise NotImplementedError('subclasses of BaseDatabaseWrapper may require a get_new_connection() method')
def init_connection_state(self):
"""Initializes the database connection settings."""
raise NotImplementedError('subclasses of BaseDatabaseWrapper may require an init_connection_state() method')
def create_cursor(self):
"""Creates a cursor. Assumes that a connection is established."""
raise NotImplementedError('subclasses of BaseDatabaseWrapper may require a create_cursor() method')
# ##### Backend-specific methods for creating connections #####
def connect(self):
"""Connects to the database. Assumes that the connection is closed."""
# Check for invalid configurations.
self.check_settings()
# In case the previous connection was closed while in an atomic block
self.in_atomic_block = False
self.savepoint_ids = []
self.needs_rollback = False
# Reset parameters defining when to close the connection
max_age = self.settings_dict['CONN_MAX_AGE']
self.close_at = None if max_age is None else time.time() + max_age
self.closed_in_transaction = False
self.errors_occurred = False
# Establish the connection
conn_params = self.get_connection_params()
self.connection = self.get_new_connection(conn_params)
self.set_autocommit(self.settings_dict['AUTOCOMMIT'])
self.init_connection_state()
connection_created.send(sender=self.__class__, connection=self)
self.run_on_commit = []
def check_settings(self):
if self.settings_dict['TIME_ZONE'] is not None:
if not settings.USE_TZ:
raise ImproperlyConfigured(
"Connection '%s' cannot set TIME_ZONE because USE_TZ is "
"False." % self.alias)
elif self.features.supports_timezones:
raise ImproperlyConfigured(
"Connection '%s' cannot set TIME_ZONE because its engine "
"handles time zones conversions natively." % self.alias)
elif pytz is None:
raise ImproperlyConfigured(
"Connection '%s' cannot set TIME_ZONE because pytz isn't "
"installed." % self.alias)
def ensure_connection(self):
"""
Guarantees that a connection to the database is established.
"""
if self.connection is None:
with self.wrap_database_errors:
self.connect()
# ##### Backend-specific wrappers for PEP-249 connection methods #####
def _cursor(self):
self.ensure_connection()
with self.wrap_database_errors:
return self.create_cursor()
def _commit(self):
if self.connection is not None:
with self.wrap_database_errors:
return self.connection.commit()
def _rollback(self):
if self.connection is not None:
with self.wrap_database_errors:
return self.connection.rollback()
def _close(self):
if self.connection is not None:
with self.wrap_database_errors:
return self.connection.close()
# ##### Generic wrappers for PEP-249 connection methods #####
def cursor(self):
"""
Creates a cursor, opening a connection if necessary.
"""
self.validate_thread_sharing()
if self.queries_logged:
cursor = self.make_debug_cursor(self._cursor())
else:
cursor = self.make_cursor(self._cursor())
return cursor
def commit(self):
"""
Commits a transaction and resets the dirty flag.
"""
self.validate_thread_sharing()
self.validate_no_atomic_block()
self._commit()
# A successful commit means that the database connection works.
self.errors_occurred = False
self.run_commit_hooks_on_set_autocommit_on = True
def rollback(self):
"""
Rolls back a transaction and resets the dirty flag.
"""
self.validate_thread_sharing()
self.validate_no_atomic_block()
self._rollback()
# A successful rollback means that the database connection works.
self.errors_occurred = False
self.run_on_commit = []
def close(self):
"""
Closes the connection to the database.
"""
self.validate_thread_sharing()
self.run_on_commit = []
# Don't call validate_no_atomic_block() to avoid making it difficult
# to get rid of a connection in an invalid state. The next connect()
# will reset the transaction state anyway.
if self.closed_in_transaction or self.connection is None:
return
try:
self._close()
finally:
if self.in_atomic_block:
self.closed_in_transaction = True
self.needs_rollback = True
else:
self.connection = None
# ##### Backend-specific savepoint management methods #####
def _savepoint(self, sid):
with self.cursor() as cursor:
cursor.execute(self.ops.savepoint_create_sql(sid))
def _savepoint_rollback(self, sid):
with self.cursor() as cursor:
cursor.execute(self.ops.savepoint_rollback_sql(sid))
def _savepoint_commit(self, sid):
with self.cursor() as cursor:
cursor.execute(self.ops.savepoint_commit_sql(sid))
def _savepoint_allowed(self):
# Savepoints cannot be created outside a transaction
return self.features.uses_savepoints and not self.get_autocommit()
# ##### Generic savepoint management methods #####
def savepoint(self):
"""
Creates a savepoint inside the current transaction. Returns an
identifier for the savepoint that will be used for the subsequent
rollback or commit. Does nothing if savepoints are not supported.
"""
if not self._savepoint_allowed():
return
thread_ident = thread.get_ident()
tid = str(thread_ident).replace('-', '')
self.savepoint_state += 1
sid = "s%s_x%d" % (tid, self.savepoint_state)
self.validate_thread_sharing()
self._savepoint(sid)
return sid
def savepoint_rollback(self, sid):
"""
Rolls back to a savepoint. Does nothing if savepoints are not supported.
"""
if not self._savepoint_allowed():
return
self.validate_thread_sharing()
self._savepoint_rollback(sid)
# Remove any callbacks registered while this savepoint was active.
self.run_on_commit = [
(sids, func) for (sids, func) in self.run_on_commit if sid not in sids
]
def savepoint_commit(self, sid):
"""
Releases a savepoint. Does nothing if savepoints are not supported.
"""
if not self._savepoint_allowed():
return
self.validate_thread_sharing()
self._savepoint_commit(sid)
def clean_savepoints(self):
"""
Resets the counter used to generate unique savepoint ids in this thread.
"""
self.savepoint_state = 0
# ##### Backend-specific transaction management methods #####
def _set_autocommit(self, autocommit):
"""
Backend-specific implementation to enable or disable autocommit.
"""
raise NotImplementedError('subclasses of BaseDatabaseWrapper may require a _set_autocommit() method')
# ##### Generic transaction management methods #####
def get_autocommit(self):
"""
Check the autocommit state.
"""
self.ensure_connection()
return self.autocommit
def set_autocommit(self, autocommit, force_begin_transaction_with_broken_autocommit=False):
"""
Enable or disable autocommit.
The usual way to start a transaction is to turn autocommit off.
SQLite does not properly start a transaction when disabling
autocommit. To avoid this buggy behavior and to actually enter a new
transaction, an explcit BEGIN is required. Using
force_begin_transaction_with_broken_autocommit=True will issue an
explicit BEGIN with SQLite. This option will be ignored for other
backends.
"""
self.validate_no_atomic_block()
self.ensure_connection()
start_transaction_under_autocommit = (
force_begin_transaction_with_broken_autocommit and not autocommit and
self.features.autocommits_when_autocommit_is_off
)
if start_transaction_under_autocommit:
self._start_transaction_under_autocommit()
else:
self._set_autocommit(autocommit)
self.autocommit = autocommit
if autocommit and self.run_commit_hooks_on_set_autocommit_on:
self.run_and_clear_commit_hooks()
self.run_commit_hooks_on_set_autocommit_on = False
def get_rollback(self):
"""
Get the "needs rollback" flag -- for *advanced use* only.
"""
if not self.in_atomic_block:
raise TransactionManagementError(
"The rollback flag doesn't work outside of an 'atomic' block.")
return self.needs_rollback
def set_rollback(self, rollback):
"""
Set or unset the "needs rollback" flag -- for *advanced use* only.
"""
if not self.in_atomic_block:
raise TransactionManagementError(
"The rollback flag doesn't work outside of an 'atomic' block.")
self.needs_rollback = rollback
def validate_no_atomic_block(self):
"""
Raise an error if an atomic block is active.
"""
if self.in_atomic_block:
raise TransactionManagementError(
"This is forbidden when an 'atomic' block is active.")
def validate_no_broken_transaction(self):
if self.needs_rollback:
raise TransactionManagementError(
"An error occurred in the current transaction. You can't "
"execute queries until the end of the 'atomic' block.")
# ##### Foreign key constraints checks handling #####
@contextmanager
def constraint_checks_disabled(self):
"""
Context manager that disables foreign key constraint checking.
"""
disabled = self.disable_constraint_checking()
try:
yield
finally:
if disabled:
self.enable_constraint_checking()
def disable_constraint_checking(self):
"""
Backends can implement as needed to temporarily disable foreign key
constraint checking. Should return True if the constraints were
disabled and will need to be reenabled.
"""
return False
def enable_constraint_checking(self):
"""
Backends can implement as needed to re-enable foreign key constraint
checking.
"""
pass
def check_constraints(self, table_names=None):
"""
Backends can override this method if they can apply constraint
checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE"). Should raise an
IntegrityError if any invalid foreign key references are encountered.
"""
pass
# ##### Connection termination handling #####
def is_usable(self):
"""
Tests if the database connection is usable.
This function may assume that self.connection is not None.
Actual implementations should take care not to raise exceptions
as that may prevent Django from recycling unusable connections.
"""
raise NotImplementedError(
"subclasses of BaseDatabaseWrapper may require an is_usable() method")
def close_if_unusable_or_obsolete(self):
"""
Closes the current connection if unrecoverable errors have occurred,
or if it outlived its maximum age.
"""
if self.connection is not None:
# If the application didn't restore the original autocommit setting,
# don't take chances, drop the connection.
if self.get_autocommit() != self.settings_dict['AUTOCOMMIT']:
self.close()
return
# If an exception other than DataError or IntegrityError occurred
# since the last commit / rollback, check if the connection works.
if self.errors_occurred:
if self.is_usable():
self.errors_occurred = False
else:
self.close()
return
if self.close_at is not None and time.time() >= self.close_at:
self.close()
return
# ##### Thread safety handling #####
def validate_thread_sharing(self):
"""
Validates that the connection isn't accessed by another thread than the
one which originally created it, unless the connection was explicitly
authorized to be shared between threads (via the `allow_thread_sharing`
property). Raises an exception if the validation fails.
"""
if not (self.allow_thread_sharing or self._thread_ident == thread.get_ident()):
raise DatabaseError(
"DatabaseWrapper objects created in a "
"thread can only be used in that same thread. The object "
"with alias '%s' was created in thread id %s and this is "
"thread id %s."
% (self.alias, self._thread_ident, thread.get_ident())
)
# ##### Miscellaneous #####
def prepare_database(self):
"""
Hook to do any database check or preparation, generally called before
migrating a project or an app.
"""
pass
@cached_property
def wrap_database_errors(self):
"""
Context manager and decorator that re-throws backend-specific database
exceptions using Django's common wrappers.
"""
return DatabaseErrorWrapper(self)
def make_debug_cursor(self, cursor):
"""
Creates a cursor that logs all queries in self.queries_log.
"""
return utils.CursorDebugWrapper(cursor, self)
def make_cursor(self, cursor):
"""
Creates a cursor without debug logging.
"""
return utils.CursorWrapper(cursor, self)
@contextmanager
def temporary_connection(self):
"""
Context manager that ensures that a connection is established, and
if it opened one, closes it to avoid leaving a dangling connection.
This is useful for operations outside of the request-response cycle.
Provides a cursor: with self.temporary_connection() as cursor: ...
"""
must_close = self.connection is None
cursor = self.cursor()
try:
yield cursor
finally:
cursor.close()
if must_close:
self.close()
@property
def _nodb_connection(self):
"""
Return an alternative connection to be used when there is no need to access
the main database, specifically for test db creation/deletion.
This also prevents the production database from being exposed to
potential child threads while (or after) the test database is destroyed.
Refs #10868, #17786, #16969.
"""
settings_dict = self.settings_dict.copy()
settings_dict['NAME'] = None
nodb_connection = self.__class__(
settings_dict,
alias=NO_DB_ALIAS,
allow_thread_sharing=False)
return nodb_connection
def _start_transaction_under_autocommit(self):
"""
Only required when autocommits_when_autocommit_is_off = True.
"""
raise NotImplementedError(
'subclasses of BaseDatabaseWrapper may require a '
'_start_transaction_under_autocommit() method'
)
def schema_editor(self, *args, **kwargs):
"""
Returns a new instance of this backend's SchemaEditor.
"""
if self.SchemaEditorClass is None:
raise NotImplementedError(
'The SchemaEditorClass attribute of this database wrapper is still None')
return self.SchemaEditorClass(self, *args, **kwargs)
def on_commit(self, func):
if self.in_atomic_block:
# Transaction in progress; save for execution on commit.
self.run_on_commit.append((set(self.savepoint_ids), func))
elif not self.get_autocommit():
raise TransactionManagementError('on_commit() cannot be used in manual transaction management')
else:
# No transaction in progress and in autocommit mode; execute
# immediately.
func()
def run_and_clear_commit_hooks(self):
self.validate_no_atomic_block()
try:
while self.run_on_commit:
sids, func = self.run_on_commit.pop(0)
func()
finally:
self.run_on_commit = []
def copy(self, alias=None, allow_thread_sharing=None):
"""
Return a copy of this connection.
For tests that require two connections to the same database.
"""
settings_dict = copy.deepcopy(self.settings_dict)
if alias is None:
alias = self.alias
if allow_thread_sharing is None:
allow_thread_sharing = self.allow_thread_sharing
return type(self)(settings_dict, alias, allow_thread_sharing)
| |
# Copyright (c) 2009 StudioNow, Inc <patrick@studionow.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
The ``pybrightcove.playlist`` module supports all Brightcove functions dealing
with playlist objects.
"""
import pybrightcove
from pybrightcove.enums import DEFAULT_SORT_BY, DEFAULT_SORT_ORDER
VALID_PLAYLIST_TYPES = (pybrightcove.enums.PlaylistTypeEnum.EXPLICIT,
pybrightcove.enums.PlaylistTypeEnum.OLDEST_TO_NEWEST,
pybrightcove.enums.PlaylistTypeEnum.NEWEST_TO_OLDEST,
pybrightcove.enums.PlaylistTypeEnum.ALPHABETICAL,
pybrightcove.enums.PlaylistTypeEnum.PLAYS_TOTAL,
pybrightcove.enums.PlaylistTypeEnum.PLAYS_TRAILING_WEEK)
class Playlist(object):
"""
The Playlist object is a collection of Videos.
"""
# pylint: disable=C0103,R0913,R0902
# redefine type,id builtins - refactor later
# pylint: disable=W0622
def __init__(self, name=None, type=None, id=None, reference_id=None,
data=None, _connection=None):
self.id = None
self.reference_id = None
self.account_id = None
self.name = None
self.short_description = None
self.thumbnail_url = None
self.videos = []
self.video_ids = []
self.type = None
self.raw_data = None
self.connection = _connection
if not self.connection:
self.connection = pybrightcove.connection.APIConnection()
if name and type in VALID_PLAYLIST_TYPES:
self.name = name
self.type = type
elif id or reference_id:
self.id = id
self.reference_id = reference_id
self._find_playlist()
elif data:
self._load(data)
else:
msg = "Invalid parameters for Playlist."
raise pybrightcove.exceptions.PyBrightcoveError(msg)
def __setattr__(self, name, value):
msg = None
if value:
if name == 'name' and len(value) > 60:
# val = value[:60] ## Is this better?
msg = "Playlist.name must be 60 characters or less."
if name == 'reference_id' and len(value) > 150:
# val = value[:150]
msg = "Playlist.reference_id must be 150 characters or less."
if name == 'short_description' and len(value) > 250:
# val = value[:250]
msg = "Playlist.short_description must be 250 chars or less."
if name == 'type' and value not in VALID_PLAYLIST_TYPES:
msg = "Playlist.type must be a valid PlaylistTypeEnum"
if msg:
raise pybrightcove.exceptions.PyBrightcoveError(msg)
return super(Playlist, self).__setattr__(name, value)
def _find_playlist(self):
"""
Internal method to populate the object given the ``id`` or
``reference_id`` that has been set in the constructor.
"""
data = None
if self.id:
data = self.connection.get_item(
'find_playlist_by_id', playlist_id=self.id)
elif self.reference_id:
data = self.connection.get_item(
'find_playlist_by_reference_id',
reference_id=self.reference_id)
if data:
self._load(data)
def _to_dict(self):
"""
Internal method that serializes object into a dictionary.
"""
data = {
'name': self.name,
'referenceId': self.reference_id,
'shortDescription': self.short_description,
'playlistType': self.type,
'id': self.id}
if self.videos:
for video in self.videos:
if video.id not in self.video_ids:
self.video_ids.append(video.id)
if self.video_ids:
data['videoIds'] = self.video_ids
[data.pop(key) for key in data.keys() if data[key] == None]
return data
def _load(self, data):
"""
Internal method that deserializes a ``pybrightcove.playlist.Playlist``
object.
"""
self.raw_data = data
self.id = data['id']
self.reference_id = data['referenceId']
self.name = data['name']
self.short_description = data['shortDescription']
self.thumbnail_url = data['thumbnailURL']
self.videos = []
self.video_ids = data['videoIds']
self.type = data['playlistType']
for video in data.get('videos', []):
self.videos.append(pybrightcove.video.Video(
data=video, _connection=self.connection))
def save(self):
"""
Create or update a playlist.
"""
d = self._to_dict()
if len(d.get('videoIds', [])) > 0:
if not self.id:
self.id = self.connection.post('create_playlist', playlist=d)
else:
data = self.connection.post('update_playlist', playlist=d)
if data:
self._load(data)
def delete(self, cascade=False):
"""
Deletes this playlist.
"""
if self.id:
self.connection.post('delete_playlist', playlist_id=self.id,
cascade=cascade)
self.id = None
@staticmethod
def find_all(connection=None, page_size=100, page_number=0,
sort_by=DEFAULT_SORT_BY, sort_order=DEFAULT_SORT_ORDER):
"""
List all playlists.
"""
return pybrightcove.connection.ItemResultSet("find_all_playlists",
Playlist, connection, page_size, page_number, sort_by, sort_order)
@staticmethod
def find_by_ids(ids, connection=None, page_size=100, page_number=0,
sort_by=DEFAULT_SORT_BY, sort_order=DEFAULT_SORT_ORDER):
"""
List playlists by specific IDs.
"""
ids = ','.join([str(i) for i in ids])
return pybrightcove.connection.ItemResultSet('find_playlists_by_ids',
Playlist, connection, page_size, page_number, sort_by, sort_order,
playlist_ids=ids)
@staticmethod
def find_by_reference_ids(reference_ids, connection=None, page_size=100,
page_number=0, sort_by=DEFAULT_SORT_BY, sort_order=DEFAULT_SORT_ORDER):
"""
List playlists by specific reference_ids.
"""
reference_ids = ','.join([str(i) for i in reference_ids])
return pybrightcove.connection.ItemResultSet(
"find_playlists_by_reference_ids", Playlist, connection, page_size,
page_number, sort_by, sort_order, reference_ids=reference_ids)
@staticmethod
def find_for_player_id(player_id, connection=None, page_size=100,
page_number=0, sort_by=DEFAULT_SORT_BY, sort_order=DEFAULT_SORT_ORDER):
"""
List playlists for a for given player id.
"""
return pybrightcove.connection.ItemResultSet(
"find_playlists_for_player_id", Playlist, connection, page_size,
page_number, sort_by, sort_order, player_id=player_id)
| |
""" Non-negative matrix factorization
"""
# Author: Vlad Niculae
# Lars Buitinck <L.J.Buitinck@uva.nl>
# Mathieu Blondel <mathieu@mblondel.org>
# Tom Dupre la Tour
# Author: Chih-Jen Lin, National Taiwan University (original projected gradient
# NMF implementation)
# Author: Anthony Di Franco (Projected gradient, Python and NumPy port)
# License: BSD 3 clause
from __future__ import division
from math import sqrt
import warnings
import numbers
import numpy as np
import scipy.sparse as sp
from ..externals import six
from ..base import BaseEstimator, TransformerMixin
from ..utils import check_random_state, check_array
from ..utils.extmath import randomized_svd, safe_sparse_dot, squared_norm
from ..utils.extmath import fast_dot
from ..utils.validation import check_is_fitted, check_non_negative
from ..utils import deprecated
from ..utils import ConvergenceWarning
from .cdnmf_fast import _update_cdnmf_fast
def safe_vstack(Xs):
if any(sp.issparse(X) for X in Xs):
return sp.vstack(Xs)
else:
return np.vstack(Xs)
def norm(x):
"""Dot product-based Euclidean norm implementation
See: http://fseoane.net/blog/2011/computing-the-vector-norm/
"""
return sqrt(squared_norm(x))
def trace_dot(X, Y):
"""Trace of np.dot(X, Y.T)."""
return np.dot(X.ravel(), Y.ravel())
def _sparseness(x):
"""Hoyer's measure of sparsity for a vector"""
sqrt_n = np.sqrt(len(x))
return (sqrt_n - np.linalg.norm(x, 1) / norm(x)) / (sqrt_n - 1)
def _check_init(A, shape, whom):
A = check_array(A)
if np.shape(A) != shape:
raise ValueError('Array with wrong shape passed to %s. Expected %s, '
'but got %s ' % (whom, shape, np.shape(A)))
check_non_negative(A, whom)
if np.max(A) == 0:
raise ValueError('Array passed to %s is full of zeros.' % whom)
def _safe_compute_error(X, W, H):
"""Frobenius norm between X and WH, safe for sparse array"""
if not sp.issparse(X):
error = norm(X - np.dot(W, H))
else:
norm_X = np.dot(X.data, X.data)
norm_WH = trace_dot(np.dot(np.dot(W.T, W), H), H)
cross_prod = trace_dot((X * H.T), W)
error = sqrt(norm_X + norm_WH - 2. * cross_prod)
return error
def _check_string_param(sparseness, solver):
allowed_sparseness = (None, 'data', 'components')
if sparseness not in allowed_sparseness:
raise ValueError(
'Invalid sparseness parameter: got %r instead of one of %r' %
(sparseness, allowed_sparseness))
allowed_solver = ('pg', 'cd')
if solver not in allowed_solver:
raise ValueError(
'Invalid solver parameter: got %r instead of one of %r' %
(solver, allowed_solver))
def _initialize_nmf(X, n_components, init=None, eps=1e-6,
random_state=None):
"""Algorithms for NMF initialization.
Computes an initial guess for the non-negative
rank k matrix approximation for X: X = WH
Parameters
----------
X : array-like, shape (n_samples, n_features)
The data matrix to be decomposed.
n_components : integer
The number of components desired in the approximation.
init : None | 'random' | 'nndsvd' | 'nndsvda' | 'nndsvdar'
Method used to initialize the procedure.
Default: 'nndsvdar' if n_components < n_features, otherwise 'random'.
Valid options:
'random': non-negative random matrices, scaled with:
sqrt(X.mean() / n_components)
'nndsvd': Nonnegative Double Singular Value Decomposition (NNDSVD)
initialization (better for sparseness)
'nndsvda': NNDSVD with zeros filled with the average of X
(better when sparsity is not desired)
'nndsvdar': NNDSVD with zeros filled with small random values
(generally faster, less accurate alternative to NNDSVDa
for when sparsity is not desired)
eps: float
Truncate all values less then this in output to zero.
random_state : int seed, RandomState instance, or None (default)
Random number generator seed control, used in 'nndsvdar' and
'random' modes.
Returns
-------
W : array-like, shape (n_samples, n_components)
Initial guesses for solving X ~= WH
H : array-like, shape (n_components, n_features)
Initial guesses for solving X ~= WH
References
----------
C. Boutsidis, E. Gallopoulos: SVD based initialization: A head start for
nonnegative matrix factorization - Pattern Recognition, 2008
http://tinyurl.com/nndsvd
"""
check_non_negative(X, "NMF initialization")
n_samples, n_features = X.shape
if init is None:
if n_components < n_features:
init = 'nndsvd'
else:
init = 'random'
# Random initialization
if init == 'random':
avg = np.sqrt(X.mean() / n_components)
rng = check_random_state(random_state)
H = avg * rng.randn(n_components, n_features)
W = avg * rng.randn(n_samples, n_components)
# we do not write np.abs(H, out=H) to stay compatible with
# numpy 1.5 and earlier where the 'out' keyword is not
# supported as a kwarg on ufuncs
np.abs(H, H)
np.abs(W, W)
return W, H
# NNDSVD initialization
U, S, V = randomized_svd(X, n_components, random_state=random_state)
W, H = np.zeros(U.shape), np.zeros(V.shape)
# The leading singular triplet is non-negative
# so it can be used as is for initialization.
W[:, 0] = np.sqrt(S[0]) * np.abs(U[:, 0])
H[0, :] = np.sqrt(S[0]) * np.abs(V[0, :])
for j in range(1, n_components):
x, y = U[:, j], V[j, :]
# extract positive and negative parts of column vectors
x_p, y_p = np.maximum(x, 0), np.maximum(y, 0)
x_n, y_n = np.abs(np.minimum(x, 0)), np.abs(np.minimum(y, 0))
# and their norms
x_p_nrm, y_p_nrm = norm(x_p), norm(y_p)
x_n_nrm, y_n_nrm = norm(x_n), norm(y_n)
m_p, m_n = x_p_nrm * y_p_nrm, x_n_nrm * y_n_nrm
# choose update
if m_p > m_n:
u = x_p / x_p_nrm
v = y_p / y_p_nrm
sigma = m_p
else:
u = x_n / x_n_nrm
v = y_n / y_n_nrm
sigma = m_n
lbd = np.sqrt(S[j] * sigma)
W[:, j] = lbd * u
H[j, :] = lbd * v
W[W < eps] = 0
H[H < eps] = 0
if init == "nndsvd":
pass
elif init == "nndsvda":
avg = X.mean()
W[W == 0] = avg
H[H == 0] = avg
elif init == "nndsvdar":
rng = check_random_state(random_state)
avg = X.mean()
W[W == 0] = abs(avg * rng.randn(len(W[W == 0])) / 100)
H[H == 0] = abs(avg * rng.randn(len(H[H == 0])) / 100)
else:
raise ValueError(
'Invalid init parameter: got %r instead of one of %r' %
(init, (None, 'random', 'nndsvd', 'nndsvda', 'nndsvdar')))
return W, H
def _nls_subproblem(V, W, H, tol, max_iter, alpha=0., l1_ratio=0.,
sigma=0.01, beta=0.1):
"""Non-negative least square solver
Solves a non-negative least squares subproblem using the projected
gradient descent algorithm.
Parameters
----------
V : array-like, shape (n_samples, n_features)
Constant matrix.
W : array-like, shape (n_samples, n_components)
Constant matrix.
H : array-like, shape (n_components, n_features)
Initial guess for the solution.
tol : float
Tolerance of the stopping condition.
max_iter : int
Maximum number of iterations before timing out.
alpha : double, default: 0.
Constant that multiplies the regularization terms. Set it to zero to
have no regularization.
l1_ratio : double, default: 0.
The regularization mixing parameter, with 0 <= l1_ratio <= 1.
For l1_ratio = 0 the penalty is an L2 penalty.
For l1_ratio = 1 it is an L1 penalty.
For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.
sigma : float
Constant used in the sufficient decrease condition checked by the line
search. Smaller values lead to a looser sufficient decrease condition,
thus reducing the time taken by the line search, but potentially
increasing the number of iterations of the projected gradient
procedure. 0.01 is a commonly used value in the optimization
literature.
beta : float
Factor by which the step size is decreased (resp. increased) until
(resp. as long as) the sufficient decrease condition is satisfied.
Larger values allow to find a better step size but lead to longer line
search. 0.1 is a commonly used value in the optimization literature.
Returns
-------
H : array-like, shape (n_components, n_features)
Solution to the non-negative least squares problem.
grad : array-like, shape (n_components, n_features)
The gradient.
n_iter : int
The number of iterations done by the algorithm.
References
----------
C.-J. Lin. Projected gradient methods for non-negative matrix
factorization. Neural Computation, 19(2007), 2756-2779.
http://www.csie.ntu.edu.tw/~cjlin/nmf/
"""
WtV = safe_sparse_dot(W.T, V)
WtW = fast_dot(W.T, W)
# values justified in the paper (alpha is renamed gamma)
gamma = 1
for n_iter in range(1, max_iter + 1):
grad = np.dot(WtW, H) - WtV
if alpha > 0 and l1_ratio == 1.:
grad += alpha
elif alpha > 0:
grad += alpha * (l1_ratio + (1 - l1_ratio) * H)
# The following multiplication with a boolean array is more than twice
# as fast as indexing into grad.
if norm(grad * np.logical_or(grad < 0, H > 0)) < tol:
break
Hp = H
for inner_iter in range(20):
# Gradient step.
Hn = H - gamma * grad
# Projection step.
Hn *= Hn > 0
d = Hn - H
gradd = np.dot(grad.ravel(), d.ravel())
dQd = np.dot(np.dot(WtW, d).ravel(), d.ravel())
suff_decr = (1 - sigma) * gradd + 0.5 * dQd < 0
if inner_iter == 0:
decr_gamma = not suff_decr
if decr_gamma:
if suff_decr:
H = Hn
break
else:
gamma *= beta
elif not suff_decr or (Hp == Hn).all():
H = Hp
break
else:
gamma /= beta
Hp = Hn
if n_iter == max_iter:
warnings.warn("Iteration limit reached in nls subproblem.")
return H, grad, n_iter
def _update_projected_gradient_w(X, W, H, tolW, nls_max_iter, alpha, l1_ratio,
sparseness, beta, eta):
"""Helper function for _fit_projected_gradient"""
n_samples, n_features = X.shape
n_components_ = H.shape[0]
if sparseness is None:
Wt, gradW, iterW = _nls_subproblem(X.T, H.T, W.T, tolW, nls_max_iter,
alpha=alpha, l1_ratio=l1_ratio)
elif sparseness == 'data':
Wt, gradW, iterW = _nls_subproblem(
safe_vstack([X.T, np.zeros((1, n_samples))]),
safe_vstack([H.T, np.sqrt(beta) * np.ones((1,
n_components_))]),
W.T, tolW, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio)
elif sparseness == 'components':
Wt, gradW, iterW = _nls_subproblem(
safe_vstack([X.T,
np.zeros((n_components_, n_samples))]),
safe_vstack([H.T,
np.sqrt(eta) * np.eye(n_components_)]),
W.T, tolW, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio)
return Wt.T, gradW.T, iterW
def _update_projected_gradient_h(X, W, H, tolH, nls_max_iter, alpha, l1_ratio,
sparseness, beta, eta):
"""Helper function for _fit_projected_gradient"""
n_samples, n_features = X.shape
n_components_ = W.shape[1]
if sparseness is None:
H, gradH, iterH = _nls_subproblem(X, W, H, tolH, nls_max_iter,
alpha=alpha, l1_ratio=l1_ratio)
elif sparseness == 'data':
H, gradH, iterH = _nls_subproblem(
safe_vstack([X, np.zeros((n_components_, n_features))]),
safe_vstack([W,
np.sqrt(eta) * np.eye(n_components_)]),
H, tolH, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio)
elif sparseness == 'components':
H, gradH, iterH = _nls_subproblem(
safe_vstack([X, np.zeros((1, n_features))]),
safe_vstack([W,
np.sqrt(beta)
* np.ones((1, n_components_))]),
H, tolH, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio)
return H, gradH, iterH
def _fit_projected_gradient(X, W, H, tol, max_iter,
nls_max_iter, alpha, l1_ratio,
sparseness, beta, eta):
"""Compute Non-negative Matrix Factorization (NMF) with Projected Gradient
References
----------
C.-J. Lin. Projected gradient methods for non-negative matrix
factorization. Neural Computation, 19(2007), 2756-2779.
http://www.csie.ntu.edu.tw/~cjlin/nmf/
P. Hoyer. Non-negative Matrix Factorization with Sparseness Constraints.
Journal of Machine Learning Research 2004.
"""
gradW = (np.dot(W, np.dot(H, H.T))
- safe_sparse_dot(X, H.T, dense_output=True))
gradH = (np.dot(np.dot(W.T, W), H)
- safe_sparse_dot(W.T, X, dense_output=True))
init_grad = squared_norm(gradW) + squared_norm(gradH.T)
# max(0.001, tol) to force alternating minimizations of W and H
tolW = max(0.001, tol) * np.sqrt(init_grad)
tolH = tolW
for n_iter in range(1, max_iter + 1):
# stopping condition
# as discussed in paper
proj_grad_W = squared_norm(gradW * np.logical_or(gradW < 0, W > 0))
proj_grad_H = squared_norm(gradH * np.logical_or(gradH < 0, H > 0))
if (proj_grad_W + proj_grad_H) / init_grad < tol ** 2:
break
# update W
W, gradW, iterW = _update_projected_gradient_w(X, W, H, tolW,
nls_max_iter,
alpha, l1_ratio,
sparseness, beta, eta)
if iterW == 1:
tolW = 0.1 * tolW
# update H
H, gradH, iterH = _update_projected_gradient_h(X, W, H, tolH,
nls_max_iter,
alpha, l1_ratio,
sparseness, beta, eta)
if iterH == 1:
tolH = 0.1 * tolH
H[H == 0] = 0 # fix up negative zeros
if n_iter == max_iter:
W, _, _ = _update_projected_gradient_w(X, W, H, tol, nls_max_iter,
alpha, l1_ratio, sparseness,
beta, eta)
return W, H, n_iter
def _update_coordinate_descent(X, W, Ht, alpha, l1_ratio, shuffle,
random_state):
"""Helper function for _fit_coordinate_descent
Update W to minimize the objective function, iterating once over all
coordinates. By symmetry, to update H, one can call
_update_coordinate_descent(X.T, Ht, W, ...)
"""
n_components = Ht.shape[1]
HHt = fast_dot(Ht.T, Ht)
XHt = safe_sparse_dot(X, Ht)
# L1 and L2 regularizations
l1_reg = 1. * l1_ratio * alpha
l2_reg = (1. - l1_ratio) * alpha
# L2 regularization corresponds to increase the diagonal of HHt
if l2_reg != 0.:
# adds l2_reg only on the diagonal
HHt.flat[::n_components + 1] += l2_reg
# L1 regularization correponds to decrease each element of XHt
if l1_reg != 0.:
XHt -= l1_reg
seed = random_state.randint(np.iinfo(np.int32).max)
return _update_cdnmf_fast(W, HHt, XHt, shuffle, seed)
def _fit_coordinate_descent(X, W, H, tol=1e-4, max_iter=200, alpha=0.001,
l1_ratio=0., regularization=None, update_H=True,
verbose=0, shuffle=False, random_state=None):
"""Compute Non-negative Matrix Factorization (NMF) with Coordinate Descent
The objective function is minimized with an alternating minimization of W
and H. Each minimization is done with a cyclic (up to a permutation of the
features) Coordinate Descent.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Constant matrix.
W : array-like, shape (n_samples, n_components)
Initial guess for the solution.
H : array-like, shape (n_components, n_features)
Initial guess for the solution.
tol : float, default: 1e-4
Tolerance of the stopping condition.
max_iter : integer, default: 200
Maximum number of iterations before timing out.
alpha : double, default: 0.
Constant that multiplies the regularization terms.
l1_ratio : double, default: 0.
The regularization mixing parameter, with 0 <= l1_ratio <= 1.
For l1_ratio = 0 the penalty is an L2 penalty.
For l1_ratio = 1 it is an L1 penalty.
For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.
regularization : 'both' | 'components' | 'transformation' | None
Select whether the regularization affects the components (H), the
transformation (W), both or none of them.
update_H : boolean, default: True
Set to True, both W and H will be estimated from initial guesses.
Set to False, only W will be estimated.
verbose : integer, default: 0
The verbosity level.
shuffle : boolean, default: False
If True, the samples will be taken in shuffled order during
coordinate descent.
random_state : integer seed, RandomState instance, or None (default)
Random number generator seed control.
Returns
-------
W : array-like, shape (n_samples, n_components)
Solution to the non-negative least squares problem.
H : array-like, shape (n_components, n_features)
Solution to the non-negative least squares problem.
n_iter : int
The number of iterations done by the algorithm.
References
----------
Cichocki, Andrzej, and P. H. A. N. Anh-Huy. "Fast local algorithms for
large scale nonnegative matrix and tensor factorizations."
IEICE transactions on fundamentals of electronics, communications and
computer sciences 92.3: 708-721, 2009.
"""
# so W and Ht are both in C order in memory
Ht = check_array(H.T, order='C')
X = check_array(X, accept_sparse='csr')
alpha_H = 0.
alpha_W = 0.
if regularization in ('both', 'components'):
alpha_H = float(alpha)
if regularization in ('both', 'transformation'):
alpha_W = float(alpha)
rng = check_random_state(random_state)
for n_iter in range(max_iter):
violation = 0.
# Update W
violation += _update_coordinate_descent(X, W, Ht, alpha_W,
l1_ratio, shuffle, rng)
# Update H
if update_H:
violation += _update_coordinate_descent(X.T, Ht, W, alpha_H,
l1_ratio, shuffle, rng)
if n_iter == 0:
violation_init = violation
if violation_init == 0:
break
if verbose:
print("violation:", violation / violation_init)
if violation / violation_init <= tol:
if verbose:
print("Converged at iteration", n_iter + 1)
break
return W, Ht.T, n_iter
def non_negative_factorization(X, W=None, H=None, n_components=None,
init='random', update_H=True, solver='cd',
tol=1e-4, max_iter=200, alpha=0., l1_ratio=0.,
regularization=None, random_state=None,
verbose=0, shuffle=False, nls_max_iter=2000,
sparseness=None, beta=1, eta=0.1):
"""Compute Non-negative Matrix Factorization (NMF)
Find two non-negative matrices (W, H) whose product approximates the non-
negative matrix X. This factorization can be used for example for
dimensionality reduction, source separation or topic extraction.
The objective function is::
0.5 * ||X - WH||_Fro^2
+ alpha * l1_ratio * ||vec(W)||_1
+ alpha * l1_ratio * ||vec(H)||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
+ 0.5 * alpha * (1 - l1_ratio) * ||H||_Fro^2
Where::
||A||_Fro^2 = \sum_{i,j} A_{ij}^2 (Frobenius norm)
||vec(A)||_1 = \sum_{i,j} abs(A_{ij}) (Elementwise L1 norm)
The objective function is minimized with an alternating minimization of W
and H. If H is given and update_H=False, it solves for W only.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Constant matrix.
W : array-like, shape (n_samples, n_components)
If init='custom', it is used as initial guess for the solution.
H : array-like, shape (n_components, n_features)
If init='custom', it is used as initial guess for the solution.
If update_H=False, it is used as a constant, to solve for W only.
n_components : integer
Number of components, if n_components is not set all features
are kept.
init : None | 'random' | 'nndsvd' | 'nndsvda' | 'nndsvdar' | 'custom'
Method used to initialize the procedure.
Default: 'nndsvd' if n_components < n_features, otherwise random.
Valid options::
'random': non-negative random matrices, scaled with:
sqrt(X.mean() / n_components)
'nndsvd': Nonnegative Double Singular Value Decomposition (NNDSVD)
initialization (better for sparseness)
'nndsvda': NNDSVD with zeros filled with the average of X
(better when sparsity is not desired)
'nndsvdar': NNDSVD with zeros filled with small random values
(generally faster, less accurate alternative to NNDSVDa
for when sparsity is not desired)
'custom': use custom matrices W and H
update_H : boolean, default: True
Set to True, both W and H will be estimated from initial guesses.
Set to False, only W will be estimated.
solver : 'pg' | 'cd'
Numerical solver to use:
'pg' is a (deprecated) Projected Gradient solver.
'cd' is a Coordinate Descent solver.
tol : float, default: 1e-4
Tolerance of the stopping condition.
max_iter : integer, default: 200
Maximum number of iterations before timing out.
alpha : double, default: 0.
Constant that multiplies the regularization terms.
l1_ratio : double, default: 0.
The regularization mixing parameter, with 0 <= l1_ratio <= 1.
For l1_ratio = 0 the penalty is an elementwise L2 penalty
(aka Frobenius Norm).
For l1_ratio = 1 it is an elementwise L1 penalty.
For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.
regularization : 'both' | 'components' | 'transformation' | None
Select whether the regularization affects the components (H), the
transformation (W), both or none of them.
random_state : integer seed, RandomState instance, or None (default)
Random number generator seed control.
verbose : integer, default: 0
The verbosity level.
shuffle : boolean
If True, the samples will be taken in shuffled order during
coordinate descent.
nls_max_iter : integer, default: 2000
Number of iterations in NLS subproblem.
Used only in the deprecated 'pg' solver.
sparseness : 'data' | 'components' | None, default: None
Where to enforce sparsity in the model.
Used only in the deprecated 'pg' solver.
beta : double, default: 1
Degree of sparseness, if sparseness is not None. Larger values mean
more sparseness. Used only in the deprecated 'pg' solver.
eta : double, default: 0.1
Degree of correctness to maintain, if sparsity is not None. Smaller
values mean larger error. Used only in the deprecated 'pg' solver.
Returns
-------
W : array-like, shape (n_samples, n_components)
Solution to the non-negative least squares problem.
H : array-like, shape (n_components, n_features)
Solution to the non-negative least squares problem.
n_iter : int
Actual number of iterations.
References
----------
C.-J. Lin. Projected gradient methods for non-negative matrix
factorization. Neural Computation, 19(2007), 2756-2779.
http://www.csie.ntu.edu.tw/~cjlin/nmf/
Cichocki, Andrzej, and P. H. A. N. Anh-Huy. "Fast local algorithms for
large scale nonnegative matrix and tensor factorizations."
IEICE transactions on fundamentals of electronics, communications and
computer sciences 92.3: 708-721, 2009.
"""
X = check_array(X, accept_sparse=('csr', 'csc'))
check_non_negative(X, "NMF (input X)")
_check_string_param(sparseness, solver)
n_samples, n_features = X.shape
if n_components is None:
n_components = n_features
if not isinstance(n_components, six.integer_types) or n_components <= 0:
raise ValueError("Number of components must be positive;"
" got (n_components=%r)" % n_components)
if not isinstance(max_iter, numbers.Number) or max_iter < 0:
raise ValueError("Maximum number of iteration must be positive;"
" got (max_iter=%r)" % max_iter)
if not isinstance(tol, numbers.Number) or tol < 0:
raise ValueError("Tolerance for stopping criteria must be "
"positive; got (tol=%r)" % tol)
# check W and H, or initialize them
if init == 'custom':
_check_init(H, (n_components, n_features), "NMF (input H)")
_check_init(W, (n_samples, n_components), "NMF (input W)")
elif not update_H:
_check_init(H, (n_components, n_features), "NMF (input H)")
W = np.zeros((n_samples, n_components))
else:
W, H = _initialize_nmf(X, n_components, init=init,
random_state=random_state)
if solver == 'pg':
warnings.warn("'pg' solver will be removed in release 0.19."
" Use 'cd' solver instead.", DeprecationWarning)
if update_H: # fit_transform
W, H, n_iter = _fit_projected_gradient(X, W, H, tol,
max_iter,
nls_max_iter,
alpha, l1_ratio,
sparseness,
beta, eta)
else: # transform
W, H, n_iter = _update_projected_gradient_w(X, W, H,
tol, nls_max_iter,
alpha, l1_ratio,
sparseness, beta,
eta)
elif solver == 'cd':
W, H, n_iter = _fit_coordinate_descent(X, W, H, tol,
max_iter,
alpha, l1_ratio,
regularization,
update_H=update_H,
verbose=verbose,
shuffle=shuffle,
random_state=random_state)
else:
raise ValueError("Invalid solver parameter '%s'." % solver)
if n_iter == max_iter:
warnings.warn("Maximum number of iteration %d reached. Increase it to"
" improve convergence." % max_iter, ConvergenceWarning)
return W, H, n_iter
class NMF(BaseEstimator, TransformerMixin):
"""Non-Negative Matrix Factorization (NMF)
Find two non-negative matrices (W, H) whose product approximates the non-
negative matrix X. This factorization can be used for example for
dimensionality reduction, source separation or topic extraction.
The objective function is::
0.5 * ||X - WH||_Fro^2
+ alpha * l1_ratio * ||vec(W)||_1
+ alpha * l1_ratio * ||vec(H)||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
+ 0.5 * alpha * (1 - l1_ratio) * ||H||_Fro^2
Where::
||A||_Fro^2 = \sum_{i,j} A_{ij}^2 (Frobenius norm)
||vec(A)||_1 = \sum_{i,j} abs(A_{ij}) (Elementwise L1 norm)
The objective function is minimized with an alternating minimization of W
and H.
Read more in the :ref:`User Guide <NMF>`.
Parameters
----------
n_components : int or None
Number of components, if n_components is not set all features
are kept.
init : 'random' | 'nndsvd' | 'nndsvda' | 'nndsvdar' | 'custom'
Method used to initialize the procedure.
Default: 'nndsvdar' if n_components < n_features, otherwise random.
Valid options::
'random': non-negative random matrices
'nndsvd': Nonnegative Double Singular Value Decomposition (NNDSVD)
initialization (better for sparseness)
'nndsvda': NNDSVD with zeros filled with the average of X
(better when sparsity is not desired)
'nndsvdar': NNDSVD with zeros filled with small random values
(generally faster, less accurate alternative to NNDSVDa
for when sparsity is not desired)
'custom': use custom matrices W and H, given in 'fit' method.
solver : 'pg' | 'cd'
Numerical solver to use:
'pg' is a (deprecated) Projected Gradient solver.
'cd' is a Coordinate Descent solver.
tol : double, default: 1e-4
Tolerance value used in stopping conditions.
max_iter : integer, default: 200
Number of iterations to compute.
random_state : integer seed, RandomState instance, or None (default)
Random number generator seed control.
alpha : double, default: 0.
Constant that multiplies the regularization terms. Set it to zero to
have no regularization.
l1_ratio : double, default: 0.
The regularization mixing parameter, with 0 <= l1_ratio <= 1.
For l1_ratio = 0 the penalty is an elementwise L2 penalty
(aka Frobenius Norm).
For l1_ratio = 1 it is an elementwise L1 penalty.
For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.
shuffle : boolean
If True, the samples will be taken in shuffled order during
coordinate descent.
nls_max_iter : integer, default: 2000
Number of iterations in NLS subproblem.
Used only in the deprecated 'pg' solver.
sparseness : 'data' | 'components' | None, default: None
Where to enforce sparsity in the model.
Used only in the deprecated 'pg' solver.
beta : double, default: 1
Degree of sparseness, if sparseness is not None. Larger values mean
more sparseness. Used only in the deprecated 'pg' solver.
eta : double, default: 0.1
Degree of correctness to maintain, if sparsity is not None. Smaller
values mean larger error. Used only in the deprecated 'pg' solver.
Attributes
----------
components_ : array, [n_components, n_features]
Non-negative components of the data.
reconstruction_err_ : number
Frobenius norm of the matrix difference between
the training data and the reconstructed data from
the fit produced by the model. ``|| X - WH ||_2``
n_iter_ : int
Actual number of iterations.
Examples
--------
>>> import numpy as np
>>> X = np.array([[1,1], [2, 1], [3, 1.2], [4, 1], [5, 0.8], [6, 1]])
>>> from sklearn.decomposition import NMF
>>> model = NMF(n_components=2, init='random', random_state=0)
>>> model.fit(X) #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
NMF(alpha=0.0, beta=1, eta=0.1, init='random', l1_ratio=0.0, max_iter=200,
n_components=2, nls_max_iter=2000, random_state=0, shuffle=False,
solver='cd', sparseness=None, tol=0.0001, verbose=0)
>>> model.components_
array([[ 2.09783018, 0.30560234],
[ 2.13443044, 2.13171694]])
>>> model.reconstruction_err_ #doctest: +ELLIPSIS
0.00115993...
References
----------
C.-J. Lin. Projected gradient methods for non-negative matrix
factorization. Neural Computation, 19(2007), 2756-2779.
http://www.csie.ntu.edu.tw/~cjlin/nmf/
Cichocki, Andrzej, and P. H. A. N. Anh-Huy. "Fast local algorithms for
large scale nonnegative matrix and tensor factorizations."
IEICE transactions on fundamentals of electronics, communications and
computer sciences 92.3: 708-721, 2009.
"""
def __init__(self, n_components=None, init=None, solver='cd',
tol=1e-4, max_iter=200, random_state=None,
alpha=0., l1_ratio=0., verbose=0, shuffle=False,
nls_max_iter=2000, sparseness=None, beta=1, eta=0.1):
self.n_components = n_components
self.init = init
self.solver = solver
self.tol = tol
self.max_iter = max_iter
self.random_state = random_state
self.alpha = alpha
self.l1_ratio = l1_ratio
self.verbose = verbose
self.shuffle = shuffle
if sparseness is not None:
warnings.warn("Controlling regularization through the sparseness,"
" beta and eta arguments is only available"
" for 'pg' solver, which will be removed"
" in release 0.19. Use another solver with L1 or L2"
" regularization instead.", DeprecationWarning)
self.nls_max_iter = nls_max_iter
self.sparseness = sparseness
self.beta = beta
self.eta = eta
def fit_transform(self, X, y=None, W=None, H=None):
"""Learn a NMF model for the data X and returns the transformed data.
This is more efficient than calling fit followed by transform.
Parameters
----------
X: {array-like, sparse matrix}, shape (n_samples, n_features)
Data matrix to be decomposed
W : array-like, shape (n_samples, n_components)
If init='custom', it is used as initial guess for the solution.
H : array-like, shape (n_components, n_features)
If init='custom', it is used as initial guess for the solution.
Attributes
----------
components_ : array-like, shape (n_components, n_features)
Factorization matrix, sometimes called 'dictionary'.
n_iter_ : int
Actual number of iterations for the transform.
Returns
-------
W: array, shape (n_samples, n_components)
Transformed data.
"""
X = check_array(X, accept_sparse=('csr', 'csc'))
W, H, n_iter_ = non_negative_factorization(
X=X, W=W, H=H, n_components=self.n_components,
init=self.init, update_H=True, solver=self.solver,
tol=self.tol, max_iter=self.max_iter, alpha=self.alpha,
l1_ratio=self.l1_ratio, regularization='both',
random_state=self.random_state, verbose=self.verbose,
shuffle=self.shuffle,
nls_max_iter=self.nls_max_iter, sparseness=self.sparseness,
beta=self.beta, eta=self.eta)
if self.solver == 'pg':
self.comp_sparseness_ = _sparseness(H.ravel())
self.data_sparseness_ = _sparseness(W.ravel())
self.reconstruction_err_ = _safe_compute_error(X, W, H)
self.n_components_ = H.shape[0]
self.components_ = H
self.n_iter_ = n_iter_
return W
def fit(self, X, y=None, **params):
"""Learn a NMF model for the data X.
Parameters
----------
X: {array-like, sparse matrix}, shape (n_samples, n_features)
Data matrix to be decomposed
Attributes
----------
components_ : array-like, shape (n_components, n_features)
Factorization matrix, sometimes called 'dictionary'.
n_iter_ : int
Actual number of iterations for the transform.
Returns
-------
self
"""
self.fit_transform(X, **params)
return self
def transform(self, X):
"""Transform the data X according to the fitted NMF model
Parameters
----------
X: {array-like, sparse matrix}, shape (n_samples, n_features)
Data matrix to be transformed by the model
Attributes
----------
n_iter_ : int
Actual number of iterations for the transform.
Returns
-------
W: array, shape (n_samples, n_components)
Transformed data
"""
check_is_fitted(self, 'n_components_')
W, _, n_iter_ = non_negative_factorization(
X=X, W=None, H=self.components_, n_components=self.n_components_,
init=self.init, update_H=False, solver=self.solver,
tol=self.tol, max_iter=self.max_iter, alpha=self.alpha,
l1_ratio=self.l1_ratio, regularization='both',
random_state=self.random_state, verbose=self.verbose,
shuffle=self.shuffle,
nls_max_iter=self.nls_max_iter, sparseness=self.sparseness,
beta=self.beta, eta=self.eta)
self.n_iter_ = n_iter_
return W
@deprecated("It will be removed in release 0.19. Use NMF instead."
"'pg' solver is still available until release 0.19.")
class ProjectedGradientNMF(NMF):
def __init__(self, n_components=None, solver='pg', init=None,
tol=1e-4, max_iter=200, random_state=None,
alpha=0., l1_ratio=0., verbose=0,
nls_max_iter=2000, sparseness=None, beta=1, eta=0.1):
super(ProjectedGradientNMF, self).__init__(
n_components=n_components, init=init, solver='pg', tol=tol,
max_iter=max_iter, random_state=random_state, alpha=alpha,
l1_ratio=l1_ratio, verbose=verbose, nls_max_iter=nls_max_iter,
sparseness=sparseness, beta=beta, eta=eta)
| |
from jedi._compatibility import Python3Method
from jedi.common import unite
from parso.python.tree import ExprStmt, CompFor
from jedi.parser_utils import clean_scope_docstring, get_doc_with_call_signature
class Context(object):
"""
Should be defined, otherwise the API returns empty types.
"""
"""
To be defined by subclasses.
"""
predefined_names = {}
tree_node = None
def __init__(self, evaluator, parent_context=None):
self.evaluator = evaluator
self.parent_context = parent_context
@property
def api_type(self):
# By default just lower name of the class. Can and should be
# overwritten.
return self.__class__.__name__.lower()
def get_root_context(self):
context = self
while True:
if context.parent_context is None:
return context
context = context.parent_context
def execute(self, arguments):
return self.evaluator.execute(self, arguments)
def execute_evaluated(self, *value_list):
"""
Execute a function with already executed arguments.
"""
from jedi.evaluate.param import ValuesArguments
arguments = ValuesArguments([[value] for value in value_list])
return self.execute(arguments)
def eval_node(self, node):
return self.evaluator.eval_element(self, node)
def eval_stmt(self, stmt, seek_name=None):
return self.evaluator.eval_statement(self, stmt, seek_name)
def eval_trailer(self, types, trailer):
return self.evaluator.eval_trailer(self, types, trailer)
@Python3Method
def py__getattribute__(self, name_or_str, name_context=None, position=None,
search_global=False, is_goto=False,
analysis_errors=True):
if name_context is None:
name_context = self
return self.evaluator.find_types(
self, name_or_str, name_context, position, search_global, is_goto,
analysis_errors)
def create_context(self, node, node_is_context=False, node_is_object=False):
return self.evaluator.create_context(self, node, node_is_context, node_is_object)
def is_class(self):
return False
def py__bool__(self):
"""
Since Wrapper is a super class for classes, functions and modules,
the return value will always be true.
"""
return True
def py__doc__(self, include_call_signature=False):
try:
self.tree_node.get_doc_node
except AttributeError:
return ''
else:
if include_call_signature:
return get_doc_with_call_signature(self.tree_node)
else:
return clean_scope_docstring(self.tree_node)
return None
class TreeContext(Context):
def __init__(self, evaluator, parent_context=None):
super(TreeContext, self).__init__(evaluator, parent_context)
self.predefined_names = {}
def __repr__(self):
return '<%s: %s>' % (self.__class__.__name__, self.tree_node)
class AbstractLazyContext(object):
def __init__(self, data):
self.data = data
def __repr__(self):
return '<%s: %s>' % (self.__class__.__name__, self.data)
def infer(self):
raise NotImplementedError
class LazyKnownContext(AbstractLazyContext):
"""data is a context."""
def infer(self):
return set([self.data])
class LazyKnownContexts(AbstractLazyContext):
"""data is a set of contexts."""
def infer(self):
return self.data
class LazyUnknownContext(AbstractLazyContext):
def __init__(self):
super(LazyUnknownContext, self).__init__(None)
def infer(self):
return set()
class LazyTreeContext(AbstractLazyContext):
def __init__(self, context, node):
super(LazyTreeContext, self).__init__(node)
self._context = context
# We need to save the predefined names. It's an unfortunate side effect
# that needs to be tracked otherwise results will be wrong.
self._predefined_names = dict(context.predefined_names)
def infer(self):
old, self._context.predefined_names = \
self._context.predefined_names, self._predefined_names
try:
return self._context.eval_node(self.data)
finally:
self._context.predefined_names = old
def get_merged_lazy_context(lazy_contexts):
if len(lazy_contexts) > 1:
return MergedLazyContexts(lazy_contexts)
else:
return lazy_contexts[0]
class MergedLazyContexts(AbstractLazyContext):
"""data is a list of lazy contexts."""
def infer(self):
return unite(l.infer() for l in self.data)
class ContextualizedNode(object):
def __init__(self, context, node):
self.context = context
self._node = node
def get_root_context(self):
return self.context.get_root_context()
def infer(self):
return self.context.eval_node(self._node)
class ContextualizedName(ContextualizedNode):
# TODO merge with TreeNameDefinition?!
@property
def name(self):
return self._node
def assignment_indexes(self):
"""
Returns an array of tuple(int, node) of the indexes that are used in
tuple assignments.
For example if the name is ``y`` in the following code::
x, (y, z) = 2, ''
would result in ``[(1, xyz_node), (0, yz_node)]``.
"""
indexes = []
node = self._node.parent
compare = self._node
while node is not None:
if node.type in ('testlist', 'testlist_comp', 'testlist_star_expr', 'exprlist'):
for i, child in enumerate(node.children):
if child == compare:
indexes.insert(0, (int(i / 2), node))
break
else:
raise LookupError("Couldn't find the assignment.")
elif isinstance(node, (ExprStmt, CompFor)):
break
compare = node
node = node.parent
return indexes
| |
#!/usr/bin/env python -OO
# encoding: utf-8
###########
# ORP - Open Robotics Platform
#
# Copyright (c) 2010 John Harrison, William Woodall
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
##########
"""
rpcserver.py - Contains the RPCServer class which defines the available \
functions in the rpc server.
Created by William Woodall on 2010-09-18.
"""
__author__ = "William Woodall"
__copyright__ = "Copyright (c) 2010 John Harrison, William Woodall"
### Imports ###
# Standard Python Libraries
import sys
import os
import sys
import types
import signal
from multiprocessing import Process, Lock, Value, Queue
from threading import Timer
from SimpleXMLRPCServer import SimpleXMLRPCServer
import time
import logging
import ctypes
# Other Libraries
import orpd
from orpd import network_handlers
import orpdaemon
from logerror import logError
from sandbox import Sandbox
### Class ###
class RPCServer(SimpleXMLRPCServer):
"""Defines the available xmlrpc functions"""
def __init__(self, connection, daemon):
"""docstring for __init__"""
# Setup logging
self.log = logging.getLogger('ORPD')
self.log_servers = []
self.daemon = daemon
self.sandbox = None
self.sandbox_proc = None
self.sandbox_lock = None
self.sandbox_queue = None
self.sandbox_running = None
self.sandbox_paused = False
self.client_addr = None
self.network_handlers = network_handlers
SimpleXMLRPCServer.__init__(self,
connection, logRequests=False, allow_none=True)
def _dispatch(self, method, params):
"""Overrides the dispatch method"""
try:
# We are forcing the 'xmlrpc_' prefix on methods that are
# callable through XML-RPC
func = getattr(self, 'xmlrpc_'+method)
except AttributeError:
try:
func = self.funcs[method]
if func is not None:
try:
return func(*params)
except Exception as err:
logError(sys.exc_info(), self.log.error, 'Exception in RPC call %s' % method, orpdaemon.HWM_MAGIC_LINENO)
else:
raise Exception("Method '%s' is not supported by this Server" % method)
except Exception:
return SimpleXMLRPCServer._dispatch(self, method, params)
else:
try:
return func(*params)
except Exception as err:
logError(sys.exc_info(), self.log.error, "Exception in RPC call %s" % method)
def registerFunctions(self, functions):
"""Takes a dictionary, functions, and registers them"""
for func_name in functions:
self.register_function(functions[func_name], func_name)
def verify_request(self, request, client_addr):
"""Overrides SimpleXMLRPCServer.verify_request to
capture the address of the latest request"""
self.client_addr = client_addr
return True
def xmlrpc_listFunctions(self):
"""Lists the Available Functions"""
methods = self.funcs.keys()
for x in ['system.listMethods', 'system.methodHelp', 'system.methodSignature']:
if x in methods:
methods.remove(x)
return methods
#### Functions Related to Executing Control Code ####
def xmlrpc_runControlCode(self, control_code=None):
"""Runs control code in the files dir"""
# Check for correct parameters
if control_code == None:
self.log.error("No Control Code passed to function runControlCode")
return False
if self.sandbox_proc != None and self.sandbox_proc.is_alive():
self.log.error("Control Code already running")
return False
if not os.path.exists(control_code):
self.log.error('Control Code not found: ' + control_code)
return False
# Spawn the sandbox
self.sandbox = Sandbox()
self.sandbox_lock = Lock()
self.sandbox_running = Value(ctypes.c_bool, True)
self.sandbox_queue = Queue()
self.sandbox_proc = \
Process("Sandbox", target=self.sandbox.startUp,
args=(self.daemon.device_objects, self.daemon.work_directory,
control_code, self.sandbox_lock, self.sandbox_running,
self.sandbox_queue))
self.sandbox_proc.start()
Timer(0.5, self.joinControlCode).start()
# Attempt to call start() on each of the devices that are running
for device in self.daemon.device_objects:
try:
device.start()
except Exception as error:
logError(sys.exc_info(), self.log.error, "Error executing start() of the %s device:" % device.name, orpdaemon.HWM_MAGIC_LINENO)
return True
def joinControlCode(self):
"""This function trys to join the sandbox and periodically checks to see if it has crashed"""
# Wait for the sandbox to stop
try:
sandbox_running = True
while sandbox_running:
if self.sandbox_proc != None and self.sandbox_proc.exitcode == None:
pass
else:
sandbox_running = False
self.sandbox_running.value = False
break
self.sandbox_proc.join(1)
finally:
if self.sandbox_proc.exitcode == -signal.SIGTERM:
result = False
self.log.info('Control Code did not exit cleanly')
self.sandbox = None
self.sandbox_proc = None
self.sandbox_lock = None
self.sandbox_running.value = False
self.sandbox_paused = False
for device in self.daemon.device_objects:
try:
device.stop()
except Exception as error:
logError(sys.exc_info(), self.log.error, "Error executing stop() of the %s device:" % device.name, orpdaemon.HWM_MAGIC_LINENO)
self.log.info('Control Code Stopped')
def xmlrpc_stopControlCode(self):
"""Stops the sandbox, returns false if it times out"""
self.log.info('Control Code Stopping')
# Check to see if it is already stopped
result = True
if self.sandbox_proc == None or not self.sandbox_proc.is_alive():
return result
# Start a timer to kill the sandbox is necessary
Timer(2, self.sandbox_proc.terminate).start()
# Stop the sandbox
self.sandbox_running.value = False
self.sandbox_proc.join()
if self.sandbox_proc.exitcode == -signal.SIGTERM:
result = False
return result
def xmlrpc_pauseControlCode(self):
"""Pauses the current running control, if some is running"""
# Check that control code is running, else return False
if self.sandbox_proc == None:
return False
# Pause the control code
if not self.sandbox_paused:
self.sandbox_lock.acquire()
self.sandbox_paused = True
return True
def xmlrpc_resumeControlCode(self):
"""Pauses the current running control, if some is running"""
# Check that control code is running, else return False
if self.sandbox_proc == None or not self.sandbox_paused:
return False
# Resume the control code
# self.sandbox_lock.acquire(0)
self.sandbox_lock.release()
self.sandbox_paused = False
return True
#### Functions related to logging ####
def xmlrpc_log(self, level, msg):
"""Allows for people to inject logs over rpc"""
if type(level) == str:
levels = {'notset':0,'debug':10,'info':20,
'warning':30,'error':40,'critical':50}
self.log.log(levels[level.lower()], msg)
elif type(level) == int:
self.log.log(level, msg)
def xmlrpc_debug(self, msg):
"""Creates a debug log"""
self.log.debug(msg)
def xmlrpc_info(self, msg):
"""Creates an info log"""
self.log.info(msg)
def xmlrpc_warning(self, msg):
"""Creates a warning log"""
self.log.warning(msg)
def xmlrpc_error(self, msg):
"""Creates an error log"""
self.log.error(msg)
def xmlrpc_critical(self, msg):
"""Creates a critical log"""
self.log.critical(msg)
#### File Management Functions ####
def xmlrpc_write(self, file_name, file_contents, timestamp=None):
"""Writes a file sent to the daemon,
returns True on success and False on failure"""
file_dir, _ = os.path.split(file_name)
if file_dir and not os.path.exists(file_dir):
os.makedirs(file_dir)
result = True
try:
save_file = open(file_name, 'w+')
save_file.write(file_contents)
save_file.close()
if timestamp:
os.utime(file_name, (timestamp, timestamp))
self.log.info('Wrote file '+file_name)
except IOError as error:
self.log.error('Cannot write file: '+file_name+\
'\n'+str(error))
result = False
return result
def xmlrpc_getFileContents(self, file_name):
"""Returns the contents of the given file"""
file_handler = open(file_name, 'r')
return file_handler.read()
def xmlrpc_getConfig(self):
"""This function returns the config file as a string"""
config_file = open(self.daemon.config_file_name, 'r')
return config_file.read()
def xmlrpc_sendConfig(self, config):
"""Writes the given data to the config file"""
config_file_name = self.daemon.config_file_name
_, temp_name = os.path.split(config_file_name)
if temp_name == 'orpd.cfg.default':
self.daemon.config_file_name = config_file_name = config_file_name[:-8]
config_file = open(config_file_name, 'w+')
config_file.write(config)
config_file.close()
#### Misc Functions ####
def xmlrpc_ping(self):
"""Ping, Pong."""
self.log.info('Pong')
return True
def xmlrpc_connect(self):
"""Called when a dashboard connects"""
self.log.info('Receiving connection from %s' % self.client_addr[0])
if self.client_addr[0] in self.network_handlers:
self.log.debug('Dashboard Already Connected, not opening a new logging socket')
else:
# Setup Network handler
network = logging.handlers.SocketHandler(self.client_addr[0],
logging.handlers.DEFAULT_TCP_LOGGING_PORT)
network.setLevel(logging.DEBUG)
root = logging.getLogger('')
root.addHandler(network)
self.log_servers.append(network)
self.network_handlers[self.client_addr[0]] = network
def xmlrpc_fileSync(self):
"Synchronize the files between the server and the client"
return self.__buildListing()
def __buildListing(self):
"""Build a listing of the files in files and modules for connection"""
cc_list = self.__walkDirectory(os.path.join(
self.daemon.work_directory, 'files'))
module_list = self.__walkDirectory(os.path.join(
self.daemon.work_directory, 'modules'))
return (cc_list, module_list)
def __walkDirectory(self, path):
"""Walks the Directory"""
listing = {}
for root, _, files in os.walk(path):
if root[0] == '.':
continue
file_path = root.replace(path, '')[1:]
if file_path and filter(lambda x: x[0] == '.', file_path.split(os.sep)):
continue
for f in files:
if f[0] != '.' and not f.endswith(('.hwmo', '.hwmc', '.pyo', '.pyc', '.cco', '.ccc')):
full_path = os.path.join(path, file_path, f)
listing_name = os.path.join(file_path, f)
listing[listing_name] = os.stat(full_path)[8]
return listing
def xmlrpc_disconnect(self):
"""docstring for xmlrpc_disconnect"""
if self.client_addr[0] in self.network_handlers:
root = logging.getLogger()
root.removeHandler(self.network_handlers[self.client_addr[0]])
del self.network_handlers[self.client_addr[0]]
def xmlrpc_shutdown(self):
"""Shutsdown the system"""
for device in self.daemon.device_objects:
try:
device.shutdown()
except Exception as error:
logError(sys.exc_info(), self.log.error, "Error executing shutdown() of the %s device:" % device.name, orpdaemon.HWM_MAGIC_LINENO)
self.log.debug('Daemon Shutdown')
# I do this so that the xmlrpc function can return properly.
# If you just xmlrpc.shutdown() then,
# the return None line never gets executed.
# So I just have it call that 100mS later to allow it to return first.
Timer(0.1, self.__shutdown).start()
return None
def xmlrpc_restart(self):
"""Restarts the server"""
self.log.info('Server Restarted')
return self.xmlrpc_changeWorkDirectory(self.daemon.work_directory)
def xmlrpc_changeWorkDirectory(self, work_dir):
"""This stops the services, changes the work directory,
and then reloads everything that can be configured through config files"""
if os.path.exists(work_dir):
self.daemon.new_work_dir = work_dir
self.xmlrpc_shutdown()
return True
return False
def __shutdown(self):
"""Shuts down"""
self.shutdown()
self.socket.close()
| |
import openpnm as op
from openpnm.io import Dict
import py
import os
class DictTest:
def setup_class(self):
ws = op.Workspace()
ws.settings['local_data'] = True
self.net = op.network.Cubic(shape=[2, 2, 2])
Ps = [0, 1, 2, 3]
Ts = self.net.find_neighbor_throats(pores=Ps)
self.geo_1 = op.geometry.GenericGeometry(network=self.net,
pores=Ps, throats=Ts)
self.geo_1['pore.boo'] = 1
self.geo_1['throat.boo'] = 1
Ps = [4, 5, 6, 7]
Ts = self.net.find_neighbor_throats(pores=Ps, mode='xnor')
self.geo_2 = op.geometry.GenericGeometry(network=self.net,
pores=Ps, throats=Ts)
self.geo_2['pore.boo'] = 1
self.geo_2['throat.boo'] = 1
self.phase_1 = op.phase.GenericPhase(network=self.net)
self.phase_1['pore.bar'] = 2
self.phase_1['throat.bar'] = 2
self.phase_2 = op.phase.GenericPhase(network=self.net)
self.phase_2['pore.bar'] = 2
self.phase_2['throat.bar'] = 2
self.phys_1 = op.physics.GenericPhysics(network=self.net,
phase=self.phase_1,
geometry=self.geo_1)
self.phys_1['pore.baz'] = 11
self.phys_1['throat.baz'] = 11
self.phys_2 = op.physics.GenericPhysics(network=self.net,
phase=self.phase_1,
geometry=self.geo_2)
self.phys_2['pore.baz'] = 12
self.phys_2['throat.baz'] = 12
self.phys_3 = op.physics.GenericPhysics(network=self.net,
phase=self.phase_2,
geometry=self.geo_1)
self.phys_3['pore.baz'] = 21
self.phys_3['throat.baz'] = 21
self.phys_4 = op.physics.GenericPhysics(network=self.net,
phase=self.phase_2,
geometry=self.geo_2)
self.phys_4['pore.baz'] = 22
self.phys_4['throat.baz'] = 22
def teardown_class(self):
ws = op.Workspace()
ws.clear()
def test_to_dict_missing_all_physics(self):
net = op.network.Cubic(shape=[4, 4, 4])
op.geometry.GenericGeometry(network=net, pores=net.Ps, throats=net.Ts)
phase = op.phase.GenericPhase(network=net)
Dict.to_dict(network=net, phases=[phase], flatten=True,
interleave=True, categorize_by=[])
def test_to_dict_flattened_interleaved(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1, self.phase_2],
flatten=True, interleave=True, categorize_by=[])
a = set(['net_01', 'phase_01', 'phase_02'])
assert a == set(D.keys())
assert set(['geo_01', 'geo_02']).isdisjoint(D['net_01'].keys())
assert set(['phys_01', 'phys_02']).isdisjoint(D['phase_01'].keys())
assert set(['phys_03', 'phys_04']).isdisjoint(D['phase_02'].keys())
def test_to_dict_flattened_not_interleaved(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1, self.phase_2],
flatten=True, interleave=False, categorize_by=[])
a = set([i.name for i in self.net.project])
assert a == set(D.keys())
assert set(['geo_01', 'geo_02']).isdisjoint(D['net_01'].keys())
assert set(['phys_01', 'phys_02']).isdisjoint(D['phase_01'].keys())
assert set(['phys_03', 'phys_04']).isdisjoint(D['phase_02'].keys())
def test_to_dict_not_flattened_interleaved(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1, self.phase_2],
flatten=False, interleave=True, categorize_by=[])
a = set(['net_01', 'phase_01', 'phase_02'])
assert a == set(D.keys())
assert set(['geo_01', 'geo_02']).isdisjoint(D['net_01'].keys())
assert set(['phys_01', 'phys_02']).isdisjoint(D['phase_01'].keys())
assert set(['phys_03', 'phys_04']).isdisjoint(D['phase_02'].keys())
def test_to_dict_not_flattened_not_interleaved(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1, self.phase_2],
flatten=False, interleave=False, categorize_by=[])
_ = set(['network', 'phase', 'physics', 'geometry'])
b = set(['net_01', 'phase_01', 'phase_02'])
_ = set(['labels', 'properties'])
_ = set(['pore', 'throat'])
# Ensure NOT categorized by object
assert b == set(D.keys())
# Ensure NOT flattened
assert set(['geo_01', 'geo_02']).issubset(D['net_01'].keys())
assert set(['phys_01', 'phys_02']).issubset(D['phase_01'].keys())
assert set(['phys_03', 'phys_04']).issubset(D['phase_02'].keys())
# Ensure no cross talk between phases
assert set(['phys_01', 'phys_02']).isdisjoint(D['phase_02'].keys())
assert set(['phys_03', 'phys_04']).isdisjoint(D['phase_01'].keys())
def test_to_dict_not_flat_not_interleaved_categorized_by_object(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1, self.phase_2],
flatten=False, interleave=False,
categorize_by=['object'])
_ = set(['network', 'phase', 'physics', 'geometry'])
_ = set(['net_01', 'phase_01', 'phase_02'])
_ = set(['labels', 'properties'])
_ = set(['pore', 'throat'])
e = set(['network', 'phase'])
# Ensure categorized by object
assert e == set(D.keys())
# Ensure flatten, which occurs when categorized by object
keys = D['network']['net_01']['geometry'].keys()
assert set(['geo_01', 'geo_02']).issubset(keys)
keys = D['phase'].keys()
assert set(['phase_01', 'phase_02']).issubset(keys)
keys = D['phase']['phase_01']['physics'].keys()
assert set(['phys_01', 'phys_02']).issubset(keys)
def test_to_dict_not_flat_not_interleaved_categorized_by_data(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1, self.phase_2],
flatten=False, interleave=False,
categorize_by=['data'])
_ = set(['network', 'phase', 'physics', 'geometry'])
b = set(['net_01', 'phase_01', 'phase_02'])
c = set(['labels', 'properties'])
_ = set(['pore', 'throat'])
# Ensure NOT categorized by object
assert b == set(D.keys())
# Ensure NOT flattened
assert set(['geo_01', 'geo_02']).issubset(D['net_01'].keys())
assert set(['phys_01', 'phys_02']).issubset(D['phase_01'].keys())
assert set(['phys_03', 'phys_04']).issubset(D['phase_02'].keys())
# Ensure categorized by data
assert c.issubset(D['net_01'].keys())
assert c.issubset(D['phase_01'].keys())
assert c.issubset(D['phase_02'].keys())
assert c.issubset(D['net_01']['geo_01'].keys())
assert c.issubset(D['net_01']['geo_02'].keys())
assert c.issubset(D['phase_01']['phys_01'].keys())
assert c.issubset(D['phase_01']['phys_02'].keys())
assert c.issubset(D['phase_02']['phys_03'].keys())
assert c.issubset(D['phase_02']['phys_04'].keys())
def test_to_dict_not_flat_not_interleaved_categorized_by_element(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1, self.phase_2],
flatten=False, interleave=False,
categorize_by=['element'])
_ = set(['network', 'phase', 'physics', 'geometry'])
b = set(['net_01', 'phase_01', 'phase_02'])
_ = set(['labels', 'properties'])
d = set(['pore', 'throat'])
# Ensure NOT categorized by object
assert b == set(D.keys())
# Ensure NOT flattened
assert set(['geo_01', 'geo_02']).issubset(D['net_01'].keys())
assert set(['phys_01', 'phys_02']).issubset(D['phase_01'].keys())
assert set(['phys_03', 'phys_04']).issubset(D['phase_02'].keys())
# Ensure it's categorized by element
assert d.issubset(D['net_01'].keys())
assert d.issubset(D['phase_01'].keys())
assert d.issubset(D['phase_01'].keys())
assert d.issubset(D['phase_02'].keys())
assert d.issubset(D['phase_02'].keys())
assert d.issubset(D['net_01']['geo_01'].keys())
assert d.issubset(D['net_01']['geo_01'].keys())
assert d.issubset(D['net_01']['geo_02'].keys())
assert d.issubset(D['net_01']['geo_02'].keys())
assert d.issubset(D['phase_01']['phys_01'].keys())
assert d.issubset(D['phase_01']['phys_01'].keys())
assert d.issubset(D['phase_01']['phys_02'].keys())
assert d.issubset(D['phase_01']['phys_02'].keys())
assert d.issubset(D['phase_02']['phys_03'].keys())
assert d.issubset(D['phase_02']['phys_03'].keys())
assert d.issubset(D['phase_02']['phys_04'].keys())
assert d.issubset(D['phase_02']['phys_04'].keys())
def test_to_dict_not_flat_not_interleaved_cat_by_element_data(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1, self.phase_2],
flatten=False, interleave=False,
categorize_by=['element', 'data'])
_ = set(['network', 'phase', 'physics', 'geometry'])
b = set(['net_01', 'phase_01', 'phase_02'])
_ = set(['labels', 'properties'])
d = set(['pore', 'throat'])
# Ensure NOT categorized by object
assert b == set(D.keys())
# Ensure NOT flattened
assert set(['geo_01', 'geo_02']).issubset(D['net_01'].keys())
assert set(['phys_01', 'phys_02']).issubset(D['phase_01'].keys())
assert set(['phys_03', 'phys_04']).issubset(D['phase_02'].keys())
# Ensure categorized by data and element
assert d.issubset(D['net_01']['properties'].keys())
assert d.issubset(D['net_01']['labels'].keys())
assert d.issubset(D['phase_01']['properties'].keys())
assert d.issubset(D['phase_01']['labels'].keys())
assert d.issubset(D['phase_02']['properties'].keys())
assert d.issubset(D['phase_02']['labels'].keys())
assert d.issubset(D['net_01']['geo_01']['properties'].keys())
assert d.issubset(D['net_01']['geo_01']['labels'].keys())
assert d.issubset(D['net_01']['geo_02']['properties'].keys())
assert d.issubset(D['net_01']['geo_02']['labels'].keys())
assert d.issubset(D['phase_01']['phys_01']['properties'].keys())
assert d.issubset(D['phase_01']['phys_01']['labels'].keys())
assert d.issubset(D['phase_01']['phys_02']['properties'].keys())
assert d.issubset(D['phase_01']['phys_02']['labels'].keys())
assert d.issubset(D['phase_02']['phys_03']['properties'].keys())
assert d.issubset(D['phase_02']['phys_03']['labels'].keys())
assert d.issubset(D['phase_02']['phys_04']['properties'].keys())
assert d.issubset(D['phase_02']['phys_04']['labels'].keys())
def test_to_dict_not_flat_not_interleaved_cat_by_element_data_object(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1, self.phase_2],
flatten=False, interleave=False,
categorize_by=['element', 'data', 'object'])
_ = set(['network', 'phase', 'physics', 'geometry'])
_ = set(['net_01', 'phase_01', 'phase_02'])
_ = set(['labels', 'properties'])
d = set(['pore', 'throat'])
e = set(['network', 'phase'])
# Check if categorized by object, but not flattened
assert e == set(D.keys())
assert 'geometry' in D['network']['net_01'].keys()
assert 'physics' in D['phase']['phase_01'].keys()
assert 'physics' in D['phase']['phase_02'].keys()
# Ensure it's categorized by object, data, and element
assert d.issubset(D['network']['net_01']['labels'].keys())
assert d.issubset(D['phase']['phase_01']['properties'].keys())
assert d.issubset(D['phase']['phase_01']['labels'].keys())
assert d.issubset(D['phase']['phase_02']['properties'].keys())
assert d.issubset(D['phase']['phase_02']['labels'].keys())
path = D['network']['net_01']['geometry']['geo_01']['properties']
assert d.issubset(path.keys())
path = D['network']['net_01']['geometry']['geo_01']['labels']
assert d.issubset(path.keys())
path = D['network']['net_01']['geometry']['geo_02']['properties']
assert d.issubset(path.keys())
path = D['network']['net_01']['geometry']['geo_02']['labels']
assert d.issubset(path.keys())
path = D['phase']['phase_01']['physics']['phys_01']['properties']
assert d.issubset(path.keys())
path = D['phase']['phase_01']['physics']['phys_01']['labels']
assert d.issubset(path.keys())
path = D['phase']['phase_01']['physics']['phys_02']['properties']
assert d.issubset(path.keys())
path = D['phase']['phase_01']['physics']['phys_02']['labels']
assert d.issubset(path.keys())
path = D['phase']['phase_02']['physics']['phys_03']['properties']
assert d.issubset(path.keys())
path = D['phase']['phase_02']['physics']['phys_03']['labels']
assert d.issubset(path.keys())
path = D['phase']['phase_02']['physics']['phys_04']['properties']
assert d.issubset(path.keys())
path = D['phase']['phase_02']['physics']['phys_04']['labels']
assert d.issubset(path.keys())
def test_to_dict_not_flat_not_interleaved_cat_by_element_object(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1, self.phase_2],
flatten=False, interleave=False,
categorize_by=['element', 'object'])
_ = set(['network', 'phase', 'physics', 'geometry'])
_ = set(['net_01', 'phase_01', 'phase_02'])
_ = set(['labels', 'properties'])
d = set(['pore', 'throat'])
e = set(['network', 'phase'])
# Check if categorized by object
assert e == set(D.keys())
# Check if categorized by object, but not flattened
assert e == set(D.keys())
assert 'geometry' in D['network']['net_01'].keys()
assert 'physics' in D['phase']['phase_01'].keys()
assert 'physics' in D['phase']['phase_02'].keys()
# Ensure it's categorized by element
assert d.issubset(D['network']['net_01'].keys())
assert d.issubset(D['phase']['phase_01'].keys())
assert d.issubset(D['phase']['phase_01'].keys())
assert d.issubset(D['phase']['phase_02'].keys())
assert d.issubset(D['phase']['phase_02'].keys())
assert d.issubset(D['network']['net_01']['geometry']['geo_01'].keys())
assert d.issubset(D['network']['net_01']['geometry']['geo_01'].keys())
assert d.issubset(D['network']['net_01']['geometry']['geo_02'].keys())
assert d.issubset(D['network']['net_01']['geometry']['geo_02'].keys())
assert d.issubset(D['phase']['phase_01']['physics']['phys_01'].keys())
assert d.issubset(D['phase']['phase_01']['physics']['phys_01'].keys())
assert d.issubset(D['phase']['phase_01']['physics']['phys_02'].keys())
assert d.issubset(D['phase']['phase_01']['physics']['phys_02'].keys())
assert d.issubset(D['phase']['phase_02']['physics']['phys_03'].keys())
assert d.issubset(D['phase']['phase_02']['physics']['phys_03'].keys())
assert d.issubset(D['phase']['phase_02']['physics']['phys_04'].keys())
assert d.issubset(D['phase']['phase_02']['physics']['phys_04'].keys())
def test_to_dict_flat_not_interleaved_categorized_by_element(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1, self.phase_2],
flatten=True, interleave=False,
categorize_by=['element'])
assert set(D.keys()) == set([i.name for i in self.net.project])
d = set(['pore', 'throat'])
assert d.issubset(D['net_01'].keys())
assert d.issubset(D['geo_01'].keys())
assert d.issubset(D['geo_02'].keys())
assert d.issubset(D['phase_01'].keys())
assert d.issubset(D['phase_02'].keys())
assert d.issubset(D['phys_01'].keys())
assert d.issubset(D['phys_02'].keys())
assert d.issubset(D['phys_03'].keys())
assert d.issubset(D['phys_04'].keys())
def test_to_dict_flat_not_interleaved_categorized_by_data(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1, self.phase_2],
flatten=True, interleave=False,
categorize_by=['data'])
assert set(D.keys()) == set([i.name for i in self.net.project])
c = set(['labels', 'properties'])
assert c.issubset(D['net_01'].keys())
assert c.issubset(D['geo_01'].keys())
assert c.issubset(D['geo_02'].keys())
assert c.issubset(D['phase_01'].keys())
assert c.issubset(D['phase_02'].keys())
assert c.issubset(D['phys_01'].keys())
assert c.issubset(D['phys_02'].keys())
assert c.issubset(D['phys_03'].keys())
assert c.issubset(D['phys_04'].keys())
def test_to_dict_flat_not_interleaved_categorized_by_data_element(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1, self.phase_2],
flatten=True, interleave=False,
categorize_by=['data', 'element'])
assert set(D.keys()) == set([i.name for i in self.net.project])
d = set(['pore', 'throat'])
assert d.issubset(D['net_01']['labels'].keys())
assert d.issubset(D['net_01']['properties'].keys())
assert d.issubset(D['geo_01']['labels'].keys())
assert d.issubset(D['geo_01']['properties'].keys())
assert d.issubset(D['geo_02']['labels'].keys())
assert d.issubset(D['geo_02']['properties'].keys())
assert d.issubset(D['phase_01']['labels'].keys())
assert d.issubset(D['phase_01']['properties'].keys())
assert d.issubset(D['phase_02']['labels'].keys())
assert d.issubset(D['phase_02']['properties'].keys())
assert d.issubset(D['phys_01']['labels'].keys())
assert d.issubset(D['phys_01']['properties'].keys())
assert d.issubset(D['phys_02']['labels'].keys())
assert d.issubset(D['phys_02']['properties'].keys())
assert d.issubset(D['phys_03']['labels'].keys())
assert d.issubset(D['phys_03']['properties'].keys())
assert d.issubset(D['phys_04']['labels'].keys())
assert d.issubset(D['phys_04']['properties'].keys())
def test_to_dict_interleaved_categorized_by_element(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1, self.phase_2],
flatten=False, interleave=True,
categorize_by=['element'])
b = set(['net_01', 'phase_01', 'phase_02'])
assert set(D.keys()) == b
d = set(['pore', 'throat'])
assert d.issubset(D['net_01'].keys())
assert d.issubset(D['phase_01'].keys())
assert d.issubset(D['phase_02'].keys())
def test_to_dict_interleaved_categorized_by_data(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1, self.phase_2],
flatten=False, interleave=True,
categorize_by=['data'])
b = set(['net_01', 'phase_01', 'phase_02'])
assert set(D.keys()) == b
d = set(['labels', 'properties'])
assert d.issubset(D['net_01'].keys())
assert d.issubset(D['phase_01'].keys())
assert d.issubset(D['phase_02'].keys())
def test_to_dict_interleaved_categorized_by_data_element(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1, self.phase_2],
flatten=False, interleave=True,
categorize_by=['data', 'element'])
b = set(['net_01', 'phase_01', 'phase_02'])
assert set(D.keys()) == b
d = set(['pore', 'throat'])
assert d.issubset(D['net_01']['labels'].keys())
assert d.issubset(D['net_01']['properties'].keys())
assert d.issubset(D['phase_01']['labels'].keys())
assert d.issubset(D['phase_01']['properties'].keys())
assert d.issubset(D['phase_02']['labels'].keys())
assert d.issubset(D['phase_02']['properties'].keys())
def test_to_dict_categorize_by_project(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1, self.phase_2],
flatten=False, interleave=True,
categorize_by=['project'])
assert 'proj_01' in D.keys()
def test_from_dict_interleaved_categorized_by_object(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1],
flatten=False, interleave=True,
categorize_by=['object'])
proj = Dict.from_dict(D)
assert len(proj) == 2
assert len(proj.geometries().values()) == 0
assert len(proj.phases().values()) == 1
assert len(proj.physics().values()) == 0
def test_from_dict_interleaved_not_categorized(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1],
flatten=False, interleave=True,
categorize_by=[])
proj = Dict.from_dict(D)
assert len(proj) == 2
assert len(proj.geometries().values()) == 0
assert len(proj.phases().values()) == 0
assert len(proj.physics().values()) == 0
def test_from_dict_not_interleaved_flatted_categorized_by_object(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1],
flatten=True, interleave=False,
categorize_by=['object'])
proj = Dict.from_dict(D)
assert len(proj) == 6
assert len(proj.geometries().values()) == 2
assert len(proj.phases().values()) == 1
assert len(proj.physics().values()) == 2
def test_from_dict_not_interleaved_not_flatted_categorized_by_object(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1],
flatten=False, interleave=False,
categorize_by=['object'])
proj = Dict.from_dict(D)
assert len(proj) == 6
assert len(proj.geometries().values()) == 2
assert len(proj.phases().values()) == 1
assert len(proj.physics().values()) == 2
def test_from_dict_not_interleaved_not_flatted_cat_by_obj_data_elem(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1],
flatten=False, interleave=False,
categorize_by=['object', 'element', 'data'])
# Ensure that data and element categorizations are ripped out
proj = Dict.from_dict(D)
assert len(proj) == 6
assert len(proj.geometries().values()) == 2
assert len(proj.phases().values()) == 1
assert len(proj.physics().values()) == 2
def test_from_dict_not_interleaved_not_flatted_not_categorized(self):
D = Dict.to_dict(network=self.net, phases=[self.phase_1],
flatten=False, interleave=False,
categorize_by=[])
proj = Dict.from_dict(D)
assert len(proj) == 6
assert len(proj.geometries().values()) == 0
assert len(proj.phases().values()) == 0
assert len(proj.physics().values()) == 0
def test_save_and_load(self, tmpdir):
D = Dict.to_dict(network=self.net, phases=[self.phase_1],
flatten=False, interleave=False,
categorize_by=[])
fname = tmpdir.join('test.dct')
Dict.export_data(dct=D, filename=fname)
dct = Dict.import_data(filename=fname)
assert len(dct.keys()) == 2
os.remove(fname)
if __name__ == '__main__':
t = DictTest()
self = t
t.setup_class()
for item in t.__dir__():
if item.startswith('test'):
print('running test: '+item)
try:
t.__getattribute__(item)()
except TypeError:
t.__getattribute__(item)(tmpdir=py.path.local())
| |
#!/usr/bin/env python
#
# Copyright (c) 2014, Arista Networks, 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 Arista Networks 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 ARISTA NETWORKS
# 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.
#pylint: disable=R0904,F0401,W0232,E1101
#sys.path.append(os.path.join('..', 'rphm'))
import unittest
from rphm import app
class StatMonTests(unittest.TestCase):
"""Unittests for rphm
"""
def setUp(self):
self.device = {'alignmenterrors': '1',
'authpassword': '',
'authprotocol': 'SHA',
'collisions': '1',
'community': 'public',
'contextname': '',
'counters': ['inUcastPkts', 'inDiscards'],
'deferredtransmissions': '1',
'fcserrors': '1',
'giantframes': '1',
'hostname': '10.10.10.11',
'indiscards': '1',
'interfaces': ['Management 1'],
'inucastpkts': '1',
'latecollisions': '1',
'name': 'vEOS-1',
'password': 'arista',
'port': '443',
'privpassword': '',
'privprotocol': 'AES',
'protocol': 'https',
'runtframes': '1',
'rxpause': '1',
'seclevel': 'authPriv',
'symbolerrors': '1',
'traphost': 'localhost',
'txpause': '1',
'url': 'https://arista:arista@10.10.10.11:443/command-api',
'username': 'arista',
'version': '2c'}
self.reference = {'Management 1': {u'autoNegotiate': u'success',
u'bandwidth': 100000000,
u'burnedInAddress': u'08:00:27:72:f6:77',
u'description': u'My mgmt descr',
u'duplex': u'duplexFull',
u'forwardingModel': u'routed',
u'hardware': u'ethernet',
u'interfaceAddress': [{u'broadcastAddress': u'255.255.255.255',
u'primaryIp': {u'address': u'10.10.10.11',
u'maskLen': 24},
u'secondaryIps': {},
u'secondaryIpsOrderedList': []}],
u'interfaceCounters': {u'counterRefreshTime': 1407725658.76,
u'inBroadcastPkts': 0,
u'inDiscards': 0,
u'inMulticastPkts': 0,
u'inOctets': 0,
u'inUcastPkts': 0,
u'inputErrorsDetail': {u'alignmentErrors': 0,
u'fcsErrors': 0,
u'giantFrames': 0,
u'runtFrames': 0,
u'rxPause': 0,
u'symbolErrors': 0},
u'linkStatusChanges': 3,
u'outBroadcastPkts': 0,
u'outDiscards': 0,
u'outMulticastPkts': 0,
u'outOctets': 0,
u'outUcastPkts': 0,
u'outputErrorsDetail': {u'collisions': 0,
u'deferredTransmissions': 0,
u'lateCollisions': 0,
u'txPause': 0},
u'totalInErrors': 0,
u'totalOutErrors': 0},
u'interfaceStatistics': {u'inBitsRate': 0.0,
u'inPktsRate': 0.0,
u'outBitsRate': 0.0,
u'outPktsRate': 0.0,
u'updateInterval': 300.0},
u'interfaceStatus': u'connected',
u'lastStatusChangeTimestamp': 1407724637.35,
u'lineProtocolStatus': u'up',
u'mtu': 1500,
u'name': u'Management1',
u'physicalAddress': u'08:00:27:72:f6:77'}}
self.current = {'Management 1': {u'autoNegotiate': u'success',
u'bandwidth': 100000000,
u'burnedInAddress': u'08:00:27:72:f6:77',
u'description': u'My mgmt descr',
u'duplex': u'duplexFull',
u'forwardingModel': u'routed',
u'hardware': u'ethernet',
u'interfaceAddress': [{u'broadcastAddress': u'255.255.255.255',
u'primaryIp': {u'address': u'10.10.10.11',
u'maskLen': 24},
u'secondaryIps': {},
u'secondaryIpsOrderedList': []}],
u'interfaceCounters': {u'counterRefreshTime': 1407725658.76,
u'inBroadcastPkts': 0,
u'inDiscards': 0,
u'inMulticastPkts': 0,
u'inOctets': 0,
u'inUcastPkts': 0,
u'inputErrorsDetail': {u'alignmentErrors': 0,
u'fcsErrors': 0,
u'giantFrames': 0,
u'runtFrames': 0,
u'rxPause': 0,
u'symbolErrors': 0},
u'linkStatusChanges': 3,
u'outBroadcastPkts': 0,
u'outDiscards': 0,
u'outMulticastPkts': 0,
u'outOctets': 0,
u'outUcastPkts': 0,
u'outputErrorsDetail': {u'collisions': 0,
u'deferredTransmissions': 0,
u'lateCollisions': 0,
u'txPause': 0},
u'totalInErrors': 0,
u'totalOutErrors': 0},
u'interfaceStatistics': {u'inBitsRate': 0.0,
u'inPktsRate': 0.0,
u'outBitsRate': 0.0,
u'outPktsRate': 0.0,
u'updateInterval': 300.0},
u'interfaceStatus': u'connected',
u'lastStatusChangeTimestamp': 1407724637.35,
u'lineProtocolStatus': u'up',
u'mtu': 1500,
u'name': u'Management1',
u'physicalAddress': u'08:00:27:72:f6:77'}}
self.good_result = {'Management1': {u'inDiscards': {'found': 0, 'threshold': '1'},
u'inUcastPkts': {'found': 0, 'threshold': '1'}}}
self.equal_result = {}
def test_log_error(self):
app.log("test message", error=True)
# TODO Need to actually validate STDOUT and the syslog level
def test_remove_unneded_keys(self):
input_dict = {'section 1': {'a': 0,
'b': 1,
'c': 2},
'section 2': {'a': 3,
'b': 4,
'c': 5}}
extrakeys = ['a', 'c']
expected_dict = {'section 1': {'b': 1},
'section 2': {'b': 4}}
app.remove_unneded_keys(extrakeys, input_dict)
self.assertEqual(input_dict, expected_dict)
def test_compare_counters_equal(self):
result = app.compare_counters(self.device, self.reference,
self.reference)
self.assertEqual(result, {})
def test_compare_counters_missing_interface(self):
current = dict(self.current)
current.pop('Management 1')
result = app.compare_counters(self.device, self.reference, current)
self.assertEqual(result, {})
def test_compare_counters_difference(self):
device = dict(self.device)
current = dict(self.current)
#Add a counter to test and set a threshold for it.
counter = 'giantFrames'
device['counters'].append(counter)
thresh = '1'
# must be all lowercase due to ConfigParser
device[counter.lower()] = thresh
# Add a rnd number to the reference for that counter and store it
# in current.
from random import randrange
val = randrange(int(thresh), 20)
print "Tried random increment of {0}".format(val)
current['Management 1'][u'interfaceCounters'][u'inputErrorsDetail']\
[counter] = int(self.reference['Management 1']\
[u'interfaceCounters'][u'inputErrorsDetail']\
[counter]) + val
# Call the routine
result = app.compare_counters(device, self.reference, current)
self.assertEqual(result, {'Management 1': {counter: {'found': val, 'threshold': int(thresh), 'direction': 'in', 'total': 0}}})
def test_is_delta_significant_equal(self):
device = dict(self.device)
#Add a counter to test and set a threshold for it.
counter = 'giantFrames'
device['counters'].append(counter)
thresh = '1'
# must be all lowercase due to ConfigParser
device[counter.lower()] = thresh
from random import randrange
val = randrange(20)
print "Selected increment of {0}".format(val)
# Call the routine
result = app.is_delta_significant(device, counter, val, val)
self.assertEqual(result, None)
def test_is_delta_significant_invalid_counter_name(self):
device = dict(self.device)
#Add a counter to test and set a threshold for it.
counter = 'giantFrogs'
#device['counters'].append(counter)
thresh = '1'
# must be all lowercase due to ConfigParser
device[counter.lower()] = thresh
from random import randrange
val = randrange(20)
print "Selected increment of {0}".format(val)
# Call the routine
result = app.is_delta_significant(device, counter, val, val)
self.assertEqual(result, None)
def test_is_delta_significant_difference(self):
device = dict(self.device)
#current = dict(self.current)
#Add a counter to test and set a threshold for it.
counter = 'giantFrames'
device['counters'].append(counter)
thresh = '1'
# must be all lowercase due to ConfigParser
device[counter.lower()] = thresh
# Add a rnd number to the reference for that counter and store it
# in current.
from random import randrange
val = randrange(int(thresh), 20)
print "Selected increment of {0}".format(val)
ref = int(self.reference['Management 1'][u'interfaceCounters']\
[u'inputErrorsDetail'][counter])
cur = ref + val
# Call the routine
result = app.is_delta_significant(device, counter, ref, cur)
self.assertEqual(result, {'found': val, 'threshold': int(thresh), 'direction': 'in', 'total': 0})
class GetDataTests(unittest.TestCase):
"""Unittests for rphm
"""
def setUp(self):
""" Test the get_interfaces stuff
"""
self.device = {'alignmenterrors': '1',
'authpassword': '',
'authprotocol': 'SHA',
'collisions': '1',
'community': 'public',
'contextname': '',
'counters': ['inUcastPkts', 'inDiscards'],
'deferredtransmissions': '1',
'fcserrors': '1',
'giantframes': '1',
'hostname': '10.10.10.11',
'indiscards': '1',
'interfaces': ['Management 1'],
'inucastpkts': '1',
'latecollisions': '1',
'name': 'vEOS-1',
'password': 'arista',
'port': '443',
'privpassword': '',
'privprotocol': 'AES',
'protocol': 'https',
'runtframes': '1',
'rxpause': '1',
'seclevel': 'authPriv',
'symbolerrors': '1',
'traphost': 'localhost',
'txpause': '1',
'url': 'https://arista:arista@10.10.10.11:443/command-api',
'username': 'arista',
'version': '2c'}
self.reference = {'Management1': {u'autoNegotiate': u'success',
u'bandwidth': 100000000,
u'burnedInAddress': u'08:00:27:72:f6:77',
u'description': u'My mgmt descr',
u'duplex': u'duplexFull',
u'forwardingModel': u'routed',
u'hardware': u'ethernet',
u'interfaceAddress': [{u'broadcastAddress': u'255.255.255.255',
u'primaryIp': {u'address': u'10.10.10.11',
u'maskLen': 24},
u'secondaryIps': {},
u'secondaryIpsOrderedList': []}],
u'interfaceCounters': {u'counterRefreshTime': 1407725658.76,
u'inBroadcastPkts': 0,
u'inDiscards': 0,
u'inMulticastPkts': 0,
u'inOctets': 0,
u'inUcastPkts': 0,
u'inputErrorsDetail': {u'alignmentErrors': 0,
u'fcsErrors': 0,
u'giantFrames': 0,
u'runtFrames': 0,
u'rxPause': 0,
u'symbolErrors': 0},
u'linkStatusChanges': 3,
u'outBroadcastPkts': 0,
u'outDiscards': 0,
u'outMulticastPkts': 0,
u'outOctets': 0,
u'outUcastPkts': 0,
u'outputErrorsDetail': {u'collisions': 0,
u'deferredTransmissions': 0,
u'lateCollisions': 0,
u'txPause': 0},
u'totalInErrors': 0,
u'totalOutErrors': 0},
u'interfaceStatistics': {u'inBitsRate': 0.0,
u'inPktsRate': 0.0,
u'outBitsRate': 0.0,
u'outPktsRate': 0.0,
u'updateInterval': 300.0},
u'interfaceStatus': u'connected',
u'lastStatusChangeTimestamp': 1407724637.35,
u'lineProtocolStatus': u'up',
u'mtu': 1500,
u'name': u'Management1',
u'physicalAddress': u'08:00:27:72:f6:77'}}
self.int_status = {u'Ethernet1': {u'autoNegotigateActive': False,
u'bandwidth': 10000000000,
u'description': u'',
u'duplex': u'duplexFull',
u'interfaceType': u'EbraTestPhyPort',
u'linkStatus': u'connected',
u'vlanInformation': {u'interfaceForwardingModel': u'bridged',
u'interfaceMode': u'bridged',
u'vlanId': 1}},
u'Ethernet2': {u'autoNegotigateActive': False,
u'bandwidth': 10000000000,
u'description': u'',
u'duplex': u'duplexFull',
u'interfaceType': u'EbraTestPhyPort',
u'linkStatus': u'connected',
u'vlanInformation': {u'interfaceForwardingModel': u'bridged',
u'interfaceMode': u'bridged',
u'vlanId': 1}}}
self.counter_error = {"jsonrpc": "2.0",
"id": "CapiExplorer-123",
"error": {"data": [{"errors": ["Invalid input (at token 3: '1')"]}],
"message": "CLI command 1 of 1 'show interfaces Mac 1' failed: invalid command",
"code": 1002}
}
self.sh_ver = {"modelName": "vEOS",
"internalVersion": "4.13.6F-1754895.4136F.1",
"systemMacAddress": "08:00:27:27:8a:18",
"serialNumber": "",
"memTotal": 1001208,
"bootupTimestamp": 1408034881.09,
"memFree": 15100,
"version": "4.13.6F",
"architecture": "i386",
"internalBuildId": "3372c53e-4d0d-4a40-9183-6051aa07c429",
"hardwareRevision": ""}
def test_get_device_status_good(self):
""" Test get_device_status happy path
"""
from mock import MagicMock
from jsonrpclib import Server
device = dict(self.device)
sh_ver = dict(self.sh_ver)
# Arbitrary test valuse
model = "Monkey-bot"
timestamp = 1408034881.09
sh_ver['modelName'] = model
sh_ver['bootupTimestamp'] = timestamp
response = []
response.append(sh_ver)
device['eapi_obj'] = Server('https://arista:arista@10.10.10.11:443/command-api')
device['eapi_obj'].runCmds = MagicMock(return_value=response)
#response = []
#response.append({})
#response[0][u'interfaceStatuses'] = self.int_status
app.get_device_status(device)
self.assertEqual(device['modelName'], model)
self.assertEqual(device['bootupTimestamp'], timestamp)
def test_get_interfaces_good(self):
""" Test get_interfaces happy path
"""
from mock import MagicMock
from jsonrpclib import Server
switch = Server('https://arista:arista@10.10.10.11:443/command-api')
response = []
response.append({})
response[0][u'interfaceStatuses'] = self.int_status
switch.runCmds = MagicMock(return_value=response)
interfaces = app.get_interfaces(switch)
self.assertEqual(interfaces, self.int_status)
def test_get_intf_counters_default(self):
""" Test get_intf_counters with no interface specified
"""
from mock import MagicMock
from jsonrpclib import Server
switch = Server('https://arista:arista@10.10.10.11:443/command-api')
response = []
response.append({})
response[0][u'interfaces'] = self.reference
switch.runCmds = MagicMock(return_value=response)
(propername, counters) = app.get_intf_counters(switch)
self.assertDictEqual(counters, self.reference['Management1'])
#def test_get_device_counters_good(self):
# device = dict(self.device)
# from mock import MagicMock
# #from jsonrpclib import Server
# #device['eapi_obj'] = Server('https://arista:arista@10.10.10.11:443/command-api')
# #response = []
# #response.append({})
# #response[0][u'interfaces'] = self.reference
# #device['eapi_obj'].runCmds = MagicMock(return_value=response)
# response = dict(self.reference)
# app.get_intf_counters = MagicMock(return_value=('Management1', response)
# #(propername, counters) = app.get_intf_counters(switch)
# #self.assertDictEqual(counters, self.reference['Management1'])
# counters = app.get_device_counters(device)
# expected_counters = {}
# self.assertEqual(counters, expected_counters)
if __name__ == '__main__':
unittest.main()
| |
# Copyright (C) 2016-present MagicStack Inc. and the EdgeDB authors.
# Copyright (C) 2016-present the asyncpg authors 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.
#
"""PostgreSQL cluster management."""
from __future__ import annotations
from typing import *
import asyncio
import logging
import os
import os.path
import pathlib
import re
import shlex
import shutil
import textwrap
import time
import urllib.parse
import asyncpg
from edb import buildmeta
from edb.common import supervisor
from edb.common import uuidgen
from edb.server import defines
from edb.server.ha import base as ha_base
from edb.pgsql import common as pgcommon
from edb.pgsql import params as pgparams
from . import pgconnparams
logger = logging.getLogger('edb.pgcluster')
pg_dump_logger = logging.getLogger('pg_dump')
pg_ctl_logger = logging.getLogger('pg_ctl')
pg_config_logger = logging.getLogger('pg_config')
initdb_logger = logging.getLogger('initdb')
postgres_logger = logging.getLogger('postgres')
get_database_backend_name = pgcommon.get_database_backend_name
get_role_backend_name = pgcommon.get_role_backend_name
class ClusterError(Exception):
pass
class PostgresPidFileNotReadyError(Exception):
"""Raised on an attempt to read non-existent or bad Postgres PID file"""
class BaseCluster:
def __init__(
self,
*,
instance_params: Optional[pgparams.BackendInstanceParams] = None,
) -> None:
self._connection_addr: Optional[Tuple[str, int]] = None
self._connection_params: Optional[
pgconnparams.ConnectionParameters
] = None
self._default_session_auth: Optional[str] = None
self._pg_config_data: Dict[str, str] = {}
self._pg_bin_dir: Optional[pathlib.Path] = None
if instance_params is None:
self._instance_params = (
pgparams.get_default_runtime_params().instance_params)
else:
self._instance_params = instance_params
def get_db_name(self, db_name: str) -> str:
if (
not self._instance_params.capabilities
& pgparams.BackendCapabilities.CREATE_DATABASE
):
assert (
db_name == defines.EDGEDB_SUPERUSER_DB
), f"db_name={db_name} is not allowed"
rv = self.get_connection_params().database
assert rv is not None
return rv
return get_database_backend_name(
db_name,
tenant_id=self._instance_params.tenant_id,
)
def get_role_name(self, role_name: str) -> str:
if (
not self._instance_params.capabilities
& pgparams.BackendCapabilities.CREATE_ROLE
):
assert (
role_name == defines.EDGEDB_SUPERUSER
), f"role_name={role_name} is not allowed"
return self.get_connection_params().user
return get_database_backend_name(
role_name,
tenant_id=self._instance_params.tenant_id,
)
async def start(
self,
wait: int = 60,
*,
server_settings: Optional[Mapping[str, str]] = None,
**opts: Any,
) -> None:
raise NotImplementedError
async def stop(self, wait: int = 60) -> None:
raise NotImplementedError
def destroy(self) -> None:
raise NotImplementedError
async def connect(self, **kwargs: Any) -> asyncpg.Connection:
conn_info = self.get_connection_spec()
conn_info.update(kwargs)
if 'sslmode' in conn_info:
conn_info['ssl'] = conn_info.pop('sslmode').name
conn = await asyncpg.connect(**conn_info)
if (not kwargs.get('user')
and self._default_session_auth
and conn_info.get('user') != self._default_session_auth):
# No explicit user given, and the default
# SESSION AUTHORIZATION is different from the user
# used to connect.
await conn.execute(
f'SET ROLE {pgcommon.quote_ident(self._default_session_auth)}'
)
return conn
async def start_watching(
self, cluster_protocol: Optional[ha_base.ClusterProtocol] = None
) -> None:
pass
def stop_watching(self) -> None:
pass
def get_runtime_params(self) -> pgparams.BackendRuntimeParams:
params = self.get_connection_params()
login_role: Optional[str] = params.user
sup_role = self.get_role_name(defines.EDGEDB_SUPERUSER)
return pgparams.BackendRuntimeParams(
instance_params=self._instance_params,
session_authorization_role=(
None if login_role == sup_role else login_role
),
)
def overwrite_capabilities(
self, caps: pgparams.BackendCapabilities
) -> None:
self._instance_params = self._instance_params._replace(
capabilities=caps
)
def get_connection_addr(self) -> Optional[Tuple[str, int]]:
return self._get_connection_addr()
def set_default_session_authorization(self, rolename: str) -> None:
self._default_session_auth = rolename
def set_connection_params(
self,
params: pgconnparams.ConnectionParameters,
) -> None:
self._connection_params = params
def get_connection_params(
self,
) -> pgconnparams.ConnectionParameters:
assert self._connection_params is not None
return self._connection_params
def get_connection_spec(self) -> Dict[str, Any]:
conn_dict: Dict[str, Any] = {}
addr = self.get_connection_addr()
assert addr is not None
conn_dict['host'] = addr[0]
conn_dict['port'] = addr[1]
params = self.get_connection_params()
for k in (
'user',
'password',
'database',
'ssl',
'sslmode',
'server_settings',
):
v = getattr(params, k)
if v is not None:
conn_dict[k] = v
cluster_settings = conn_dict.get('server_settings', {})
edgedb_settings = {
'client_encoding': 'utf-8',
'search_path': 'edgedb',
'timezone': 'UTC',
'intervalstyle': 'iso_8601',
'jit': 'off',
}
conn_dict['server_settings'] = {**cluster_settings, **edgedb_settings}
return conn_dict
def _get_connection_addr(self) -> Optional[Tuple[str, int]]:
return self._connection_addr
def is_managed(self) -> bool:
raise NotImplementedError
async def get_status(self) -> str:
raise NotImplementedError
async def dump_database(
self,
dbname: str,
*,
exclude_schemas: Iterable[str] = (),
dump_object_owners: bool = True,
) -> bytes:
status = await self.get_status()
if status != 'running':
raise ClusterError('cannot dump: cluster is not running')
if self._pg_bin_dir is None:
await self.lookup_postgres()
pg_dump = self._find_pg_binary('pg_dump')
conn_spec = self.get_connection_spec()
args = [
pg_dump,
'--inserts',
f'--dbname={dbname}',
f'--host={conn_spec["host"]}',
f'--port={conn_spec["port"]}',
f'--username={conn_spec["user"]}',
]
if not dump_object_owners:
args.append('--no-owner')
env = os.environ.copy()
if conn_spec.get("password"):
env['PGPASSWORD'] = conn_spec["password"]
if exclude_schemas:
for exclude_schema in exclude_schemas:
args.append(f'--exclude-schema={exclude_schema}')
stdout_lines, _, _ = await _run_logged_subprocess(
args,
logger=pg_dump_logger,
log_stdout=False,
env=env,
)
return b'\n'.join(stdout_lines)
def _find_pg_binary(self, binary: str) -> str:
assert self._pg_bin_dir is not None
bpath = self._pg_bin_dir / binary
if not bpath.is_file():
raise ClusterError(
'could not find {} executable: '.format(binary) +
'{!r} does not exist or is not a file'.format(bpath))
return str(bpath)
def _subprocess_error(
self,
name: str,
exitcode: int,
stderr: Optional[bytes],
) -> ClusterError:
if stderr:
return ClusterError(
f'{name} exited with status {exitcode}:\n'
+ textwrap.indent(stderr.decode(), ' ' * 4),
)
else:
return ClusterError(
f'{name} exited with status {exitcode}',
)
async def lookup_postgres(self) -> None:
self._pg_bin_dir = await get_pg_bin_dir()
class Cluster(BaseCluster):
def __init__(
self,
data_dir: pathlib.Path,
*,
runstate_dir: Optional[pathlib.Path] = None,
instance_params: Optional[pgparams.BackendInstanceParams] = None,
log_level: str = 'i',
):
super().__init__(instance_params=instance_params)
self._data_dir = data_dir
self._runstate_dir = (
runstate_dir if runstate_dir is not None else data_dir)
self._daemon_pid: Optional[int] = None
self._daemon_process: Optional[asyncio.subprocess.Process] = None
self._daemon_supervisor: Optional[supervisor.Supervisor] = None
self._log_level = log_level
def is_managed(self) -> bool:
return True
def get_data_dir(self) -> pathlib.Path:
return self._data_dir
async def get_status(self) -> str:
stdout_lines, stderr_lines, exit_code = (
await _run_logged_text_subprocess(
[self._pg_ctl, 'status', '-D', str(self._data_dir)],
logger=pg_ctl_logger,
check=False,
)
)
if (
exit_code == 4
or not os.path.exists(self._data_dir)
or not os.listdir(self._data_dir)
):
return 'not-initialized'
elif exit_code == 3:
return 'stopped'
elif exit_code == 0:
output = '\n'.join(stdout_lines)
r = re.match(r'.*PID\s?:\s+(\d+).*', output)
if not r:
raise ClusterError(
f'could not parse pg_ctl status output: {output}')
self._daemon_pid = int(r.group(1))
if self._connection_addr is None:
self._connection_addr = self._connection_addr_from_pidfile()
return 'running'
else:
stderr_text = '\n'.join(stderr_lines)
raise ClusterError(
f'`pg_ctl status` exited with status {exit_code}:\n'
+ textwrap.indent(stderr_text, ' ' * 4),
)
async def ensure_initialized(self, **settings: Any) -> bool:
cluster_status = await self.get_status()
if cluster_status == 'not-initialized':
logger.info(
'Initializing database cluster in %s', self._data_dir)
have_c_utf8 = self.get_runtime_params().has_c_utf8_locale
await self.init(
username='postgres',
locale='C.UTF-8' if have_c_utf8 else 'en_US.UTF-8',
lc_collate='C',
encoding='UTF8',
)
self.reset_hba()
self.add_hba_entry(
type='local',
database='all',
user='postgres',
auth_method='trust'
)
return True
else:
return False
async def init(self, **settings: str) -> None:
"""Initialize cluster."""
if await self.get_status() != 'not-initialized':
raise ClusterError(
'cluster in {!r} has already been initialized'.format(
self._data_dir))
if settings:
settings_args = ['--{}={}'.format(k.replace('_', '-'), v)
for k, v in settings.items()]
extra_args = ['-o'] + [' '.join(settings_args)]
else:
extra_args = []
await _run_logged_subprocess(
[self._pg_ctl, 'init', '-D', str(self._data_dir)] + extra_args,
logger=initdb_logger,
)
async def start(
self,
wait: int = 60,
*,
server_settings: Optional[Mapping[str, str]] = None,
**opts: str,
) -> None:
"""Start the cluster."""
status = await self.get_status()
if status == 'running':
return
elif status == 'not-initialized':
raise ClusterError(
'cluster in {!r} has not been initialized'.format(
self._data_dir))
extra_args = ['--{}={}'.format(k, v) for k, v in opts.items()]
start_settings = {
'listen_addresses': '', # we use Unix sockets
'unix_socket_permissions': '0700',
'unix_socket_directories': str(self._runstate_dir),
# here we are not setting superuser_reserved_connections because
# we're using superuser only now (so all connections available),
# and we don't support reserving connections for now
'max_connections': str(self._instance_params.max_connections),
# From Postgres docs:
#
# You might need to raise this value if you have queries that
# touch many different tables in a single transaction, e.g.,
# query of a parent table with many children.
#
# EdgeDB queries might touch _lots_ of tables, especially in deep
# inheritance hierarchies. This is especially important in low
# `max_connections` scenarios.
'max_locks_per_transaction': 256,
}
if os.getenv('EDGEDB_DEBUG_PGSERVER'):
start_settings['log_min_messages'] = 'info'
start_settings['log_statement'] = 'all'
else:
log_level_map = {
'd': 'INFO',
'i': 'NOTICE',
'w': 'WARNING',
'e': 'ERROR',
's': 'PANIC',
}
start_settings['log_min_messages'] = log_level_map[self._log_level]
start_settings['log_statement'] = 'none'
start_settings['log_line_prefix'] = ''
if server_settings:
start_settings.update(server_settings)
ssl_key = start_settings.get('ssl_key_file')
if ssl_key:
# Make sure server certificate key file has correct permissions.
keyfile = os.path.join(self._data_dir, 'srvkey.pem')
assert isinstance(ssl_key, str)
shutil.copy(ssl_key, keyfile)
os.chmod(keyfile, 0o600)
start_settings['ssl_key_file'] = keyfile
for k, v in start_settings.items():
extra_args.extend(['-c', '{}={}'.format(k, v)])
self._daemon_process, *loggers = await _start_logged_subprocess(
[self._postgres, '-D', str(self._data_dir), *extra_args],
capture_stdout=False,
capture_stderr=False,
logger=postgres_logger,
log_processor=postgres_log_processor,
)
self._daemon_pid = self._daemon_process.pid
sup = await supervisor.Supervisor.create(name="postgres loggers")
for logger_coro in loggers:
sup.create_task(logger_coro)
self._daemon_supervisor = sup
await self._test_connection(timeout=wait)
async def reload(self) -> None:
"""Reload server configuration."""
status = await self.get_status()
if status != 'running':
raise ClusterError('cannot reload: cluster is not running')
await _run_logged_subprocess(
[self._pg_ctl, 'reload', '-D', str(self._data_dir)],
logger=pg_ctl_logger,
)
async def stop(self, wait: int = 60) -> None:
await _run_logged_subprocess(
[
self._pg_ctl,
'stop', '-D', str(self._data_dir),
'-t', str(wait), '-m', 'fast'
],
logger=pg_ctl_logger,
)
if (
self._daemon_process is not None and
self._daemon_process.returncode is None
):
self._daemon_process.terminate()
await asyncio.wait_for(self._daemon_process.wait(), timeout=wait)
if self._daemon_supervisor is not None:
await self._daemon_supervisor.cancel()
self._daemon_supervisor = None
def destroy(self) -> None:
shutil.rmtree(self._data_dir)
def reset_hba(self) -> None:
"""Remove all records from pg_hba.conf."""
pg_hba = os.path.join(self._data_dir, 'pg_hba.conf')
try:
with open(pg_hba, 'w'):
pass
except IOError as e:
raise ClusterError(
'cannot modify HBA records: {}'.format(e)) from e
def add_hba_entry(
self,
*,
type: str = 'host',
database: str,
user: str,
address: Optional[str] = None,
auth_method: str,
auth_options: Optional[Mapping[str, Any]] = None,
) -> None:
"""Add a record to pg_hba.conf."""
if type not in {'local', 'host', 'hostssl', 'hostnossl'}:
raise ValueError('invalid HBA record type: {!r}'.format(type))
pg_hba = os.path.join(self._data_dir, 'pg_hba.conf')
record = '{} {} {}'.format(type, database, user)
if type != 'local':
if address is None:
raise ValueError(
'{!r} entry requires a valid address'.format(type))
else:
record += ' {}'.format(address)
record += ' {}'.format(auth_method)
if auth_options is not None:
record += ' ' + ' '.join(
'{}={}'.format(k, v) for k, v in auth_options.items())
try:
with open(pg_hba, 'a') as f:
print(record, file=f)
except IOError as e:
raise ClusterError(
'cannot modify HBA records: {}'.format(e)) from e
async def trust_local_connections(self) -> None:
self.reset_hba()
self.add_hba_entry(type='local', database='all',
user='all', auth_method='trust')
self.add_hba_entry(type='host', address='127.0.0.1/32',
database='all', user='all',
auth_method='trust')
self.add_hba_entry(type='host', address='::1/128',
database='all', user='all',
auth_method='trust')
status = await self.get_status()
if status == 'running':
await self.reload()
async def lookup_postgres(self) -> None:
await super().lookup_postgres()
self._pg_ctl = self._find_pg_binary('pg_ctl')
self._postgres = self._find_pg_binary('postgres')
def _get_connection_addr(self) -> Tuple[str, int]:
if self._connection_addr is None:
self._connection_addr = self._connection_addr_from_pidfile()
return self._connection_addr
def _connection_addr_from_pidfile(self) -> Tuple[str, int]:
pidfile = os.path.join(self._data_dir, 'postmaster.pid')
try:
with open(pidfile, 'rt') as f:
piddata = f.read()
except FileNotFoundError:
raise PostgresPidFileNotReadyError
lines = piddata.splitlines()
if len(lines) < 6:
# A complete postgres pidfile is at least 6 lines
raise PostgresPidFileNotReadyError
pmpid = int(lines[0])
if self._daemon_pid and pmpid != self._daemon_pid:
# This might be an old pidfile left from previous postgres
# daemon run.
raise PostgresPidFileNotReadyError
portnum = int(lines[3])
sockdir = lines[4]
hostaddr = lines[5]
if sockdir:
if sockdir[0] != '/':
# Relative sockdir
sockdir = os.path.normpath(
os.path.join(self._data_dir, sockdir))
host_str = sockdir
elif hostaddr:
host_str = hostaddr
else:
raise PostgresPidFileNotReadyError
if host_str == '*':
host_str = 'localhost'
elif host_str == '0.0.0.0':
host_str = '127.0.0.1'
elif host_str == '::':
host_str = '::1'
return (host_str, portnum)
async def _test_connection(self, timeout: int = 60) -> str:
self._connection_addr = None
connected = False
for n in range(timeout + 1):
# pg usually comes up pretty quickly, but not so
# quickly that we don't hit the wait case. Make our
# first sleep pretty short, to shave almost a second
# off the happy case.
sleep_time = 1 if n else 0.10
try:
conn_addr = self._get_connection_addr()
except PostgresPidFileNotReadyError:
time.sleep(sleep_time)
continue
try:
con = await asyncpg.connect(
database='postgres',
user='postgres',
timeout=5,
host=conn_addr[0],
port=conn_addr[1],
)
except (
OSError,
asyncio.TimeoutError,
asyncpg.CannotConnectNowError,
asyncpg.PostgresConnectionError,
):
time.sleep(sleep_time)
continue
except asyncpg.PostgresError:
# Any other error other than ServerNotReadyError or
# ConnectionError is interpreted to indicate the server is
# up.
break
else:
connected = True
await con.close()
break
if connected:
return 'running'
else:
return 'not-initialized'
class RemoteCluster(BaseCluster):
def __init__(
self,
addr: Tuple[str, int],
params: pgconnparams.ConnectionParameters,
*,
instance_params: Optional[pgparams.BackendInstanceParams] = None,
ha_backend: Optional[ha_base.HABackend] = None,
):
super().__init__(instance_params=instance_params)
self._connection_addr = addr
self._connection_params = params
self._ha_backend = ha_backend
def _get_connection_addr(self) -> Optional[Tuple[str, int]]:
if self._ha_backend is not None:
return self._ha_backend.get_master_addr()
return self._connection_addr
async def ensure_initialized(self, **settings: Any) -> bool:
return False
def is_managed(self) -> bool:
return False
async def get_status(self) -> str:
return 'running'
def init(self, **settings: str) -> str:
pass
async def start(
self,
wait: int = 60,
*,
server_settings: Optional[Mapping[str, str]] = None,
**opts: Any,
) -> None:
pass
async def stop(self, wait: int = 60) -> None:
pass
def destroy(self) -> None:
pass
def reset_hba(self) -> None:
raise ClusterError('cannot modify HBA records of unmanaged cluster')
def add_hba_entry(
self,
*,
type: str = 'host',
database: str,
user: str,
address: Optional[str] = None,
auth_method: str,
auth_options: Optional[Mapping[str, Any]] = None,
) -> None:
raise ClusterError('cannot modify HBA records of unmanaged cluster')
async def start_watching(
self, cluster_protocol: Optional[ha_base.ClusterProtocol] = None
) -> None:
if self._ha_backend is not None:
await self._ha_backend.start_watching(cluster_protocol)
def stop_watching(self) -> None:
if self._ha_backend is not None:
self._ha_backend.stop_watching()
async def get_pg_bin_dir() -> pathlib.Path:
pg_config_data = await get_pg_config()
pg_bin_dir = pg_config_data.get('bindir')
if not pg_bin_dir:
raise ClusterError(
'pg_config output did not provide the BINDIR value')
return pathlib.Path(pg_bin_dir)
async def get_pg_config() -> Dict[str, str]:
stdout_lines, _, _ = await _run_logged_text_subprocess(
[str(buildmeta.get_pg_config_path())],
logger=pg_config_logger,
)
config = {}
for line in stdout_lines:
k, eq, v = line.partition('=')
if eq:
config[k.strip().lower()] = v.strip()
return config
async def get_local_pg_cluster(
data_dir: pathlib.Path,
*,
runstate_dir: Optional[pathlib.Path] = None,
max_connections: Optional[int] = None,
tenant_id: Optional[str] = None,
log_level: Optional[str] = None,
) -> Cluster:
if log_level is None:
log_level = 'i'
if tenant_id is None:
tenant_id = buildmeta.get_default_tenant_id()
instance_params = None
if max_connections is not None:
instance_params = pgparams.get_default_runtime_params(
max_connections=max_connections,
tenant_id=tenant_id,
).instance_params
cluster = Cluster(
data_dir=data_dir,
runstate_dir=runstate_dir,
instance_params=instance_params,
log_level=log_level,
)
await cluster.lookup_postgres()
return cluster
async def get_remote_pg_cluster(
dsn: str,
*,
tenant_id: Optional[str] = None,
) -> RemoteCluster:
parsed = urllib.parse.urlparse(dsn)
ha_backend = None
if parsed.scheme not in {'postgresql', 'postgres'}:
ha_backend = ha_base.get_backend(parsed)
if ha_backend is None:
raise ValueError(
'invalid DSN: scheme is expected to be "postgresql", '
'"postgres" or one of the supported HA backend, '
'got {!r}'.format(parsed.scheme))
addr = await ha_backend.get_cluster_consensus()
dsn = 'postgresql://{}:{}'.format(*addr)
addrs, params = pgconnparams.parse_dsn(dsn)
if len(addrs) > 1:
raise ValueError('multiple hosts in Postgres DSN are not supported')
if tenant_id is None:
t_id = buildmeta.get_default_tenant_id()
else:
t_id = tenant_id
rcluster = RemoteCluster(addrs[0], params)
async def _get_cluster_type(
conn: asyncpg.Connection,
) -> Tuple[Type[RemoteCluster], Optional[str]]:
managed_clouds = {
'rds_superuser': RemoteCluster, # Amazon RDS
'cloudsqlsuperuser': RemoteCluster, # GCP Cloud SQL
'azure_pg_admin': RemoteCluster, # Azure Postgres
}
managed_cloud_super = await conn.fetchval(
"""
SELECT
rolname
FROM
pg_roles
WHERE
rolname = any($1::text[])
LIMIT
1
""",
list(managed_clouds),
)
if managed_cloud_super is not None:
return managed_clouds[managed_cloud_super], managed_cloud_super
else:
return RemoteCluster, None
async def _detect_capabilities(
conn: asyncpg.Connection,
) -> pgparams.BackendCapabilities:
caps = pgparams.BackendCapabilities.NONE
try:
cur_cluster_name = await conn.fetchval(f'''
SELECT
setting
FROM
pg_file_settings
WHERE
setting = 'cluster_name'
AND sourcefile = ((
SELECT setting
FROM pg_settings WHERE name = 'data_directory'
) || '/postgresql.auto.conf')
''')
except asyncpg.InsufficientPrivilegeError:
configfile_access = False
else:
try:
await conn.execute(f"""
ALTER SYSTEM SET cluster_name = 'edgedb-test'
""")
except asyncpg.InsufficientPrivilegeError:
configfile_access = False
except asyncpg.InternalServerError as e:
# Stolon keeper symlinks postgresql.auto.conf to /dev/null
# making ALTER SYSTEM fail with InternalServerError,
# see https://github.com/sorintlab/stolon/pull/343
if 'could not fsync file "postgresql.auto.conf"' in e.args[0]:
configfile_access = False
else:
raise
else:
configfile_access = True
if cur_cluster_name:
await conn.execute(f"""
ALTER SYSTEM SET cluster_name =
'{pgcommon.quote_literal(cur_cluster_name)}'
""")
else:
await conn.execute(f"""
ALTER SYSTEM SET cluster_name = DEFAULT
""")
if configfile_access:
caps |= pgparams.BackendCapabilities.CONFIGFILE_ACCESS
tx = conn.transaction()
await tx.start()
rname = str(uuidgen.uuid1mc())
try:
await conn.execute(f'CREATE ROLE "{rname}" WITH SUPERUSER')
except asyncpg.InsufficientPrivilegeError:
can_make_superusers = False
else:
can_make_superusers = True
finally:
await tx.rollback()
if can_make_superusers:
caps |= pgparams.BackendCapabilities.SUPERUSER_ACCESS
coll = await conn.fetchval('''
SELECT collname FROM pg_collation
WHERE lower(replace(collname, '-', '')) = 'c.utf8' LIMIT 1;
''')
if coll is not None:
caps |= pgparams.BackendCapabilities.C_UTF8_LOCALE
roles = await conn.fetchrow('''
SELECT rolcreaterole, rolcreatedb FROM pg_roles
WHERE rolname = (SELECT current_user);
''')
if roles['rolcreaterole']:
caps |= pgparams.BackendCapabilities.CREATE_ROLE
if roles['rolcreatedb']:
caps |= pgparams.BackendCapabilities.CREATE_DATABASE
return caps
async def _get_pg_settings(
conn: asyncpg.Connection,
name: str,
) -> str:
return await conn.fetchval( # type: ignore
'SELECT setting FROM pg_settings WHERE name = $1', name
)
async def _get_reserved_connections(
conn: asyncpg.Connection,
) -> int:
rv = int(
await _get_pg_settings(conn, 'superuser_reserved_connections')
)
for name in [
'rds.rds_superuser_reserved_connections',
]:
value = await _get_pg_settings(conn, name)
if value:
rv += int(value)
return rv
conn = await rcluster.connect()
try:
user, dbname = await conn.fetchrow(
"SELECT current_user, current_database()"
)
cluster_type, superuser_name = await _get_cluster_type(conn)
max_connections = await _get_pg_settings(conn, 'max_connections')
capabilities = await _detect_capabilities(conn)
if t_id != buildmeta.get_default_tenant_id():
# GOTCHA: This tenant_id check cannot protect us from running
# multiple EdgeDB servers using the default tenant_id with
# different catalog versions on the same backend. However, that
# would fail during bootstrap in single-role/database mode.
if not capabilities & pgparams.BackendCapabilities.CREATE_ROLE:
raise ClusterError(
"The remote backend doesn't support CREATE ROLE; "
"multi-tenancy is disabled."
)
if not capabilities & pgparams.BackendCapabilities.CREATE_DATABASE:
raise ClusterError(
"The remote backend doesn't support CREATE DATABASE; "
"multi-tenancy is disabled."
)
parsed_ver = conn.get_server_version()
ver_string = conn.get_settings().server_version
instance_params = pgparams.BackendInstanceParams(
capabilities=capabilities,
version=pgparams.BackendVersion(
major=parsed_ver.major,
minor=parsed_ver.minor,
micro=parsed_ver.micro,
releaselevel=parsed_ver.releaselevel,
serial=parsed_ver.serial,
string=ver_string,
),
base_superuser=superuser_name,
max_connections=int(max_connections),
reserved_connections=await _get_reserved_connections(conn),
tenant_id=t_id,
)
finally:
await conn.close()
params.user = user
params.database = dbname
return cluster_type(
addrs[0],
params,
instance_params=instance_params,
ha_backend=ha_backend,
)
async def _run_logged_text_subprocess(
args: Sequence[str],
logger: logging.Logger,
level: int = logging.DEBUG,
check: bool = True,
log_stdout: bool = True,
timeout: Optional[float] = None,
**kwargs: Any,
) -> Tuple[List[str], List[str], int]:
stdout_lines, stderr_lines, exit_code = await _run_logged_subprocess(
args,
logger=logger,
level=level,
check=check,
log_stdout=log_stdout,
timeout=timeout,
**kwargs,
)
return (
[line.decode() for line in stdout_lines],
[line.decode() for line in stderr_lines],
exit_code,
)
async def _run_logged_subprocess(
args: Sequence[str],
logger: logging.Logger,
level: int = logging.DEBUG,
check: bool = True,
log_stdout: bool = True,
log_stderr: bool = True,
capture_stdout: bool = True,
capture_stderr: bool = True,
timeout: Optional[float] = None,
**kwargs: Any,
) -> Tuple[List[bytes], List[bytes], int]:
process, stdout_reader, stderr_reader = await _start_logged_subprocess(
args,
logger=logger,
level=level,
log_stdout=log_stdout,
log_stderr=log_stderr,
capture_stdout=capture_stdout,
capture_stderr=capture_stderr,
**kwargs,
)
exit_code, stdout_lines, stderr_lines = await asyncio.wait_for(
asyncio.gather(process.wait(), stdout_reader, stderr_reader),
timeout=timeout,
)
if exit_code != 0 and check:
stderr_text = b'\n'.join(stderr_lines).decode()
raise ClusterError(
f'{args[0]} exited with status {exit_code}:\n'
+ textwrap.indent(stderr_text, ' ' * 4),
)
else:
return stdout_lines, stderr_lines, exit_code
async def _start_logged_subprocess(
args: Sequence[str],
*,
logger: logging.Logger,
level: int = logging.DEBUG,
log_stdout: bool = True,
log_stderr: bool = True,
capture_stdout: bool = True,
capture_stderr: bool = True,
log_processor: Optional[Callable[[str], Tuple[str, int]]] = None,
**kwargs: Any,
) -> Tuple[
asyncio.subprocess.Process,
Coroutine[Any, Any, List[bytes]],
Coroutine[Any, Any, List[bytes]],
]:
logger.log(
level,
f'running `{" ".join(shlex.quote(arg) for arg in args)}`'
)
process = await asyncio.create_subprocess_exec(
*args,
stdout=(
asyncio.subprocess.PIPE if log_stdout or capture_stdout
else asyncio.subprocess.DEVNULL
),
stderr=(
asyncio.subprocess.PIPE if log_stderr or capture_stderr
else asyncio.subprocess.DEVNULL
),
**kwargs,
)
assert process.stderr is not None
assert process.stdout is not None
if log_stderr and capture_stderr:
stderr_reader = _capture_and_log_subprocess_output(
process.pid,
process.stderr,
logger,
level,
log_processor,
)
elif capture_stderr:
stderr_reader = _capture_subprocess_output(process.stderr)
elif log_stderr:
stderr_reader = _log_subprocess_output(
process.pid, process.stderr, logger, level, log_processor)
else:
stderr_reader = _dummy()
if log_stdout and capture_stdout:
stdout_reader = _capture_and_log_subprocess_output(
process.pid,
process.stdout,
logger,
level,
log_processor,
)
elif capture_stdout:
stdout_reader = _capture_subprocess_output(process.stdout)
elif log_stdout:
stdout_reader = _log_subprocess_output(
process.pid, process.stdout, logger, level, log_processor)
else:
stdout_reader = _dummy()
return process, stdout_reader, stderr_reader
async def _capture_subprocess_output(
stream: asyncio.StreamReader,
) -> List[bytes]:
lines = []
while not stream.at_eof():
line = await stream.readline()
if line or not stream.at_eof():
lines.append(line.rstrip(b'\n'))
return lines
async def _capture_and_log_subprocess_output(
pid: int,
stream: asyncio.StreamReader,
logger: logging.Logger,
level: int,
log_processor: Optional[Callable[[str], Tuple[str, int]]] = None,
) -> List[bytes]:
lines = []
while not stream.at_eof():
line = await stream.readline()
if line or not stream.at_eof():
line = line.rstrip(b'\n')
lines.append(line)
log_line = line.decode()
if log_processor is not None:
log_line, level = log_processor(log_line)
logger.log(level, log_line, extra={"process": pid})
return lines
async def _log_subprocess_output(
pid: int,
stream: asyncio.StreamReader,
logger: logging.Logger,
level: int,
log_processor: Optional[Callable[[str], Tuple[str, int]]] = None,
) -> List[bytes]:
while not stream.at_eof():
line = await stream.readline()
if line or not stream.at_eof():
log_line = line.rstrip(b'\n').decode()
if log_processor is not None:
log_line, level = log_processor(log_line)
logger.log(level, log_line, extra={"process": pid})
return []
async def _dummy() -> List[bytes]:
return []
postgres_to_python_level_map = {
"DEBUG5": logging.DEBUG,
"DEBUG4": logging.DEBUG,
"DEBUG3": logging.DEBUG,
"DEBUG2": logging.DEBUG,
"DEBUG1": logging.DEBUG,
"INFO": logging.INFO,
"NOTICE": logging.INFO,
"LOG": logging.INFO,
"WARNING": logging.WARNING,
"ERROR": logging.ERROR,
"FATAL": logging.CRITICAL,
"PANIC": logging.CRITICAL,
}
postgres_log_re = re.compile(r'^(\w+):\s*(.*)$')
postgres_specific_msg_level_map = {
"terminating connection due to administrator command": logging.INFO,
"the database system is shutting down": logging.INFO,
}
def postgres_log_processor(msg: str) -> Tuple[str, int]:
if m := postgres_log_re.match(msg):
postgres_level = m.group(1)
msg = m.group(2)
level = postgres_specific_msg_level_map.get(
msg,
postgres_to_python_level_map.get(postgres_level, logging.INFO),
)
else:
level = logging.INFO
return msg, level
| |
"""
Copyright (c) 2017, Jose Dolz .All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
NOTES: There are still some functionalities to be implemented.
- Add pooling layer in 3D
- Add more activation functions
- Add more optimizers (ex. Adam)
Jose Dolz. Oct, 2017.
email: jose.dolz.upv@gmail.com
LIVIA Department, ETS, Montreal.
"""
import numpy
import numpy as np
import theano
import theano.tensor as T
from theano.tensor.nnet import conv
import random
from math import floor
from math import ceil
from Modules.General.Utils import computeReceptiveField
from Modules.General.Utils import extendLearningRateToParams
from Modules.General.Utils import extractCenterFeatMaps
from Modules.General.Utils import getCentralVoxels
from Modules.General.Utils import getWeightsSet
import LiviaNet3DConvLayer
import LiviaSoftmax
import pdb
#####################################################
# ------------------------------------------------- #
## ## ## ## LIVIA-SemiDenseNET 3D ## ## ## ##
# ------------------------------------------------- #
#####################################################
class LiviaSemiDenseNet3D(object):
def __init__(self):
# --- containers for Theano compiled functions ----
self.networkModel_Train = ""
self.networkModel_Test = ""
# --- shared variables will be stored in the following variables ----
self.trainingData_x = ""
self.testingData_x = ""
self.trainingData_y = ""
self.trainingData_x_Bottom = ""
self.testingData_x_Bottom = ""
self.lastLayer = ""
self.networkLayers = []
self.intermediate_ConnectedLayers = []
self.networkName = ""
self.folderName = ""
self.cnnLayers = []
self.n_classes = -1
self.sampleSize_Train = []
self.sampleSize_Test = []
self.kernel_Shapes = []
self.pooling_scales = []
self.dropout_Rates = []
self.activationType = -1
self.weight_Initialization = -1
self.dropoutRates = []
self.batch_Size = -1
self.receptiveField = 0
self.initialLearningRate = ""
self.learning_rate = theano.shared(np.cast["float32"](0.01))
# Symbolic variables,
self.inputNetwork_Train = None
self.inputNetwork_Test = None
self.L1_reg_C = 0
self.L2_reg_C = 0
self.costFunction = 0
# Params for optimizers
self.initialMomentum = ""
self.momentum = theano.shared(np.cast["float32"](0.))
self.momentumNormalized = 0
self.momentumType = 0
self.vel_Momentum = []
self.rho_RMSProp = 0
self.epsilon_RMSProp = 0
self.params_RmsProp = []
self.numberOfEpochsTrained = 0
self.applyBatchNorm = ""
self.numberEpochToApplyBatchNorm = 0
self.softmax_Temp = 1.0
self.centralVoxelsTrain = ""
self.centralVoxelsTest = ""
# -------------------------------------------------------------------- END Function ------------------------------------------------------------------- #
""" ####### Function to generate the network architecture ######### """
def generateNetworkLayers(self,
cnnLayers,
kernel_Shapes,
maxPooling_Layer,
sampleShape_Train,
sampleShape_Test,
inputSample_Train,
inputSample_Train_Bottom,
inputSample_Test,
inputSample_Test_Bottom,
layersToConnect):
rng = np.random.RandomState(24575)
# Define inputs for first layers (which will be re-used for next layers)
inputSampleToNextLayer_Train = inputSample_Train
inputSampleToNextLayer_Test = inputSample_Test
inputSampleToNextLayer_Train_Bottom = inputSample_Train_Bottom
inputSampleToNextLayer_Test_Bottom = inputSample_Test_Bottom
inputSampleToNextLayerShape_Train = sampleShape_Train
inputSampleToNextLayerShape_Test = sampleShape_Test
# Get the convolutional layers
numLayers = len(kernel_Shapes)
numberCNNLayers = []
numberFCLayers = []
for l_i in range(1,len(kernel_Shapes)):
if len(kernel_Shapes[l_i]) == 3:
numberCNNLayers = l_i + 1
numberFCLayers = numLayers - numberCNNLayers
######### -------------- Generate the convolutional layers -------------- #########
# Some checks
if self.weight_Initialization_CNN == 2:
if len(self.weightsTrainedIdx) <> numberCNNLayers:
print(" ... WARNING!!!! Number of indexes specified for trained layers does not correspond with number of conv layers in the created architecture...")
if self.weight_Initialization_CNN == 2:
weightsNames = getWeightsSet(self.weightsFolderName, self.weightsTrainedIdx)
for l_i in xrange(0, numberCNNLayers) :
# Get properties of this layer
# The second element is the number of feature maps of previous layer
currentLayerKernelShape = [cnnLayers[l_i], inputSampleToNextLayerShape_Train[1]] + kernel_Shapes[l_i]
# If weights are going to be initialized from other pre-trained network they should be loaded in this stage
# Otherwise
weights = []
if self.weight_Initialization_CNN == 2:
weights = np.load(weightsNames[l_i])
maxPoolingParameters = []
dropoutRate = 0.0
### TOP ##
myLiviaNet3DConvLayerTop = LiviaNet3DConvLayer.LiviaNet3DConvLayer(rng,
l_i,
inputSampleToNextLayer_Train,
inputSampleToNextLayer_Test,
inputSampleToNextLayerShape_Train,
inputSampleToNextLayerShape_Test,
currentLayerKernelShape,
self.applyBatchNorm,
self.numberEpochToApplyBatchNorm,
maxPoolingParameters,
self.weight_Initialization_CNN,
weights,
self.activationType,
dropoutRate
)
self.networkLayers.append(myLiviaNet3DConvLayerTop)
## BOTTOM ##
myLiviaNet3DConvLayerBottom = LiviaNet3DConvLayer.LiviaNet3DConvLayer(rng,
l_i,
inputSampleToNextLayer_Train_Bottom,
inputSampleToNextLayer_Test_Bottom,
inputSampleToNextLayerShape_Train,
inputSampleToNextLayerShape_Test,
currentLayerKernelShape,
self.applyBatchNorm,
self.numberEpochToApplyBatchNorm,
maxPoolingParameters,
self.weight_Initialization_CNN,
weights,
self.activationType,
dropoutRate
)
self.networkLayers.append(myLiviaNet3DConvLayerBottom)
# Just for printing
inputSampleToNextLayer_Train_Old = inputSampleToNextLayerShape_Train
inputSampleToNextLayer_Test_Old = inputSampleToNextLayerShape_Test
# Update inputs for next layer
inputSampleToNextLayer_Train = myLiviaNet3DConvLayerTop.outputTrain
inputSampleToNextLayer_Test = myLiviaNet3DConvLayerTop.outputTest
inputSampleToNextLayer_Train_Bottom = myLiviaNet3DConvLayerBottom.outputTrain
inputSampleToNextLayer_Test_Bottom = myLiviaNet3DConvLayerBottom.outputTest
inputSampleToNextLayerShape_Train = myLiviaNet3DConvLayerTop.outputShapeTrain
inputSampleToNextLayerShape_Test = myLiviaNet3DConvLayerTop.outputShapeTest
print(" ----- (Training) Input shape: {} ---> Output shape: {} || kernel shape {}".format(inputSampleToNextLayer_Train_Old,inputSampleToNextLayerShape_Train, currentLayerKernelShape))
print(" ----- (Testing) Input shape: {} ---> Output shape: {}".format(inputSampleToNextLayer_Test_Old,inputSampleToNextLayerShape_Test))
### Create the semi-dense connectivity
centralVoxelsTrain = self.centralVoxelsTrain
centralVoxelsTest = self.centralVoxelsTest
numLayersPerPath = len(self.networkLayers)/2
featMapsInFullyCN = 0
# ------- TOP -------- #
print(" ----------- TOP PATH ----------------")
for l_i in xrange(0,numLayersPerPath-1) :
print(' --- concatennating layer {} ...'.format(str(l_i)))
currentLayer = self.networkLayers[2*l_i] # to access the layers from the top path
output_train = currentLayer.outputTrain
output_trainShape = currentLayer.outputShapeTrain
output_test = currentLayer.outputTest
output_testShape = currentLayer.outputShapeTest
# Get the middle part of feature maps at intermediate levels to make them of the same shape at the beginning of the
# first fully connected layer
featMapsCenter_Train = extractCenterFeatMaps(output_train, output_trainShape, centralVoxelsTrain)
featMapsCenter_Test = extractCenterFeatMaps(output_test, output_testShape, centralVoxelsTest)
featMapsInFullyCN = featMapsInFullyCN + currentLayer._numberOfFeatureMaps
inputSampleToNextLayer_Train = T.concatenate([inputSampleToNextLayer_Train, featMapsCenter_Train], axis=1)
inputSampleToNextLayer_Test = T.concatenate([inputSampleToNextLayer_Test, featMapsCenter_Test], axis=1)
# ------- Bottom -------- #
print(" ---------- BOTTOM PATH ---------------")
for l_i in xrange(0,numLayersPerPath-1) :
print(' --- concatennating layer {} ...'.format(str(l_i)))
currentLayer = self.networkLayers[2*l_i+1] # to access the layers from the bottom path
output_train = currentLayer.outputTrain
output_trainShape = currentLayer.outputShapeTrain
output_test = currentLayer.outputTest
output_testShape = currentLayer.outputShapeTest
# Get the middle part of feature maps at intermediate levels to make them of the same shape at the beginning of the
# first fully connected layer
featMapsCenter_Train = extractCenterFeatMaps(output_train, output_trainShape, centralVoxelsTrain)
featMapsCenter_Test = extractCenterFeatMaps(output_test, output_testShape, centralVoxelsTest)
featMapsInFullyCN = featMapsInFullyCN + currentLayer._numberOfFeatureMaps
inputSampleToNextLayer_Train_Bottom = T.concatenate([inputSampleToNextLayer_Train_Bottom, featMapsCenter_Train], axis=1)
inputSampleToNextLayer_Test_Bottom = T.concatenate([inputSampleToNextLayer_Test_Bottom, featMapsCenter_Test], axis=1)
######### -------------- Generate the Fully Connected Layers ----------------- ##################
inputToFullyCN_Train = inputSampleToNextLayer_Train
inputToFullyCN_Train = T.concatenate([inputToFullyCN_Train, inputSampleToNextLayer_Train_Bottom], axis=1)
inputToFullyCN_Test = inputSampleToNextLayer_Test
inputToFullyCN_Test = T.concatenate([inputToFullyCN_Test, inputSampleToNextLayer_Test_Bottom], axis=1)
featMapsInFullyCN = featMapsInFullyCN + inputSampleToNextLayerShape_Train[1] * 2 # Because we have two symmetric paths
# Define inputs
inputFullyCNShape_Train = [self.batch_Size, featMapsInFullyCN] + inputSampleToNextLayerShape_Train[2:5]
inputFullyCNShape_Test = [self.batch_Size, featMapsInFullyCN] + inputSampleToNextLayerShape_Test[2:5]
# Kamnitsas applied padding and mirroring to the images when kernels in FC layers were larger than 1x1x1.
# For this current work, we employed kernels of this size (i.e. 1x1x1), so there is no need to apply padding or mirroring.
# TODO. Check
print(" --- Starting to create the fully connected layers....")
for l_i in xrange(numberCNNLayers, numLayers) :
numberOfKernels = cnnLayers[l_i]
kernel_shape = [kernel_Shapes[l_i][0],kernel_Shapes[l_i][0],kernel_Shapes[l_i][0]]
currentLayerKernelShape = [cnnLayers[l_i], inputFullyCNShape_Train[1]] + kernel_shape
# If weights are going to be initialized from other pre-trained network they should be loaded in this stage
# Otherwise
weights = []
applyBatchNorm = True
epochsToApplyBatchNorm = 60
maxPoolingParameters = []
dropoutRate = self.dropout_Rates[l_i-numberCNNLayers]
myLiviaNet3DFullyConnectedLayer = LiviaNet3DConvLayer.LiviaNet3DConvLayer(rng,
l_i,
inputToFullyCN_Train,
inputToFullyCN_Test,
inputFullyCNShape_Train,
inputFullyCNShape_Test,
currentLayerKernelShape,
self.applyBatchNorm,
self.numberEpochToApplyBatchNorm,
maxPoolingParameters,
self.weight_Initialization_FCN,
weights,
self.activationType,
dropoutRate
)
self.networkLayers.append(myLiviaNet3DFullyConnectedLayer)
# Just for printing
inputFullyCNShape_Train_Old = inputFullyCNShape_Train
inputFullyCNShape_Test_Old = inputFullyCNShape_Test
# Update inputs for next layer
inputToFullyCN_Train = myLiviaNet3DFullyConnectedLayer.outputTrain
inputToFullyCN_Test = myLiviaNet3DFullyConnectedLayer.outputTest
inputFullyCNShape_Train = myLiviaNet3DFullyConnectedLayer.outputShapeTrain
inputFullyCNShape_Test = myLiviaNet3DFullyConnectedLayer.outputShapeTest
# Print
print(" ----- (Training) Input shape: {} ---> Output shape: {} || kernel shape {}".format(inputFullyCNShape_Train_Old,inputFullyCNShape_Train, currentLayerKernelShape))
print(" ----- (Testing) Input shape: {} ---> Output shape: {}".format(inputFullyCNShape_Test_Old,inputFullyCNShape_Test))
######### -------------- Do Classification layer ----------------- ##################
# Define kernel shape for classification layer
featMaps_LastLayer = self.cnnLayers[-1]
filterShape_ClassificationLayer = [self.n_classes, featMaps_LastLayer, 1, 1, 1]
# Define inputs and shapes for the classification layer
inputImageClassificationLayer_Train = inputToFullyCN_Train
inputImageClassificationLayer_Test = inputToFullyCN_Test
inputImageClassificationLayerShape_Train = inputFullyCNShape_Train
inputImageClassificationLayerShape_Test = inputFullyCNShape_Test
print(" ----- (Classification layer) kernel shape {}".format(filterShape_ClassificationLayer))
classification_layer_Index = l_i
weights = []
applyBatchNorm = True
epochsToApplyBatchNorm = 60
maxPoolingParameters = []
dropoutRate = self.dropout_Rates[len(self.dropout_Rates)-1]
softmaxTemperature = 1.0
myLiviaNet_ClassificationLayer = LiviaSoftmax.LiviaSoftmax(rng,
classification_layer_Index,
inputImageClassificationLayer_Train,
inputImageClassificationLayer_Test,
inputImageClassificationLayerShape_Train,
inputImageClassificationLayerShape_Test,
filterShape_ClassificationLayer,
self.applyBatchNorm,
self.numberEpochToApplyBatchNorm,
maxPoolingParameters,
self.weight_Initialization_FCN,
weights,
0, #self.activationType,
dropoutRate,
softmaxTemperature
)
self.networkLayers.append(myLiviaNet_ClassificationLayer)
self.lastLayer = myLiviaNet_ClassificationLayer
print(" ----- (Training) Input shape: {} ---> Output shape: {} || kernel shape {}".format(inputImageClassificationLayerShape_Train,myLiviaNet_ClassificationLayer.outputShapeTrain, filterShape_ClassificationLayer))
print(" ----- (Testing) Input shape: {} ---> Output shape: {}".format(inputImageClassificationLayerShape_Test,myLiviaNet_ClassificationLayer.outputShapeTest))
# -------------------------------------------------------------------- END Function ------------------------------------------------------------------- #
def updateLayersMatricesBatchNorm(self):
for l_i in xrange(0, len(self.networkLayers) ) :
self.networkLayers[l_i].updateLayerMatricesBatchNorm()
# -------------------------------------------------------------------- END Function ------------------------------------------------------------------- #
""" Function that connects intermediate layers to the input of the first fully connected layer
This is done for multi-scale features """
def connectIntermediateLayers(self,
layersToConnect,
inputSampleInFullyCN_Train,
inputSampleInFullyCN_Test,
featMapsInFullyCN):
centralVoxelsTrain = self.centralVoxelsTrain
centralVoxelsTest = self.centralVoxelsTest
for l_i in layersToConnect :
currentLayer = self.networkLayers[l_i]
output_train = currentLayer.outputTrain
output_trainShape = currentLayer.outputShapeTrain
output_test = currentLayer.outputTest
output_testShape = currentLayer.outputShapeTest
# Get the middle part of feature maps at intermediate levels to make them of the same shape at the beginning of the
# first fully connected layer
featMapsCenter_Train = extractCenterFeatMaps(output_train, output_trainShape, centralVoxelsTrain)
featMapsCenter_Test = extractCenterFeatMaps(output_test, output_testShape, centralVoxelsTest)
featMapsInFullyCN = featMapsInFullyCN + currentLayer._numberOfFeatureMaps
inputSampleInFullyCN_Train = T.concatenate([inputSampleInFullyCN_Train, featMapsCenter_Train], axis=1)
inputSampleInFullyCN_Test = T.concatenate([inputSampleInFullyCN_Test, featMapsCenter_Test], axis=1)
return [featMapsInFullyCN, inputSampleInFullyCN_Train, inputSampleInFullyCN_Test]
############# Functions for OPTIMIZERS #################
def getUpdatesOfTrainableParameters(self, cost, paramsTraining, numberParamsPerLayer) :
# Optimizers
def SGD():
print (" --- Optimizer: Stochastic gradient descent (SGD)")
updates = self.updateParams_SGD(cost, paramsTraining, numberParamsPerLayer)
return updates
def RMSProp():
print (" --- Optimizer: RMS Prop")
updates = self.updateParams_RMSProp(cost, paramsTraining, numberParamsPerLayer)
return updates
# TODO. Include more optimizers here
optionsOptimizer = {0 : SGD,
1 : RMSProp}
updates = optionsOptimizer[self.optimizerType]()
return updates
""" # Optimizers:
# More optimizers in : https://github.com/Lasagne/Lasagne/blob/master/lasagne/updates.py """
# ========= Update the trainable parameters using Stocastic Gradient Descent ===============
def updateParams_SGD(self, cost, paramsTraining, numberParamsPerLayer) :
# Create a list of gradients for all model parameters
grads = T.grad(cost, paramsTraining)
# Get learning rates for each param
#learning_rates = extendLearningRateToParams(numberParamsPerLayer,self.learning_rate)
self.vel_Momentum = []
updates = []
constantForCurrentGradientUpdate = 1.0 - self.momentum*self.momentumNormalized
#for param, grad, lrate in zip(paramsTraining, grads, learning_rates) :
for param, grad in zip(paramsTraining, grads) :
v = theano.shared(param.get_value()*0., broadcastable=param.broadcastable)
self.vel_Momentum.append(v)
stepToGradientDirection = constantForCurrentGradientUpdate*self.learning_rate*grad
newVel = self.momentum * v - stepToGradientDirection
if self.momentumType == 0 :
updateToParam = newVel
else :
updateToParam = self.momentum*newVel - stepToGradientDirection
updates.append((v, newVel))
updates.append((param, param + updateToParam))
return updates
# ========= Update the trainable parameters using RMSProp ===============
def updateParams_RMSProp(self, cost, paramsTraining, numberParamsPerLayer) :
# Original code: https://gist.github.com/Newmu/acb738767acb4788bac3
# epsilon=1e-4 in paper.
# Kamnitsas reported NaN values in cost function when employing this value.
# Worked ok with epsilon=1e-6.
grads = T.grad(cost, paramsTraining)
# Get learning rates for each param
#learning_rates = extendLearningRateToParams(numberParamsPerLayer,self.learning_rate)
self.params_RmsProp = []
self.vel_Momentum = []
updates = []
constantForCurrentGradientUpdate = 1.0 - self.momentum*self.momentumNormalized
# Using theano constant to prevent upcasting of float32
one = T.constant(1)
for param, grad in zip(paramsTraining, grads):
accu = theano.shared(param.get_value()*0., broadcastable=param.broadcastable)
self.params_RmsProp.append(accu)
v = theano.shared(param.get_value()*0., broadcastable=param.broadcastable)
self.vel_Momentum.append(v)
accu_new = self.rho_RMSProp * accu + (one - self.rho_RMSProp) * T.sqr(grad)
numGradStep = self.learning_rate * grad
denGradStep = T.sqrt(accu_new + self.epsilon_RMSProp)
stepToGradientDirection = constantForCurrentGradientUpdate*(numGradStep /denGradStep)
newVel = self.momentum * v - stepToGradientDirection
if self.momentumType == 0 :
updateToParam = newVel
else :
updateToParam = self.momentum*newVel - stepToGradientDirection
updates.append((accu, accu_new))
updates.append((v, newVel))
updates.append((param, param + updateToParam))
return updates
# -------------------------------------------------------------------- END Function ------------------------------------------------------------------- #
""" ------ Get trainable parameters --------- """
def getTrainable_Params(_self):
trainable_Params = []
numberTrain_ParamsLayer = []
for l_i in xrange(0, len(_self.networkLayers) ) :
trainable_Params = trainable_Params + _self.networkLayers[l_i].params
numberTrain_ParamsLayer.append(_self.networkLayers[l_i].numberOfTrainableParams) # TODO: Get this directly as len(_self.networkLayers[l_i].params)
return trainable_Params,numberTrain_ParamsLayer
# -------------------------------------------------------------------- END Function ------------------------------------------------------------------- #
def initTrainingParameters(self,
costFunction,
L1_reg_C,
L2_reg_C,
learning_rate,
momentumType,
momentumValue,
momentumNormalized,
optimizerType,
rho_RMSProp,
epsilon_RMSProp
) :
print(" ------- Initializing network training parameters...........")
self.numberOfEpochsTrained = 0
self.L1_reg_C = L1_reg_C
self.L2_reg_C = L2_reg_C
# Set Learning rate and store the last epoch where it was modified
self.initialLearningRate = learning_rate
# TODO: Check the shared variables from learning rates
self.learning_rate.set_value(self.initialLearningRate[0])
# Set momentum type and values
self.momentumType = momentumType
self.initialMomentumValue = momentumValue
self.momentumNormalized = momentumNormalized
self.momentum.set_value(self.initialMomentumValue)
# Optimizers
if (optimizerType == 2):
optimizerType = 1
def SGD():
print (" --- Optimizer: Stochastic gradient descent (SGD)")
self.optimizerType = optimizerType
def RMSProp():
print (" --- Optimizer: RMS Prop")
self.optimizerType = optimizerType
self.rho_RMSProp = rho_RMSProp
self.epsilon_RMSProp = epsilon_RMSProp
# TODO. Include more optimizers here
optionsOptimizer = {0 : SGD,
1 : RMSProp}
optionsOptimizer[optimizerType]()
# -------------------------------------------------------------------- END Function ------------------------------------------------------------------- #
def updateParams_BatchNorm(self) :
updatesForBnRollingAverage = []
for l_i in xrange(0, len(self.networkLayers) ) :
currentLayer = self.networkLayers[l_i]
updatesForBnRollingAverage.extend( currentLayer.getUpdatesForBnRollingAverage() )
return updatesForBnRollingAverage
# ------------------------------------------------------------------------------------ #
# --------------------------- Compile the Theano functions ------------------- #
# ------------------------------------------------------------------------------------ #
def compileTheanoFunctions(self):
print(" ----------------- Starting compilation process ----------------- ")
# ------- Create and initialize sharedVariables needed to compile the training function ------ #
# -------------------------------------------------------------------------------------------- #
# For training
self.trainingData_x = theano.shared(np.zeros([1,1,1,1,1], dtype="float32"), borrow = True)
self.trainingData_y = theano.shared(np.zeros([1,1,1,1], dtype="float32") , borrow = True)
self.trainingData_x_Bottom = theano.shared(np.zeros([1,1,1,1,1], dtype="float32"), borrow = True)
# For testing
self.testingData_x_Bottom = theano.shared(np.zeros([1,1,1,1,1], dtype="float32"), borrow = True)
self.testingData_x = theano.shared(np.zeros([1,1,1,1,1], dtype="float32"), borrow = True)
x_Train = self.inputNetwork_Train
x_Train_Bottom = self.inputNetwork_Train_Bottom
x_Test = self.inputNetwork_Test
x_Test_Bottom = self.inputNetwork_Test_Bottom
y_Train = T.itensor4('y')
# Allocate symbolic variables for the data
index_Train = T.lscalar()
index_Test = T.lscalar()
# ------- Needed to compile the training function ------ #
# ------------------------------------------------------ #
trainingData_y_CastedToInt = T.cast( self.trainingData_y, 'int32')
# To accomodate the weights in the cost function to account for class imbalance
weightsOfClassesInCostFunction = T.fvector()
weightPerClass = T.fvector()
# --------- Get trainable parameters (to be fit by gradient descent) ------- #
# -------------------------------------------------------------------------- #
[paramsTraining, numberParamsPerLayer] = self.getTrainable_Params()
# ------------------ Define the cost function --------------------- #
# ----------------------------------------------------------------- #
def negLogLikelihood():
print (" --- Cost function: negativeLogLikelihood")
costInLastLayer = self.lastLayer.negativeLogLikelihoodWeighted(y_Train,weightPerClass)
return costInLastLayer
def NotDefined():
print (" --- Cost function: Not defined!!!!!! WARNING!!!")
optionsCostFunction = {0 : negLogLikelihood,
1 : NotDefined}
costInLastLayer = optionsCostFunction[self.costFunction]()
# --------------------------- Get costs --------------------------- #
# ----------------------------------------------------------------- #
# Get L1 and L2 weights regularization
costL1 = 0
costL2 = 0
# Compute the costs
for l_i in xrange(0, len(self.networkLayers)) :
costL1 += abs(self.networkLayers[l_i].W).sum()
costL2 += (self.networkLayers[l_i].W ** 2).sum()
# Add also the cost of the last layer
cost = (costInLastLayer
+ self.L1_reg_C * costL1
+ self.L2_reg_C * costL2)
# --------------------- Include all trainable parameters in updates (for optimization) ---------------------- #
# ----------------------------------------------------------------------------------------------------------- #
updates = self.getUpdatesOfTrainableParameters(cost, paramsTraining, numberParamsPerLayer)
# --------------------- Include batch normalization params ---------------------- #
# ------------------------------------------------------------------------------- #
updates = updates + self.updateParams_BatchNorm()
# For the testing function we need to get the Feature maps activations
featMapsActivations = []
lower_act = 0
upper_act = 9999
# TODO: Change to output_Test
for l_i in xrange(0,len(self.networkLayers)):
featMapsActivations.append(self.networkLayers[l_i].outputTest[:, lower_act : upper_act, :, :, :])
# For the last layer get the predicted probabilities (p_y_given_x_test)
featMapsActivations.append(self.lastLayer.p_y_given_x_test)
# --------------------- Preparing data to compile the functions ---------------------- #
# ------------------------------------------------------------------------------------ #
givensDataSet_Train = { x_Train: self.trainingData_x[index_Train * self.batch_Size: (index_Train + 1) * self.batch_Size],
x_Train_Bottom: self.trainingData_x_Bottom[index_Train * self.batch_Size: (index_Train + 1) * self.batch_Size],
y_Train: trainingData_y_CastedToInt[index_Train * self.batch_Size: (index_Train + 1) * self.batch_Size],
weightPerClass: weightsOfClassesInCostFunction }
givensDataSet_Test = { x_Test: self.testingData_x[index_Test * self.batch_Size: (index_Test + 1) * self.batch_Size],
x_Test_Bottom: self.testingData_x_Bottom[index_Test * self.batch_Size: (index_Test + 1) * self.batch_Size] }
print(" ...Compiling the training function...")
self.networkModel_Train = theano.function(
[index_Train, weightsOfClassesInCostFunction],
#[cost] + self.lastLayer.doEvaluation(y_Train),
[cost],
updates=updates,
givens = givensDataSet_Train
)
print(" ...The training function was compiled...")
#self.getProbabilities = theano.function(
#[index],
#self.lastLayer.p_y_given_x_Train,
#givens={
#x: self.trainingData_x[index * _self.batch_size: (index + 1) * _self.batch_size]
#}
#)
print(" ...Compiling the testing function...")
self.networkModel_Test = theano.function(
[index_Test],
featMapsActivations,
givens = givensDataSet_Test
)
print(" ...The testing function was compiled...")
# -------------------------------------------------------------------- END Function ------------------------------------------------------------------- #
####### Function to generate the CNN #########
def createNetwork(self,
networkName,
folderName,
cnnLayers,
kernel_Shapes,
intermediate_ConnectedLayers,
n_classes,
sampleSize_Train,
sampleSize_Test,
batch_Size,
applyBatchNorm,
numberEpochToApplyBatchNorm,
activationType,
dropout_Rates,
pooling_Params,
weights_Initialization_CNN,
weights_Initialization_FCN,
weightsFolderName,
weightsTrainedIdx,
softmax_Temp
):
# ============= Model Parameters Passed as arguments ================
# Assign parameters:
self.networkName = networkName
self.folderName = folderName
self.cnnLayers = cnnLayers
self.n_classes = n_classes
self.kernel_Shapes = kernel_Shapes
self.intermediate_ConnectedLayers = intermediate_ConnectedLayers
self.pooling_scales = pooling_Params
self.dropout_Rates = dropout_Rates
self.activationType = activationType
self.weight_Initialization_CNN = weights_Initialization_CNN
self.weight_Initialization_FCN = weights_Initialization_FCN
self.weightsFolderName = weightsFolderName
self.weightsTrainedIdx = weightsTrainedIdx
self.batch_Size = batch_Size
self.sampleSize_Train = sampleSize_Train
self.sampleSize_Test = sampleSize_Test
self.applyBatchNorm = applyBatchNorm
self.numberEpochToApplyBatchNorm = numberEpochToApplyBatchNorm
self.softmax_Temp = softmax_Temp
# Compute the CNN receptive field
stride = 1;
self.receptiveField = computeReceptiveField(self.kernel_Shapes, stride)
# --- Size of Image samples ---
self.sampleSize_Train = sampleSize_Train
self.sampleSize_Test = sampleSize_Test
## --- Batch Size ---
self.batch_Size = batch_Size
# ======== Calculated Attributes =========
self.centralVoxelsTrain = getCentralVoxels(self.sampleSize_Train, self.receptiveField)
self.centralVoxelsTest = getCentralVoxels(self.sampleSize_Test, self.receptiveField)
#==============================
rng = numpy.random.RandomState(23455)
# Transfer to LIVIA NET
self.sampleSize_Train = sampleSize_Train
self.sampleSize_Test = sampleSize_Test
# --------- Now we build the model -------- #
print("...[STATUS]: Building the Network model...")
# Define the symbolic variables used as input of the CNN
# start-snippet-1
# Define tensor5
tensor5 = T.TensorType(dtype='float32', broadcastable=(False, False, False, False, False))
self.inputNetwork_Train = tensor5()
self.inputNetwork_Test = tensor5()
self.inputNetwork_Train_Bottom = tensor5()
self.inputNetwork_Test_Bottom = tensor5()
# Define input shapes to the netwrok
inputSampleShape_Train = (self.batch_Size, 1, self.sampleSize_Train[0], self.sampleSize_Train[1], self.sampleSize_Train[2])
inputSampleShape_Test = (self.batch_Size, 1, self.sampleSize_Test[0], self.sampleSize_Test[1], self.sampleSize_Test[2])
print (" - Shape of input subvolume (Training): {}".format(inputSampleShape_Train))
print (" - Shape of input subvolume (Testing): {}".format(inputSampleShape_Test))
inputSample_Train = self.inputNetwork_Train
inputSample_Test = self.inputNetwork_Test
inputSample_Train_Bottom = self.inputNetwork_Train_Bottom
inputSample_Test_Bottom = self.inputNetwork_Test_Bottom
# TODO change cnnLayers name by networkLayers
self.generateNetworkLayers(cnnLayers,
kernel_Shapes,
self.pooling_scales,
inputSampleShape_Train,
inputSampleShape_Test,
inputSample_Train,
inputSample_Train_Bottom,
inputSample_Test,
inputSample_Test_Bottom,
intermediate_ConnectedLayers)
# Release Data from GPU
def releaseGPUData(self) :
# GPU NOTE: Remove the input values to avoid copying data to the GPU
# Image Data
self.trainingData_x.set_value(np.zeros([1,1,1,1,1], dtype="float32"))
self.testingData_x.set_value(np.zeros([1,1,1,1,1], dtype="float32"))
# Labels
self.trainingData_y.set_value(np.zeros([1,1,1,1], dtype="float32"))
| |
# -*- coding: utf-8 -*-
from __future__ import print_function
from datetime import datetime
import numpy as np
import pytest
from pandas.compat import PY37
import pandas as pd
from pandas import (
Categorical, CategoricalIndex, DataFrame, Index, MultiIndex, Series, qcut)
import pandas.util.testing as tm
from pandas.util.testing import (
assert_equal, assert_frame_equal, assert_series_equal)
def cartesian_product_for_groupers(result, args, names):
""" Reindex to a cartesian production for the groupers,
preserving the nature (Categorical) of each grouper """
def f(a):
if isinstance(a, (CategoricalIndex, Categorical)):
categories = a.categories
a = Categorical.from_codes(np.arange(len(categories)),
categories=categories,
ordered=a.ordered)
return a
index = pd.MultiIndex.from_product(map(f, args), names=names)
return result.reindex(index).sort_index()
def test_apply_use_categorical_name(df):
cats = qcut(df.C, 4)
def get_stats(group):
return {'min': group.min(),
'max': group.max(),
'count': group.count(),
'mean': group.mean()}
result = df.groupby(cats, observed=False).D.apply(get_stats)
assert result.index.names[0] == 'C'
def test_basic():
cats = Categorical(["a", "a", "a", "b", "b", "b", "c", "c", "c"],
categories=["a", "b", "c", "d"], ordered=True)
data = DataFrame({"a": [1, 1, 1, 2, 2, 2, 3, 4, 5], "b": cats})
exp_index = CategoricalIndex(list('abcd'), name='b', ordered=True)
expected = DataFrame({'a': [1, 2, 4, np.nan]}, index=exp_index)
result = data.groupby("b", observed=False).mean()
tm.assert_frame_equal(result, expected)
cat1 = Categorical(["a", "a", "b", "b"],
categories=["a", "b", "z"], ordered=True)
cat2 = Categorical(["c", "d", "c", "d"],
categories=["c", "d", "y"], ordered=True)
df = DataFrame({"A": cat1, "B": cat2, "values": [1, 2, 3, 4]})
# single grouper
gb = df.groupby("A", observed=False)
exp_idx = CategoricalIndex(['a', 'b', 'z'], name='A', ordered=True)
expected = DataFrame({'values': Series([3, 7, 0], index=exp_idx)})
result = gb.sum()
tm.assert_frame_equal(result, expected)
# GH 8623
x = DataFrame([[1, 'John P. Doe'], [2, 'Jane Dove'],
[1, 'John P. Doe']],
columns=['person_id', 'person_name'])
x['person_name'] = Categorical(x.person_name)
g = x.groupby(['person_id'], observed=False)
result = g.transform(lambda x: x)
tm.assert_frame_equal(result, x[['person_name']])
result = x.drop_duplicates('person_name')
expected = x.iloc[[0, 1]]
tm.assert_frame_equal(result, expected)
def f(x):
return x.drop_duplicates('person_name').iloc[0]
result = g.apply(f)
expected = x.iloc[[0, 1]].copy()
expected.index = Index([1, 2], name='person_id')
expected['person_name'] = expected['person_name'].astype('object')
tm.assert_frame_equal(result, expected)
# GH 9921
# Monotonic
df = DataFrame({"a": [5, 15, 25]})
c = pd.cut(df.a, bins=[0, 10, 20, 30, 40])
result = df.a.groupby(c, observed=False).transform(sum)
tm.assert_series_equal(result, df['a'])
tm.assert_series_equal(
df.a.groupby(c, observed=False).transform(lambda xs: np.sum(xs)),
df['a'])
tm.assert_frame_equal(
df.groupby(c, observed=False).transform(sum),
df[['a']])
tm.assert_frame_equal(
df.groupby(c, observed=False).transform(lambda xs: np.max(xs)),
df[['a']])
# Filter
tm.assert_series_equal(
df.a.groupby(c, observed=False).filter(np.all),
df['a'])
tm.assert_frame_equal(
df.groupby(c, observed=False).filter(np.all),
df)
# Non-monotonic
df = DataFrame({"a": [5, 15, 25, -5]})
c = pd.cut(df.a, bins=[-10, 0, 10, 20, 30, 40])
result = df.a.groupby(c, observed=False).transform(sum)
tm.assert_series_equal(result, df['a'])
tm.assert_series_equal(
df.a.groupby(c, observed=False).transform(lambda xs: np.sum(xs)),
df['a'])
tm.assert_frame_equal(
df.groupby(c, observed=False).transform(sum),
df[['a']])
tm.assert_frame_equal(
df.groupby(c, observed=False).transform(lambda xs: np.sum(xs)),
df[['a']])
# GH 9603
df = DataFrame({'a': [1, 0, 0, 0]})
c = pd.cut(df.a, [0, 1, 2, 3, 4], labels=Categorical(list('abcd')))
result = df.groupby(c, observed=False).apply(len)
exp_index = CategoricalIndex(
c.values.categories, ordered=c.values.ordered)
expected = Series([1, 0, 0, 0], index=exp_index)
expected.index.name = 'a'
tm.assert_series_equal(result, expected)
# more basic
levels = ['foo', 'bar', 'baz', 'qux']
codes = np.random.randint(0, 4, size=100)
cats = Categorical.from_codes(codes, levels, ordered=True)
data = DataFrame(np.random.randn(100, 4))
result = data.groupby(cats, observed=False).mean()
expected = data.groupby(np.asarray(cats), observed=False).mean()
exp_idx = CategoricalIndex(levels, categories=cats.categories,
ordered=True)
expected = expected.reindex(exp_idx)
assert_frame_equal(result, expected)
grouped = data.groupby(cats, observed=False)
desc_result = grouped.describe()
idx = cats.codes.argsort()
ord_labels = np.asarray(cats).take(idx)
ord_data = data.take(idx)
exp_cats = Categorical(ord_labels, ordered=True,
categories=['foo', 'bar', 'baz', 'qux'])
expected = ord_data.groupby(
exp_cats, sort=False, observed=False).describe()
assert_frame_equal(desc_result, expected)
# GH 10460
expc = Categorical.from_codes(np.arange(4).repeat(8),
levels, ordered=True)
exp = CategoricalIndex(expc)
tm.assert_index_equal((desc_result.stack().index
.get_level_values(0)), exp)
exp = Index(['count', 'mean', 'std', 'min', '25%', '50%',
'75%', 'max'] * 4)
tm.assert_index_equal((desc_result.stack().index
.get_level_values(1)), exp)
def test_level_get_group(observed):
# GH15155
df = DataFrame(data=np.arange(2, 22, 2),
index=MultiIndex(
levels=[pd.CategoricalIndex(["a", "b"]), range(10)],
codes=[[0] * 5 + [1] * 5, range(10)],
names=["Index1", "Index2"]))
g = df.groupby(level=["Index1"], observed=observed)
# expected should equal test.loc[["a"]]
# GH15166
expected = DataFrame(data=np.arange(2, 12, 2),
index=pd.MultiIndex(levels=[pd.CategoricalIndex(
["a", "b"]), range(5)],
codes=[[0] * 5, range(5)],
names=["Index1", "Index2"]))
result = g.get_group('a')
assert_frame_equal(result, expected)
@pytest.mark.xfail(PY37, reason="flaky on 3.7, xref gh-21636", strict=False)
@pytest.mark.parametrize('ordered', [True, False])
def test_apply(ordered):
# GH 10138
dense = Categorical(list('abc'), ordered=ordered)
# 'b' is in the categories but not in the list
missing = Categorical(
list('aaa'), categories=['a', 'b'], ordered=ordered)
values = np.arange(len(dense))
df = DataFrame({'missing': missing,
'dense': dense,
'values': values})
grouped = df.groupby(['missing', 'dense'], observed=True)
# missing category 'b' should still exist in the output index
idx = MultiIndex.from_arrays(
[missing, dense], names=['missing', 'dense'])
expected = DataFrame([0, 1, 2.],
index=idx,
columns=['values'])
result = grouped.apply(lambda x: np.mean(x))
assert_frame_equal(result, expected)
# we coerce back to ints
expected = expected.astype('int')
result = grouped.mean()
assert_frame_equal(result, expected)
result = grouped.agg(np.mean)
assert_frame_equal(result, expected)
# but for transform we should still get back the original index
idx = MultiIndex.from_arrays([missing, dense],
names=['missing', 'dense'])
expected = Series(1, index=idx)
result = grouped.apply(lambda x: 1)
assert_series_equal(result, expected)
def test_observed(observed):
# multiple groupers, don't re-expand the output space
# of the grouper
# gh-14942 (implement)
# gh-10132 (back-compat)
# gh-8138 (back-compat)
# gh-8869
cat1 = Categorical(["a", "a", "b", "b"],
categories=["a", "b", "z"], ordered=True)
cat2 = Categorical(["c", "d", "c", "d"],
categories=["c", "d", "y"], ordered=True)
df = DataFrame({"A": cat1, "B": cat2, "values": [1, 2, 3, 4]})
df['C'] = ['foo', 'bar'] * 2
# multiple groupers with a non-cat
gb = df.groupby(['A', 'B', 'C'], observed=observed)
exp_index = pd.MultiIndex.from_arrays(
[cat1, cat2, ['foo', 'bar'] * 2],
names=['A', 'B', 'C'])
expected = DataFrame({'values': Series(
[1, 2, 3, 4], index=exp_index)}).sort_index()
result = gb.sum()
if not observed:
expected = cartesian_product_for_groupers(
expected,
[cat1, cat2, ['foo', 'bar']],
list('ABC'))
tm.assert_frame_equal(result, expected)
gb = df.groupby(['A', 'B'], observed=observed)
exp_index = pd.MultiIndex.from_arrays(
[cat1, cat2],
names=['A', 'B'])
expected = DataFrame({'values': [1, 2, 3, 4]},
index=exp_index)
result = gb.sum()
if not observed:
expected = cartesian_product_for_groupers(
expected,
[cat1, cat2],
list('AB'))
tm.assert_frame_equal(result, expected)
# https://github.com/pandas-dev/pandas/issues/8138
d = {'cat':
pd.Categorical(["a", "b", "a", "b"], categories=["a", "b", "c"],
ordered=True),
'ints': [1, 1, 2, 2],
'val': [10, 20, 30, 40]}
df = pd.DataFrame(d)
# Grouping on a single column
groups_single_key = df.groupby("cat", observed=observed)
result = groups_single_key.mean()
exp_index = pd.CategoricalIndex(list('ab'), name="cat",
categories=list('abc'),
ordered=True)
expected = DataFrame({"ints": [1.5, 1.5], "val": [20., 30]},
index=exp_index)
if not observed:
index = pd.CategoricalIndex(list('abc'), name="cat",
categories=list('abc'),
ordered=True)
expected = expected.reindex(index)
tm.assert_frame_equal(result, expected)
# Grouping on two columns
groups_double_key = df.groupby(["cat", "ints"], observed=observed)
result = groups_double_key.agg('mean')
expected = DataFrame(
{"val": [10, 30, 20, 40],
"cat": pd.Categorical(['a', 'a', 'b', 'b'],
categories=['a', 'b', 'c'],
ordered=True),
"ints": [1, 2, 1, 2]}).set_index(["cat", "ints"])
if not observed:
expected = cartesian_product_for_groupers(
expected,
[df.cat.values, [1, 2]],
['cat', 'ints'])
tm.assert_frame_equal(result, expected)
# GH 10132
for key in [('a', 1), ('b', 2), ('b', 1), ('a', 2)]:
c, i = key
result = groups_double_key.get_group(key)
expected = df[(df.cat == c) & (df.ints == i)]
assert_frame_equal(result, expected)
# gh-8869
# with as_index
d = {'foo': [10, 8, 4, 8, 4, 1, 1], 'bar': [10, 20, 30, 40, 50, 60, 70],
'baz': ['d', 'c', 'e', 'a', 'a', 'd', 'c']}
df = pd.DataFrame(d)
cat = pd.cut(df['foo'], np.linspace(0, 10, 3))
df['range'] = cat
groups = df.groupby(['range', 'baz'], as_index=False, observed=observed)
result = groups.agg('mean')
groups2 = df.groupby(['range', 'baz'], as_index=True, observed=observed)
expected = groups2.agg('mean').reset_index()
tm.assert_frame_equal(result, expected)
def test_observed_codes_remap(observed):
d = {'C1': [3, 3, 4, 5], 'C2': [1, 2, 3, 4], 'C3': [10, 100, 200, 34]}
df = pd.DataFrame(d)
values = pd.cut(df['C1'], [1, 2, 3, 6])
values.name = "cat"
groups_double_key = df.groupby([values, 'C2'], observed=observed)
idx = MultiIndex.from_arrays([values, [1, 2, 3, 4]],
names=["cat", "C2"])
expected = DataFrame({"C1": [3, 3, 4, 5],
"C3": [10, 100, 200, 34]}, index=idx)
if not observed:
expected = cartesian_product_for_groupers(
expected,
[values.values, [1, 2, 3, 4]],
['cat', 'C2'])
result = groups_double_key.agg('mean')
tm.assert_frame_equal(result, expected)
def test_observed_perf():
# we create a cartesian product, so this is
# non-performant if we don't use observed values
# gh-14942
df = DataFrame({
'cat': np.random.randint(0, 255, size=30000),
'int_id': np.random.randint(0, 255, size=30000),
'other_id': np.random.randint(0, 10000, size=30000),
'foo': 0})
df['cat'] = df.cat.astype(str).astype('category')
grouped = df.groupby(['cat', 'int_id', 'other_id'], observed=True)
result = grouped.count()
assert result.index.levels[0].nunique() == df.cat.nunique()
assert result.index.levels[1].nunique() == df.int_id.nunique()
assert result.index.levels[2].nunique() == df.other_id.nunique()
def test_observed_groups(observed):
# gh-20583
# test that we have the appropriate groups
cat = pd.Categorical(['a', 'c', 'a'], categories=['a', 'b', 'c'])
df = pd.DataFrame({'cat': cat, 'vals': [1, 2, 3]})
g = df.groupby('cat', observed=observed)
result = g.groups
if observed:
expected = {'a': Index([0, 2], dtype='int64'),
'c': Index([1], dtype='int64')}
else:
expected = {'a': Index([0, 2], dtype='int64'),
'b': Index([], dtype='int64'),
'c': Index([1], dtype='int64')}
tm.assert_dict_equal(result, expected)
def test_observed_groups_with_nan(observed):
# GH 24740
df = pd.DataFrame({'cat': pd.Categorical(['a', np.nan, 'a'],
categories=['a', 'b', 'd']),
'vals': [1, 2, 3]})
g = df.groupby('cat', observed=observed)
result = g.groups
if observed:
expected = {'a': Index([0, 2], dtype='int64')}
else:
expected = {'a': Index([0, 2], dtype='int64'),
'b': Index([], dtype='int64'),
'd': Index([], dtype='int64')}
tm.assert_dict_equal(result, expected)
def test_dataframe_categorical_with_nan(observed):
# GH 21151
s1 = pd.Categorical([np.nan, 'a', np.nan, 'a'],
categories=['a', 'b', 'c'])
s2 = pd.Series([1, 2, 3, 4])
df = pd.DataFrame({'s1': s1, 's2': s2})
result = df.groupby('s1', observed=observed).first().reset_index()
if observed:
expected = DataFrame({'s1': pd.Categorical(['a'],
categories=['a', 'b', 'c']), 's2': [2]})
else:
expected = DataFrame({'s1': pd.Categorical(['a', 'b', 'c'],
categories=['a', 'b', 'c']),
's2': [2, np.nan, np.nan]})
tm.assert_frame_equal(result, expected)
def test_datetime():
# GH9049: ensure backward compatibility
levels = pd.date_range('2014-01-01', periods=4)
codes = np.random.randint(0, 4, size=100)
cats = Categorical.from_codes(codes, levels, ordered=True)
data = DataFrame(np.random.randn(100, 4))
result = data.groupby(cats, observed=False).mean()
expected = data.groupby(np.asarray(cats), observed=False).mean()
expected = expected.reindex(levels)
expected.index = CategoricalIndex(expected.index,
categories=expected.index,
ordered=True)
assert_frame_equal(result, expected)
grouped = data.groupby(cats, observed=False)
desc_result = grouped.describe()
idx = cats.codes.argsort()
ord_labels = cats.take_nd(idx)
ord_data = data.take(idx)
expected = ord_data.groupby(ord_labels, observed=False).describe()
assert_frame_equal(desc_result, expected)
tm.assert_index_equal(desc_result.index, expected.index)
tm.assert_index_equal(
desc_result.index.get_level_values(0),
expected.index.get_level_values(0))
# GH 10460
expc = Categorical.from_codes(
np.arange(4).repeat(8), levels, ordered=True)
exp = CategoricalIndex(expc)
tm.assert_index_equal((desc_result.stack().index
.get_level_values(0)), exp)
exp = Index(['count', 'mean', 'std', 'min', '25%', '50%',
'75%', 'max'] * 4)
tm.assert_index_equal((desc_result.stack().index
.get_level_values(1)), exp)
def test_categorical_index():
s = np.random.RandomState(12345)
levels = ['foo', 'bar', 'baz', 'qux']
codes = s.randint(0, 4, size=20)
cats = Categorical.from_codes(codes, levels, ordered=True)
df = DataFrame(
np.repeat(
np.arange(20), 4).reshape(-1, 4), columns=list('abcd'))
df['cats'] = cats
# with a cat index
result = df.set_index('cats').groupby(level=0, observed=False).sum()
expected = df[list('abcd')].groupby(cats.codes, observed=False).sum()
expected.index = CategoricalIndex(
Categorical.from_codes(
[0, 1, 2, 3], levels, ordered=True), name='cats')
assert_frame_equal(result, expected)
# with a cat column, should produce a cat index
result = df.groupby('cats', observed=False).sum()
expected = df[list('abcd')].groupby(cats.codes, observed=False).sum()
expected.index = CategoricalIndex(
Categorical.from_codes(
[0, 1, 2, 3], levels, ordered=True), name='cats')
assert_frame_equal(result, expected)
def test_describe_categorical_columns():
# GH 11558
cats = pd.CategoricalIndex(['qux', 'foo', 'baz', 'bar'],
categories=['foo', 'bar', 'baz', 'qux'],
ordered=True)
df = DataFrame(np.random.randn(20, 4), columns=cats)
result = df.groupby([1, 2, 3, 4] * 5).describe()
tm.assert_index_equal(result.stack().columns, cats)
tm.assert_categorical_equal(result.stack().columns.values, cats.values)
def test_unstack_categorical():
# GH11558 (example is taken from the original issue)
df = pd.DataFrame({'a': range(10),
'medium': ['A', 'B'] * 5,
'artist': list('XYXXY') * 2})
df['medium'] = df['medium'].astype('category')
gcat = df.groupby(
['artist', 'medium'], observed=False)['a'].count().unstack()
result = gcat.describe()
exp_columns = pd.CategoricalIndex(['A', 'B'], ordered=False,
name='medium')
tm.assert_index_equal(result.columns, exp_columns)
tm.assert_categorical_equal(result.columns.values, exp_columns.values)
result = gcat['A'] + gcat['B']
expected = pd.Series([6, 4], index=pd.Index(['X', 'Y'], name='artist'))
tm.assert_series_equal(result, expected)
def test_bins_unequal_len():
# GH3011
series = Series([np.nan, np.nan, 1, 1, 2, 2, 3, 3, 4, 4])
bins = pd.cut(series.dropna().values, 4)
# len(bins) != len(series) here
with pytest.raises(ValueError):
series.groupby(bins).mean()
def test_as_index():
# GH13204
df = DataFrame({'cat': Categorical([1, 2, 2], [1, 2, 3]),
'A': [10, 11, 11],
'B': [101, 102, 103]})
result = df.groupby(['cat', 'A'], as_index=False, observed=True).sum()
expected = DataFrame(
{'cat': Categorical([1, 2], categories=df.cat.cat.categories),
'A': [10, 11],
'B': [101, 205]},
columns=['cat', 'A', 'B'])
tm.assert_frame_equal(result, expected)
# function grouper
f = lambda r: df.loc[r, 'A']
result = df.groupby(['cat', f], as_index=False, observed=True).sum()
expected = DataFrame(
{'cat': Categorical([1, 2], categories=df.cat.cat.categories),
'A': [10, 22],
'B': [101, 205]},
columns=['cat', 'A', 'B'])
tm.assert_frame_equal(result, expected)
# another not in-axis grouper (conflicting names in index)
s = Series(['a', 'b', 'b'], name='cat')
result = df.groupby(['cat', s], as_index=False, observed=True).sum()
tm.assert_frame_equal(result, expected)
# is original index dropped?
group_columns = ['cat', 'A']
expected = DataFrame(
{'cat': Categorical([1, 2], categories=df.cat.cat.categories),
'A': [10, 11],
'B': [101, 205]},
columns=['cat', 'A', 'B'])
for name in [None, 'X', 'B']:
df.index = Index(list("abc"), name=name)
result = df.groupby(group_columns, as_index=False, observed=True).sum()
tm.assert_frame_equal(result, expected)
def test_preserve_categories():
# GH-13179
categories = list('abc')
# ordered=True
df = DataFrame({'A': pd.Categorical(list('ba'),
categories=categories,
ordered=True)})
index = pd.CategoricalIndex(categories, categories, ordered=True)
tm.assert_index_equal(
df.groupby('A', sort=True, observed=False).first().index, index)
tm.assert_index_equal(
df.groupby('A', sort=False, observed=False).first().index, index)
# ordered=False
df = DataFrame({'A': pd.Categorical(list('ba'),
categories=categories,
ordered=False)})
sort_index = pd.CategoricalIndex(categories, categories, ordered=False)
nosort_index = pd.CategoricalIndex(list('bac'), list('bac'),
ordered=False)
tm.assert_index_equal(
df.groupby('A', sort=True, observed=False).first().index,
sort_index)
tm.assert_index_equal(
df.groupby('A', sort=False, observed=False).first().index,
nosort_index)
def test_preserve_categorical_dtype():
# GH13743, GH13854
df = DataFrame({'A': [1, 2, 1, 1, 2],
'B': [10, 16, 22, 28, 34],
'C1': Categorical(list("abaab"),
categories=list("bac"),
ordered=False),
'C2': Categorical(list("abaab"),
categories=list("bac"),
ordered=True)})
# single grouper
exp_full = DataFrame({'A': [2.0, 1.0, np.nan],
'B': [25.0, 20.0, np.nan],
'C1': Categorical(list("bac"),
categories=list("bac"),
ordered=False),
'C2': Categorical(list("bac"),
categories=list("bac"),
ordered=True)})
for col in ['C1', 'C2']:
result1 = df.groupby(by=col, as_index=False, observed=False).mean()
result2 = df.groupby(
by=col, as_index=True, observed=False).mean().reset_index()
expected = exp_full.reindex(columns=result1.columns)
tm.assert_frame_equal(result1, expected)
tm.assert_frame_equal(result2, expected)
def test_categorical_no_compress():
data = Series(np.random.randn(9))
codes = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2])
cats = Categorical.from_codes(codes, [0, 1, 2], ordered=True)
result = data.groupby(cats, observed=False).mean()
exp = data.groupby(codes, observed=False).mean()
exp.index = CategoricalIndex(exp.index, categories=cats.categories,
ordered=cats.ordered)
assert_series_equal(result, exp)
codes = np.array([0, 0, 0, 1, 1, 1, 3, 3, 3])
cats = Categorical.from_codes(codes, [0, 1, 2, 3], ordered=True)
result = data.groupby(cats, observed=False).mean()
exp = data.groupby(codes, observed=False).mean().reindex(cats.categories)
exp.index = CategoricalIndex(exp.index, categories=cats.categories,
ordered=cats.ordered)
assert_series_equal(result, exp)
cats = Categorical(["a", "a", "a", "b", "b", "b", "c", "c", "c"],
categories=["a", "b", "c", "d"], ordered=True)
data = DataFrame({"a": [1, 1, 1, 2, 2, 2, 3, 4, 5], "b": cats})
result = data.groupby("b", observed=False).mean()
result = result["a"].values
exp = np.array([1, 2, 4, np.nan])
tm.assert_numpy_array_equal(result, exp)
def test_sort():
# http://stackoverflow.com/questions/23814368/sorting-pandas-categorical-labels-after-groupby # noqa: flake8
# This should result in a properly sorted Series so that the plot
# has a sorted x axis
# self.cat.groupby(['value_group'])['value_group'].count().plot(kind='bar')
df = DataFrame({'value': np.random.randint(0, 10000, 100)})
labels = ["{0} - {1}".format(i, i + 499) for i in range(0, 10000, 500)]
cat_labels = Categorical(labels, labels)
df = df.sort_values(by=['value'], ascending=True)
df['value_group'] = pd.cut(df.value, range(0, 10500, 500),
right=False, labels=cat_labels)
res = df.groupby(['value_group'], observed=False)['value_group'].count()
exp = res[sorted(res.index, key=lambda x: float(x.split()[0]))]
exp.index = CategoricalIndex(exp.index, name=exp.index.name)
tm.assert_series_equal(res, exp)
def test_sort2():
# dataframe groupby sort was being ignored # GH 8868
df = DataFrame([['(7.5, 10]', 10, 10],
['(7.5, 10]', 8, 20],
['(2.5, 5]', 5, 30],
['(5, 7.5]', 6, 40],
['(2.5, 5]', 4, 50],
['(0, 2.5]', 1, 60],
['(5, 7.5]', 7, 70]], columns=['range', 'foo', 'bar'])
df['range'] = Categorical(df['range'], ordered=True)
index = CategoricalIndex(['(0, 2.5]', '(2.5, 5]', '(5, 7.5]',
'(7.5, 10]'], name='range', ordered=True)
expected_sort = DataFrame([[1, 60], [5, 30], [6, 40], [10, 10]],
columns=['foo', 'bar'], index=index)
col = 'range'
result_sort = df.groupby(col, sort=True, observed=False).first()
assert_frame_equal(result_sort, expected_sort)
# when categories is ordered, group is ordered by category's order
expected_sort = result_sort
result_sort = df.groupby(col, sort=False, observed=False).first()
assert_frame_equal(result_sort, expected_sort)
df['range'] = Categorical(df['range'], ordered=False)
index = CategoricalIndex(['(0, 2.5]', '(2.5, 5]', '(5, 7.5]',
'(7.5, 10]'], name='range')
expected_sort = DataFrame([[1, 60], [5, 30], [6, 40], [10, 10]],
columns=['foo', 'bar'], index=index)
index = CategoricalIndex(['(7.5, 10]', '(2.5, 5]', '(5, 7.5]',
'(0, 2.5]'],
categories=['(7.5, 10]', '(2.5, 5]',
'(5, 7.5]', '(0, 2.5]'],
name='range')
expected_nosort = DataFrame([[10, 10], [5, 30], [6, 40], [1, 60]],
index=index, columns=['foo', 'bar'])
col = 'range'
# this is an unordered categorical, but we allow this ####
result_sort = df.groupby(col, sort=True, observed=False).first()
assert_frame_equal(result_sort, expected_sort)
result_nosort = df.groupby(col, sort=False, observed=False).first()
assert_frame_equal(result_nosort, expected_nosort)
def test_sort_datetimelike():
# GH10505
# use same data as test_groupby_sort_categorical, which category is
# corresponding to datetime.month
df = DataFrame({'dt': [datetime(2011, 7, 1), datetime(2011, 7, 1),
datetime(2011, 2, 1), datetime(2011, 5, 1),
datetime(2011, 2, 1), datetime(2011, 1, 1),
datetime(2011, 5, 1)],
'foo': [10, 8, 5, 6, 4, 1, 7],
'bar': [10, 20, 30, 40, 50, 60, 70]},
columns=['dt', 'foo', 'bar'])
# ordered=True
df['dt'] = Categorical(df['dt'], ordered=True)
index = [datetime(2011, 1, 1), datetime(2011, 2, 1),
datetime(2011, 5, 1), datetime(2011, 7, 1)]
result_sort = DataFrame(
[[1, 60], [5, 30], [6, 40], [10, 10]], columns=['foo', 'bar'])
result_sort.index = CategoricalIndex(index, name='dt', ordered=True)
index = [datetime(2011, 7, 1), datetime(2011, 2, 1),
datetime(2011, 5, 1), datetime(2011, 1, 1)]
result_nosort = DataFrame([[10, 10], [5, 30], [6, 40], [1, 60]],
columns=['foo', 'bar'])
result_nosort.index = CategoricalIndex(index, categories=index,
name='dt', ordered=True)
col = 'dt'
assert_frame_equal(
result_sort, df.groupby(col, sort=True, observed=False).first())
# when categories is ordered, group is ordered by category's order
assert_frame_equal(
result_sort, df.groupby(col, sort=False, observed=False).first())
# ordered = False
df['dt'] = Categorical(df['dt'], ordered=False)
index = [datetime(2011, 1, 1), datetime(2011, 2, 1),
datetime(2011, 5, 1), datetime(2011, 7, 1)]
result_sort = DataFrame(
[[1, 60], [5, 30], [6, 40], [10, 10]], columns=['foo', 'bar'])
result_sort.index = CategoricalIndex(index, name='dt')
index = [datetime(2011, 7, 1), datetime(2011, 2, 1),
datetime(2011, 5, 1), datetime(2011, 1, 1)]
result_nosort = DataFrame([[10, 10], [5, 30], [6, 40], [1, 60]],
columns=['foo', 'bar'])
result_nosort.index = CategoricalIndex(index, categories=index,
name='dt')
col = 'dt'
assert_frame_equal(
result_sort, df.groupby(col, sort=True, observed=False).first())
assert_frame_equal(
result_nosort, df.groupby(col, sort=False, observed=False).first())
def test_empty_sum():
# https://github.com/pandas-dev/pandas/issues/18678
df = pd.DataFrame({"A": pd.Categorical(['a', 'a', 'b'],
categories=['a', 'b', 'c']),
'B': [1, 2, 1]})
expected_idx = pd.CategoricalIndex(['a', 'b', 'c'], name='A')
# 0 by default
result = df.groupby("A", observed=False).B.sum()
expected = pd.Series([3, 1, 0], expected_idx, name='B')
tm.assert_series_equal(result, expected)
# min_count=0
result = df.groupby("A", observed=False).B.sum(min_count=0)
expected = pd.Series([3, 1, 0], expected_idx, name='B')
tm.assert_series_equal(result, expected)
# min_count=1
result = df.groupby("A", observed=False).B.sum(min_count=1)
expected = pd.Series([3, 1, np.nan], expected_idx, name='B')
tm.assert_series_equal(result, expected)
# min_count>1
result = df.groupby("A", observed=False).B.sum(min_count=2)
expected = pd.Series([3, np.nan, np.nan], expected_idx, name='B')
tm.assert_series_equal(result, expected)
def test_empty_prod():
# https://github.com/pandas-dev/pandas/issues/18678
df = pd.DataFrame({"A": pd.Categorical(['a', 'a', 'b'],
categories=['a', 'b', 'c']),
'B': [1, 2, 1]})
expected_idx = pd.CategoricalIndex(['a', 'b', 'c'], name='A')
# 1 by default
result = df.groupby("A", observed=False).B.prod()
expected = pd.Series([2, 1, 1], expected_idx, name='B')
tm.assert_series_equal(result, expected)
# min_count=0
result = df.groupby("A", observed=False).B.prod(min_count=0)
expected = pd.Series([2, 1, 1], expected_idx, name='B')
tm.assert_series_equal(result, expected)
# min_count=1
result = df.groupby("A", observed=False).B.prod(min_count=1)
expected = pd.Series([2, 1, np.nan], expected_idx, name='B')
tm.assert_series_equal(result, expected)
def test_groupby_multiindex_categorical_datetime():
# https://github.com/pandas-dev/pandas/issues/21390
df = pd.DataFrame({
'key1': pd.Categorical(list('abcbabcba')),
'key2': pd.Categorical(
list(pd.date_range('2018-06-01 00', freq='1T', periods=3)) * 3),
'values': np.arange(9),
})
result = df.groupby(['key1', 'key2']).mean()
idx = pd.MultiIndex.from_product(
[pd.Categorical(['a', 'b', 'c']),
pd.Categorical(pd.date_range('2018-06-01 00', freq='1T', periods=3))],
names=['key1', 'key2'])
expected = pd.DataFrame(
{'values': [0, 4, 8, 3, 4, 5, 6, np.nan, 2]}, index=idx)
assert_frame_equal(result, expected)
@pytest.mark.parametrize("as_index, expected", [
(True, pd.Series(
index=pd.MultiIndex.from_arrays(
[pd.Series([1, 1, 2], dtype='category'),
[1, 2, 2]], names=['a', 'b']
),
data=[1, 2, 3], name='x'
)),
(False, pd.DataFrame({
'a': pd.Series([1, 1, 2], dtype='category'),
'b': [1, 2, 2],
'x': [1, 2, 3]
}))
])
def test_groupby_agg_observed_true_single_column(as_index, expected):
# GH-23970
df = pd.DataFrame({
'a': pd.Series([1, 1, 2], dtype='category'),
'b': [1, 2, 2],
'x': [1, 2, 3]
})
result = df.groupby(
['a', 'b'], as_index=as_index, observed=True)['x'].sum()
assert_equal(result, expected)
@pytest.mark.parametrize('fill_value', [None, np.nan, pd.NaT])
def test_shift(fill_value):
ct = pd.Categorical(['a', 'b', 'c', 'd'],
categories=['a', 'b', 'c', 'd'], ordered=False)
expected = pd.Categorical([None, 'a', 'b', 'c'],
categories=['a', 'b', 'c', 'd'], ordered=False)
res = ct.shift(1, fill_value=fill_value)
assert_equal(res, expected)
| |
import numpy as np
import os
try:
import netCDF4 as netCDF
except:
import netCDF3 as netCDF
import matplotlib.pyplot as plt
import time
from datetime import datetime
from matplotlib.dates import date2num, num2date
import pyroms
import pyroms_toolbox
import _remapping
class nctime(object):
pass
def remap_bdry(src_file, src_varname, src_grd, dst_grd, dmax=0, cdepth=0, kk=0, dst_dir='./'):
# YELLOW grid sub-sample
xrange=(225, 275); yrange=(190, 240)
# get time
nctime.long_name = 'time'
nctime.units = 'days since 1900-01-01 00:00:00'
# time reference "days since 1900-01-01 00:00:00"
ref = datetime(1900, 1, 1, 0, 0, 0)
ref = date2num(ref)
tag = src_file.rsplit('/')[-1].rsplit('_')[-1].rsplit('-')[0]
year = int(tag[:4])
month = int(tag[4:6])
day = int(tag[6:])
time = datetime(year, month, day, 0, 0, 0)
time = date2num(time)
time = time - ref
time = time + 2.5 # 5-day average
# create boundary file
dst_file = src_file.rsplit('/')[-1]
dst_file = dst_dir + dst_file[:-4] + '_' + src_varname + '_bdry_' + dst_grd.name + '.nc'
print '\nCreating boundary file', dst_file
if os.path.exists(dst_file) is True:
os.remove(dst_file)
pyroms_toolbox.nc_create_roms_file(dst_file, dst_grd, nctime, Lgrid=False)
# open boundary file
nc = netCDF.Dataset(dst_file, 'a', format='NETCDF3_CLASSIC')
#load var
cdf = netCDF.Dataset(src_file)
src_var = cdf.variables[src_varname]
#get missing value
spval = src_var._FillValue
# determine variable dimension
ndim = len(src_var.dimensions)
# YELLOW grid sub-sample
if ndim == 3:
src_var = src_var[:, yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]
elif ndim == 2:
src_var = src_var[yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]
if src_varname == 'ssh':
Bpos = 't'
Cpos = 'rho'
z = src_grd.z_t
Mp, Lp = dst_grd.hgrid.mask_rho.shape
wts_file = 'remap_weights_SODA_2.1.6_to_YELLOW_bilinear_t_to_rho.nc'
dst_varname = 'zeta'
dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
long_name = 'free-surface'
dst_varname_north = 'zeta_north'
dimensions_north = ('ocean_time', 'xi_rho')
long_name_north = 'free-surface north boundary condition'
field_north = 'zeta_north, scalar, series'
dst_varname_south = 'zeta_south'
dimensions_south = ('ocean_time', 'xi_rho')
long_name_south = 'free-surface south boundary condition'
field_south = 'zeta_south, scalar, series'
dst_varname_east = 'zeta_east'
dimensions_east = ('ocean_time', 'eta_rho')
long_name_east = 'free-surface east boundary condition'
field_east = 'zeta_east, scalar, series'
dst_varname_west = 'zeta_west'
dimensions_west = ('ocean_time', 'eta_rho')
long_name_west = 'free-surface west boundary condition'
field_west = 'zeta_west, scalar, series'
units = 'meter'
elif src_varname == 'temp':
Bpos = 't'
Cpos = 'rho'
z = src_grd.z_t
Mp, Lp = dst_grd.hgrid.mask_rho.shape
wts_file = 'remap_weights_SODA_2.1.6_to_YELLOW_bilinear_t_to_rho.nc'
dst_varname = 'temperature'
dst_varname_north = 'temp_north'
dimensions_north = ('ocean_time', 's_rho', 'xi_rho')
long_name_north = 'potential temperature north boundary condition'
field_north = 'temp_north, scalar, series'
dst_varname_south = 'temp_south'
dimensions_south = ('ocean_time', 's_rho', 'xi_rho')
long_name_south = 'potential temperature south boundary condition'
field_south = 'temp_south, scalar, series'
dst_varname_east = 'temp_east'
dimensions_east = ('ocean_time', 's_rho', 'eta_rho')
long_name_east = 'potential temperature east boundary condition'
field_east = 'temp_east, scalar, series'
dst_varname_west = 'temp_west'
dimensions_west = ('ocean_time', 's_rho', 'eta_rho')
long_name_west = 'potential temperature west boundary condition'
field_west = 'temp_west, scalar, series'
units = 'Celsius'
elif src_varname == 'salt':
Bpos = 't'
Cpos = 'rho'
z = src_grd.z_t
Mp, Lp = dst_grd.hgrid.mask_rho.shape
wts_file = 'remap_weights_SODA_2.1.6_to_YELLOW_bilinear_t_to_rho.nc'
dst_varname = 'salinity'
dst_varname_north = 'salt_north'
dimensions_north = ('ocean_time', 's_rho', 'xi_rho')
long_name_north = 'salinity north boundary condition'
field_north = 'salt_north, scalar, series'
dst_varname_south = 'salt_south'
dimensions_south = ('ocean_time', 's_rho', 'xi_rho')
long_name_south = 'salinity south boundary condition'
field_south = 'salt_south, scalar, series'
dst_varname_east = 'salt_east'
dimensions_east = ('ocean_time', 's_rho', 'eta_rho')
long_name_east = 'salinity east boundary condition'
field_east = 'salt_east, scalar, series'
dst_varname_west = 'salt_west'
dimensions_west = ('ocean_time', 's_rho', 'eta_rho')
long_name_west = 'salinity west boundary condition'
field_west = 'salt_west, scalar, series'
units = 'PSU'
else:
raise ValueError, 'Undefined src_varname'
if ndim == 3:
# build intermediate zgrid
zlevel = -z[::-1,0,0]
nzlevel = len(zlevel)
dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name+'_Z', dst_grd.hgrid, dst_zcoord)
# create variable in boudary file
print 'Creating variable', dst_varname_north
nc.createVariable(dst_varname_north, 'f8', dimensions_north, fill_value=spval)
nc.variables[dst_varname_north].long_name = long_name_north
nc.variables[dst_varname_north].units = units
nc.variables[dst_varname_north].field = field_north
#nc.variables[dst_varname_north]._FillValue = spval
print 'Creating variable', dst_varname_south
nc.createVariable(dst_varname_south, 'f8', dimensions_south, fill_value=spval)
nc.variables[dst_varname_south].long_name = long_name_south
nc.variables[dst_varname_south].units = units
nc.variables[dst_varname_south].field = field_south
#nc.variables[dst_varname_south]._FillValue = spval
print 'Creating variable', dst_varname_east
nc.createVariable(dst_varname_east, 'f8', dimensions_east, fill_value=spval)
nc.variables[dst_varname_east].long_name = long_name_east
nc.variables[dst_varname_east].units = units
nc.variables[dst_varname_east].field = field_east
#nc.variables[dst_varname_east]._FillValue = spval
print 'Creating variable', dst_varname_west
nc.createVariable(dst_varname_west, 'f8', dimensions_west, fill_value=spval)
nc.variables[dst_varname_west].long_name = long_name_west
nc.variables[dst_varname_west].units = units
nc.variables[dst_varname_west].field = field_west
#nc.variables[dst_varname_west]._FillValue = spval
# remapping
print 'remapping', dst_varname, 'from', src_grd.name, \
'to', dst_grd.name
print 'time =', time
if ndim == 3:
# flood the grid
print 'flood the grid'
src_varz = pyroms_toolbox.BGrid_SODA.flood(src_var, src_grd, Bpos=Bpos, spval=spval, \
dmax=dmax, cdepth=cdepth, kk=kk)
else:
src_varz = src_var
# horizontal interpolation using scrip weights
print 'horizontal interpolation using scrip weights'
dst_varz = pyroms.remapping.remap(src_varz, wts_file, spval=spval)
if ndim == 3:
# vertical interpolation from standard z level to sigma
print 'vertical interpolation from standard z level to sigma'
dst_var_north = pyroms.remapping.z2roms(dst_varz[::-1, Mp-1:Mp, 0:Lp], \
dst_grdz, dst_grd, Cpos=Cpos, spval=spval, \
flood=False, irange=(0,Lp), jrange=(Mp-1,Mp))
dst_var_south = pyroms.remapping.z2roms(dst_varz[::-1, 0:1, :], \
dst_grdz, dst_grd, Cpos=Cpos, spval=spval, \
flood=False, irange=(0,Lp), jrange=(0,1))
dst_var_east = pyroms.remapping.z2roms(dst_varz[::-1, :, Lp-1:Lp], \
dst_grdz, dst_grd, Cpos=Cpos, spval=spval, \
flood=False, irange=(Lp-1,Lp), jrange=(0,Mp))
dst_var_west = pyroms.remapping.z2roms(dst_varz[::-1, :, 0:1], \
dst_grdz, dst_grd, Cpos=Cpos, spval=spval, \
flood=False, irange=(0,1), jrange=(0,Mp))
else:
dst_var_north = dst_varz[-1, :]
dst_var_south = dst_varz[0, :]
dst_var_east = dst_varz[:, -1]
dst_var_west = dst_varz[:, 0]
# write data in destination file
print 'write data in destination file'
nc.variables['ocean_time'][0] = time
nc.variables[dst_varname_north][0] = np.squeeze(dst_var_north)
nc.variables[dst_varname_south][0] = np.squeeze(dst_var_south)
nc.variables[dst_varname_east][0] = np.squeeze(dst_var_east)
nc.variables[dst_varname_west][0] = np.squeeze(dst_var_west)
# close file
nc.close()
cdf.close()
if src_varname == 'ssh':
return dst_varz
| |
# lshash/storage.py
# Copyright 2012 Kay Zhu (a.k.a He Zhu) and contributors (see CONTRIBUTORS.txt)
#
# This module is part of lshash and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import time
import cPickle
try:
import redis
except ImportError:
redis = None
try:
import bsddb
except ImportError:
bsddb = None
try:
import leveldb
except ImportError:
leveldb = None
try:
import cPickle as pickle
except ImportError:
print "Couldn't import cPickle, using slower built-in pickle"
import pickle
def serialize( data):
return cPickle.dumps( data)
def deserialize( data):
return cPickle.loads( data)
__all__ = ['storage']
def storage(storage_config, index):
""" Given the configuration for storage and the index, return the
configured storage instance.
"""
if 'dict' in storage_config:
return InMemoryStorage(storage_config['dict'])
elif 'redis' in storage_config:
storage_config['redis']['db'] = index
return RedisStorage(storage_config['redis'])
elif 'berkeleydb' in storage_config:
return BerkeleyDBStorage(storage_config['berkeleydb'])
elif 'leveldb' in storage_config:
return LevelDBStorage(storage_config['leveldb'])
else:
raise ValueError("Only in-memory dictionary, berkeleydb, leveldb, and redis are supported.")
class BaseStorage(object):
def __init__(self, config):
""" An abstract class used as an adapter for storages. """
raise NotImplementedError
def serialize( self, data):
return serialize( data)
def deserialize( self, data):
return deserialize( data)
def keys(self):
""" Returns a list of binary hashes that are used as dict keys. """
raise NotImplementedError
def set_val(self, key, val):
""" Set `val` at `key`, note that the `val` must be a string. """
raise NotImplementedError
def get_val(self, key):
""" Return `val` at `key`, note that the `val` must be a string. """
raise NotImplementedError
def append_val(self, key, val):
""" Append `val` to the list stored at `key`.
If the key is not yet present in storage, create a list with `val` at
`key`.
"""
raise NotImplementedError
def get_list(self, key):
""" Returns a list stored in storage at `key`.
This method should return a list of values stored at `key`. `[]` should
be returned if the list is empty or if `key` is not present in storage.
"""
raise NotImplementedError
class InMemoryStorage(BaseStorage):
def __init__(self, config):
self.name = 'dict'
self.storage = dict()
def keys(self):
return self.storage.keys()
def set_val(self, key, val):
self.storage[key] = val
def get_val(self, key):
return self.storage[key]
def append_val(self, key, val):
self.storage.setdefault(key, []).append(val)
def get_list(self, key):
return self.storage.get(key, [])
class RedisStorage(BaseStorage):
def __init__(self, config):
if not redis:
raise ImportError("redis-py is required to use Redis as storage.")
self.name = 'redis'
self.storage = redis.StrictRedis(**config)
def keys(self, pattern="*"):
return self.storage.keys(pattern)
def set_val(self, key, val):
self.storage.set(key, val)
def get_val(self, key):
return self.storage.get(key)
def append_val(self, key, val):
self.storage.rpush(key, serialize(val))
def get_list(self, key):
# TODO: find a better way to do this
values = self.storage.lrange(key, 0, -1)
return [ deserialize(v)for v in values]
class BerkeleyDBStorage(BaseStorage):
def __init__(self, config):
if 'filename' not in config:
raise ValueError, "You must supply a 'filename' in your config"
self.storage = bsddb.hashopen( config['filename'])
def __exit__(self, type, value, traceback):
print "Cleaning up"
self.storage.sync()
def keys(self):
return self.storage.keys()
def set_val(self, key, val):
self.storage[key] = self.serialize(val)
def get_val(self, key):
return self.storage[key]
def append_val(self, key, val):
try:
current = self.deserialize( self.storage[key])
except KeyError:
current = []
# update new list
current.append( val)
self.storage[key] = self.serialize(current)
def get_list(self, key):
try:
return self.deserialize(self.storage[key])
except KeyError:
return []
class LevelDBStorage(BaseStorage):
def __init__(self, config):
if not leveldb:
raise ImportError("leveldb is required to use Redis as storage.")
if 'db' not in config:
raise ValueError, "You must specify LevelDB filename as 'db' in your config"
self.storage = leveldb.LevelDB( config['db'])
def keys(self):
return self.storage.RangeIter(include_value=False)
def set_val(self, key, val):
self.storage.Put( key, self.serialize(val))
def get_val(self, key):
return self.serialize( self.storage.Get( key))
def append_val(self, key, val):
# If a key doesn't exist, leveldb will throw KeyError
try:
current = self.deserialize(self.storage.Get(key))
except KeyError:
current = []
# update new list
current.append( val)
self.storage.Put(key, self.serialize(current))
def get_list(self, key):
try:
return self.deserialize( self.storage.Get(key))
except KeyError:
return []
| |
# Copyright 2019 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 dense_features."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
from tensorflow.python.client import session
from tensorflow.python.eager import backprop
from tensorflow.python.feature_column import feature_column_v2 as fc
from tensorflow.python.feature_column import sequence_feature_column as sfc
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import test_util
from tensorflow.python.keras import combinations
from tensorflow.python.keras import keras_parameterized
from tensorflow.python.keras.feature_column import dense_features as df
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import lookup_ops
from tensorflow.python.ops import partitioned_variables
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables as variables_lib
from tensorflow.python.platform import test
def _initialized_session(config=None):
sess = session.Session(config=config)
sess.run(variables_lib.global_variables_initializer())
sess.run(lookup_ops.tables_initializer())
return sess
class DenseFeaturesTest(keras_parameterized.TestCase):
@combinations.generate(combinations.combine(mode=['graph', 'eager']))
def test_retrieving_input(self):
features = {'a': [0.]}
dense_features = df.DenseFeatures(fc.numeric_column('a'))
inputs = self.evaluate(dense_features(features))
self.assertAllClose([[0.]], inputs)
@combinations.generate(combinations.combine(mode=['eager']))
def test_reuses_variables(self):
sparse_input = sparse_tensor.SparseTensor(
indices=((0, 0), (1, 0), (2, 0)),
values=(0, 1, 2),
dense_shape=(3, 3))
# Create feature columns (categorical and embedding).
categorical_column = fc.categorical_column_with_identity(
key='a', num_buckets=3)
embedding_dimension = 2
def _embedding_column_initializer(shape, dtype, partition_info=None):
del shape # unused
del dtype # unused
del partition_info # unused
embedding_values = (
(1, 0), # id 0
(0, 1), # id 1
(1, 1)) # id 2
return embedding_values
embedding_column = fc.embedding_column(
categorical_column,
dimension=embedding_dimension,
initializer=_embedding_column_initializer)
dense_features = df.DenseFeatures([embedding_column])
features = {'a': sparse_input}
inputs = dense_features(features)
variables = dense_features.variables
# Sanity check: test that the inputs are correct.
self.assertAllEqual([[1, 0], [0, 1], [1, 1]], inputs)
# Check that only one variable was created.
self.assertEqual(1, len(variables))
# Check that invoking dense_features on the same features does not create
# additional variables
_ = dense_features(features)
self.assertEqual(1, len(variables))
self.assertIs(variables[0], dense_features.variables[0])
@combinations.generate(combinations.combine(mode=['eager']))
def test_dense_feature_with_partitioner(self):
sparse_input = sparse_tensor.SparseTensor(
indices=((0, 0), (1, 0), (2, 0), (3, 0)),
values=(0, 1, 3, 2),
dense_shape=(4, 4))
# Create feature columns (categorical and embedding).
categorical_column = fc.categorical_column_with_identity(
key='a', num_buckets=4)
embedding_dimension = 2
def _embedding_column_initializer(shape, dtype, partition_info=None):
offset = partition_info._var_offset[0]
del shape # unused
del dtype # unused
if offset == 0:
embedding_values = (
(1, 0), # id 0
(0, 1)) # id 1
else:
embedding_values = (
(1, 1), # id 2
(2, 2)) # id 3
return embedding_values
embedding_column = fc.embedding_column(
categorical_column,
dimension=embedding_dimension,
initializer=_embedding_column_initializer)
dense_features = df.DenseFeatures(
[embedding_column],
partitioner=partitioned_variables.fixed_size_partitioner(2))
features = {'a': sparse_input}
inputs = dense_features(features)
variables = dense_features.variables
# Sanity check: test that the inputs are correct.
self.assertAllEqual([[1, 0], [0, 1], [2, 2], [1, 1]], inputs)
# Check that only one variable was created.
self.assertEqual(2, len(variables))
# Check that invoking dense_features on the same features does not create
# additional variables
_ = dense_features(features)
self.assertEqual(2, len(variables))
self.assertIs(variables[0], dense_features.variables[0])
self.assertIs(variables[1], dense_features.variables[1])
@combinations.generate(combinations.combine(mode=['eager']))
def test_feature_column_dense_features_gradient(self):
sparse_input = sparse_tensor.SparseTensor(
indices=((0, 0), (1, 0), (2, 0)),
values=(0, 1, 2),
dense_shape=(3, 3))
# Create feature columns (categorical and embedding).
categorical_column = fc.categorical_column_with_identity(
key='a', num_buckets=3)
embedding_dimension = 2
def _embedding_column_initializer(shape, dtype, partition_info=None):
del shape # unused
del dtype # unused
del partition_info # unused
embedding_values = (
(1, 0), # id 0
(0, 1), # id 1
(1, 1)) # id 2
return embedding_values
embedding_column = fc.embedding_column(
categorical_column,
dimension=embedding_dimension,
initializer=_embedding_column_initializer)
dense_features = df.DenseFeatures([embedding_column])
features = {'a': sparse_input}
def scale_matrix():
matrix = dense_features(features)
return 2 * matrix
# Sanity check: Verify that scale_matrix returns the correct output.
self.assertAllEqual([[2, 0], [0, 2], [2, 2]], scale_matrix())
# Check that the returned gradient is correct.
grad_function = backprop.implicit_grad(scale_matrix)
grads_and_vars = grad_function()
indexed_slice = grads_and_vars[0][0]
gradient = grads_and_vars[0][0].values
self.assertAllEqual([0, 1, 2], indexed_slice.indices)
self.assertAllEqual([[2, 2], [2, 2], [2, 2]], gradient)
def test_raises_if_empty_feature_columns(self):
with self.assertRaisesRegex(ValueError,
'feature_columns must not be empty'):
df.DenseFeatures(feature_columns=[])(features={})
def test_should_be_dense_column(self):
with self.assertRaisesRegex(ValueError, 'must be a .*DenseColumn'):
df.DenseFeatures(feature_columns=[
fc.categorical_column_with_hash_bucket('wire_cast', 4)
])(
features={
'a': [[0]]
})
def test_does_not_support_dict_columns(self):
with self.assertRaisesRegex(
ValueError, 'Expected feature_columns to be iterable, found dict.'):
df.DenseFeatures(feature_columns={'a': fc.numeric_column('a')})(
features={
'a': [[0]]
})
def test_bare_column(self):
with ops.Graph().as_default():
features = features = {'a': [0.]}
net = df.DenseFeatures(fc.numeric_column('a'))(features)
self.evaluate(variables_lib.global_variables_initializer())
self.evaluate(lookup_ops.tables_initializer())
self.assertAllClose([[0.]], self.evaluate(net))
def test_column_generator(self):
with ops.Graph().as_default():
features = features = {'a': [0.], 'b': [1.]}
columns = (fc.numeric_column(key) for key in features)
net = df.DenseFeatures(columns)(features)
self.evaluate(variables_lib.global_variables_initializer())
self.evaluate(lookup_ops.tables_initializer())
self.assertAllClose([[0., 1.]], self.evaluate(net))
def test_raises_if_duplicate_name(self):
with self.assertRaisesRegex(
ValueError, 'Duplicate feature column name found for columns'):
df.DenseFeatures(
feature_columns=[fc.numeric_column('a'),
fc.numeric_column('a')])(
features={
'a': [[0]]
})
def test_one_column(self):
price = fc.numeric_column('price')
with ops.Graph().as_default():
features = {'price': [[1.], [5.]]}
net = df.DenseFeatures([price])(features)
self.evaluate(variables_lib.global_variables_initializer())
self.evaluate(lookup_ops.tables_initializer())
self.assertAllClose([[1.], [5.]], self.evaluate(net))
def test_multi_dimension(self):
price = fc.numeric_column('price', shape=2)
with ops.Graph().as_default():
features = {'price': [[1., 2.], [5., 6.]]}
net = df.DenseFeatures([price])(features)
self.evaluate(variables_lib.global_variables_initializer())
self.evaluate(lookup_ops.tables_initializer())
self.assertAllClose([[1., 2.], [5., 6.]], self.evaluate(net))
def test_compute_output_shape(self):
price1 = fc.numeric_column('price1', shape=2)
price2 = fc.numeric_column('price2', shape=4)
with ops.Graph().as_default():
features = {
'price1': [[1., 2.], [5., 6.]],
'price2': [[3., 4., 5., 6.], [7., 8., 9., 10.]]
}
dense_features = df.DenseFeatures([price1, price2])
self.assertEqual((None, 6), dense_features.compute_output_shape((None,)))
net = dense_features(features)
self.evaluate(variables_lib.global_variables_initializer())
self.evaluate(lookup_ops.tables_initializer())
self.assertAllClose([[1., 2., 3., 4., 5., 6.], [5., 6., 7., 8., 9., 10.]],
self.evaluate(net))
def test_raises_if_shape_mismatch(self):
price = fc.numeric_column('price', shape=2)
with ops.Graph().as_default():
features = {'price': [[1.], [5.]]}
with self.assertRaisesRegex(
Exception,
r'Cannot reshape a tensor with 2 elements to shape \[2,2\]'):
df.DenseFeatures([price])(features)
def test_reshaping(self):
price = fc.numeric_column('price', shape=[1, 2])
with ops.Graph().as_default():
features = {'price': [[[1., 2.]], [[5., 6.]]]}
net = df.DenseFeatures([price])(features)
self.evaluate(variables_lib.global_variables_initializer())
self.evaluate(lookup_ops.tables_initializer())
self.assertAllClose([[1., 2.], [5., 6.]], self.evaluate(net))
def test_multi_column(self):
price1 = fc.numeric_column('price1', shape=2)
price2 = fc.numeric_column('price2')
with ops.Graph().as_default():
features = {'price1': [[1., 2.], [5., 6.]], 'price2': [[3.], [4.]]}
net = df.DenseFeatures([price1, price2])(features)
self.evaluate(variables_lib.global_variables_initializer())
self.evaluate(lookup_ops.tables_initializer())
self.assertAllClose([[1., 2., 3.], [5., 6., 4.]], self.evaluate(net))
def test_cols_to_output_tensors(self):
price1 = fc.numeric_column('price1', shape=2)
price2 = fc.numeric_column('price2')
with ops.Graph().as_default():
cols_dict = {}
features = {'price1': [[1., 2.], [5., 6.]], 'price2': [[3.], [4.]]}
dense_features = df.DenseFeatures([price1, price2])
net = dense_features(features, cols_dict)
self.evaluate(variables_lib.global_variables_initializer())
self.evaluate(lookup_ops.tables_initializer())
self.assertAllClose([[1., 2.], [5., 6.]],
self.evaluate(cols_dict[price1]))
self.assertAllClose([[3.], [4.]], self.evaluate(cols_dict[price2]))
self.assertAllClose([[1., 2., 3.], [5., 6., 4.]], self.evaluate(net))
def test_column_order(self):
price_a = fc.numeric_column('price_a')
price_b = fc.numeric_column('price_b')
with ops.Graph().as_default():
features = {
'price_a': [[1.]],
'price_b': [[3.]],
}
net1 = df.DenseFeatures([price_a, price_b])(features)
net2 = df.DenseFeatures([price_b, price_a])(features)
self.evaluate(variables_lib.global_variables_initializer())
self.evaluate(lookup_ops.tables_initializer())
self.assertAllClose([[1., 3.]], self.evaluate(net1))
self.assertAllClose([[1., 3.]], self.evaluate(net2))
def test_fails_for_categorical_column(self):
animal = fc.categorical_column_with_identity('animal', num_buckets=4)
with ops.Graph().as_default():
features = {
'animal':
sparse_tensor.SparseTensor(
indices=[[0, 0], [0, 1]], values=[1, 2], dense_shape=[1, 2])
}
with self.assertRaisesRegex(Exception, 'must be a .*DenseColumn'):
df.DenseFeatures([animal])(features)
def test_static_batch_size_mismatch(self):
price1 = fc.numeric_column('price1')
price2 = fc.numeric_column('price2')
with ops.Graph().as_default():
features = {
'price1': [[1.], [5.], [7.]], # batchsize = 3
'price2': [[3.], [4.]] # batchsize = 2
}
with self.assertRaisesRegex(
ValueError,
r'Batch size \(first dimension\) of each feature must be same.'): # pylint: disable=anomalous-backslash-in-string
df.DenseFeatures([price1, price2])(features)
def test_subset_of_static_batch_size_mismatch(self):
price1 = fc.numeric_column('price1')
price2 = fc.numeric_column('price2')
price3 = fc.numeric_column('price3')
with ops.Graph().as_default():
features = {
'price1': array_ops.placeholder(dtype=dtypes.int64), # batchsize = 3
'price2': [[3.], [4.]], # batchsize = 2
'price3': [[3.], [4.], [5.]] # batchsize = 3
}
with self.assertRaisesRegex(
ValueError,
r'Batch size \(first dimension\) of each feature must be same.'): # pylint: disable=anomalous-backslash-in-string
df.DenseFeatures([price1, price2, price3])(features)
def test_runtime_batch_size_mismatch(self):
price1 = fc.numeric_column('price1')
price2 = fc.numeric_column('price2')
with ops.Graph().as_default():
features = {
'price1': array_ops.placeholder(dtype=dtypes.int64), # batchsize = 3
'price2': [[3.], [4.]] # batchsize = 2
}
net = df.DenseFeatures([price1, price2])(features)
with _initialized_session() as sess:
with self.assertRaisesRegex(errors.OpError,
'Dimensions of inputs should match'):
sess.run(net, feed_dict={features['price1']: [[1.], [5.], [7.]]})
def test_runtime_batch_size_matches(self):
price1 = fc.numeric_column('price1')
price2 = fc.numeric_column('price2')
with ops.Graph().as_default():
features = {
'price1': array_ops.placeholder(dtype=dtypes.int64), # batchsize = 2
'price2': array_ops.placeholder(dtype=dtypes.int64), # batchsize = 2
}
net = df.DenseFeatures([price1, price2])(features)
with _initialized_session() as sess:
sess.run(
net,
feed_dict={
features['price1']: [[1.], [5.]],
features['price2']: [[1.], [5.]],
})
def test_multiple_layers_with_same_embedding_column(self):
some_sparse_column = fc.categorical_column_with_hash_bucket(
'sparse_feature', hash_bucket_size=5)
some_embedding_column = fc.embedding_column(
some_sparse_column, dimension=10)
with ops.Graph().as_default():
features = {
'sparse_feature': [['a'], ['x']],
}
all_cols = [some_embedding_column]
df.DenseFeatures(all_cols)(features)
df.DenseFeatures(all_cols)(features)
# Make sure that 2 variables get created in this case.
self.assertEqual(2,
len(ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)))
expected_var_names = [
'dense_features/sparse_feature_embedding/embedding_weights:0',
'dense_features_1/sparse_feature_embedding/embedding_weights:0'
]
self.assertItemsEqual(
expected_var_names,
[v.name for v in ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)])
@test_util.run_deprecated_v1
def test_multiple_layers_with_same_shared_embedding_column(self):
categorical_column_a = fc.categorical_column_with_identity(
key='aaa', num_buckets=3)
categorical_column_b = fc.categorical_column_with_identity(
key='bbb', num_buckets=3)
embedding_dimension = 2
embedding_column_b, embedding_column_a = fc.shared_embedding_columns_v2(
[categorical_column_b, categorical_column_a],
dimension=embedding_dimension)
with ops.Graph().as_default():
features = {
'aaa':
sparse_tensor.SparseTensor(
indices=((0, 0), (1, 0), (1, 1)),
values=(0, 1, 0),
dense_shape=(2, 2)),
'bbb':
sparse_tensor.SparseTensor(
indices=((0, 0), (1, 0), (1, 1)),
values=(1, 2, 1),
dense_shape=(2, 2)),
}
all_cols = [embedding_column_a, embedding_column_b]
df.DenseFeatures(all_cols)(features)
df.DenseFeatures(all_cols)(features)
# Make sure that only 1 variable gets created in this case.
self.assertEqual(1,
len(ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)))
self.assertItemsEqual(
['aaa_bbb_shared_embedding:0'],
[v.name for v in ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)])
@test_util.run_deprecated_v1
def test_multiple_layers_with_same_shared_embedding_column_diff_graphs(self):
categorical_column_a = fc.categorical_column_with_identity(
key='aaa', num_buckets=3)
categorical_column_b = fc.categorical_column_with_identity(
key='bbb', num_buckets=3)
embedding_dimension = 2
embedding_column_b, embedding_column_a = fc.shared_embedding_columns_v2(
[categorical_column_b, categorical_column_a],
dimension=embedding_dimension)
all_cols = [embedding_column_a, embedding_column_b]
with ops.Graph().as_default():
features = {
'aaa':
sparse_tensor.SparseTensor(
indices=((0, 0), (1, 0), (1, 1)),
values=(0, 1, 0),
dense_shape=(2, 2)),
'bbb':
sparse_tensor.SparseTensor(
indices=((0, 0), (1, 0), (1, 1)),
values=(1, 2, 1),
dense_shape=(2, 2)),
}
df.DenseFeatures(all_cols)(features)
# Make sure that only 1 variable gets created in this case.
self.assertEqual(1,
len(ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)))
with ops.Graph().as_default():
features1 = {
'aaa':
sparse_tensor.SparseTensor(
indices=((0, 0), (1, 0), (1, 1)),
values=(0, 1, 0),
dense_shape=(2, 2)),
'bbb':
sparse_tensor.SparseTensor(
indices=((0, 0), (1, 0), (1, 1)),
values=(1, 2, 1),
dense_shape=(2, 2)),
}
df.DenseFeatures(all_cols)(features1)
# Make sure that only 1 variable gets created in this case.
self.assertEqual(1,
len(ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)))
self.assertItemsEqual(
['aaa_bbb_shared_embedding:0'],
[v.name for v in ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)])
@test_util.run_deprecated_v1
def test_with_1d_sparse_tensor(self):
embedding_values = (
(1., 2., 3., 4., 5.), # id 0
(6., 7., 8., 9., 10.), # id 1
(11., 12., 13., 14., 15.) # id 2
)
def _initializer(shape, dtype, partition_info=None):
del shape, dtype, partition_info
return embedding_values
# price has 1 dimension in dense_features
price = fc.numeric_column('price')
# one_hot_body_style has 3 dims in dense_features.
body_style = fc.categorical_column_with_vocabulary_list(
'body-style', vocabulary_list=['hardtop', 'wagon', 'sedan'])
one_hot_body_style = fc.indicator_column(body_style)
# embedded_body_style has 5 dims in dense_features.
country = fc.categorical_column_with_vocabulary_list(
'country', vocabulary_list=['US', 'JP', 'CA'])
embedded_country = fc.embedding_column(
country, dimension=5, initializer=_initializer)
# Provides 1-dim tensor and dense tensor.
features = {
'price':
constant_op.constant([
11.,
12.,
]),
'body-style':
sparse_tensor.SparseTensor(
indices=((0,), (1,)),
values=('sedan', 'hardtop'),
dense_shape=(2,)),
# This is dense tensor for the categorical_column.
'country':
constant_op.constant(['CA', 'US']),
}
self.assertEqual(1, features['price'].shape.ndims)
self.assertEqual(1, features['body-style'].dense_shape.get_shape()[0])
self.assertEqual(1, features['country'].shape.ndims)
net = df.DenseFeatures([price, one_hot_body_style, embedded_country])(
features)
self.assertEqual(1 + 3 + 5, net.shape[1])
with _initialized_session() as sess:
# Each row is formed by concatenating `embedded_body_style`,
# `one_hot_body_style`, and `price` in order.
self.assertAllEqual([[0., 0., 1., 11., 12., 13., 14., 15., 11.],
[1., 0., 0., 1., 2., 3., 4., 5., 12.]],
sess.run(net))
@test_util.run_deprecated_v1
def test_with_1d_unknown_shape_sparse_tensor(self):
embedding_values = (
(1., 2.), # id 0
(6., 7.), # id 1
(11., 12.) # id 2
)
def _initializer(shape, dtype, partition_info=None):
del shape, dtype, partition_info
return embedding_values
# price has 1 dimension in dense_features
price = fc.numeric_column('price')
# one_hot_body_style has 3 dims in dense_features.
body_style = fc.categorical_column_with_vocabulary_list(
'body-style', vocabulary_list=['hardtop', 'wagon', 'sedan'])
one_hot_body_style = fc.indicator_column(body_style)
# embedded_body_style has 5 dims in dense_features.
country = fc.categorical_column_with_vocabulary_list(
'country', vocabulary_list=['US', 'JP', 'CA'])
embedded_country = fc.embedding_column(
country, dimension=2, initializer=_initializer)
# Provides 1-dim tensor and dense tensor.
features = {
'price': array_ops.placeholder(dtypes.float32),
'body-style': array_ops.sparse_placeholder(dtypes.string),
# This is dense tensor for the categorical_column.
'country': array_ops.placeholder(dtypes.string),
}
self.assertIsNone(features['price'].shape.ndims)
self.assertIsNone(features['body-style'].get_shape().ndims)
self.assertIsNone(features['country'].shape.ndims)
price_data = np.array([11., 12.])
body_style_data = sparse_tensor.SparseTensorValue(
indices=((0,), (1,)), values=('sedan', 'hardtop'), dense_shape=(2,))
country_data = np.array([['US'], ['CA']])
net = df.DenseFeatures([price, one_hot_body_style, embedded_country])(
features)
self.assertEqual(1 + 3 + 2, net.shape[1])
with _initialized_session() as sess:
# Each row is formed by concatenating `embedded_body_style`,
# `one_hot_body_style`, and `price` in order.
self.assertAllEqual(
[[0., 0., 1., 1., 2., 11.], [1., 0., 0., 11., 12., 12.]],
sess.run(
net,
feed_dict={
features['price']: price_data,
features['body-style']: body_style_data,
features['country']: country_data
}))
@test_util.run_deprecated_v1
def test_with_rank_0_feature(self):
# price has 1 dimension in dense_features
price = fc.numeric_column('price')
features = {
'price': constant_op.constant(0),
}
self.assertEqual(0, features['price'].shape.ndims)
# Static rank 0 should fail
with self.assertRaisesRegex(ValueError, 'Feature .* cannot have rank 0'):
df.DenseFeatures([price])(features)
# Dynamic rank 0 should fail
features = {
'price': array_ops.placeholder(dtypes.float32),
}
net = df.DenseFeatures([price])(features)
self.assertEqual(1, net.shape[1])
with _initialized_session() as sess:
with self.assertRaisesOpError('Feature .* cannot have rank 0'):
sess.run(net, feed_dict={features['price']: np.array(1)})
class IndicatorColumnTest(test.TestCase):
@test_util.run_deprecated_v1
def test_dense_features(self):
animal = fc.indicator_column(
fc.categorical_column_with_identity('animal', num_buckets=4))
with ops.Graph().as_default():
features = {
'animal':
sparse_tensor.SparseTensor(
indices=[[0, 0], [0, 1]], values=[1, 2], dense_shape=[1, 2])
}
net = df.DenseFeatures([animal])(features)
self.evaluate(variables_lib.global_variables_initializer())
self.evaluate(lookup_ops.tables_initializer())
self.assertAllClose([[0., 1., 1., 0.]], self.evaluate(net))
class EmbeddingColumnTest(test.TestCase, parameterized.TestCase):
@parameterized.named_parameters(
{
'testcase_name': 'use_safe_embedding_lookup',
'use_safe_embedding_lookup': True,
'partition_variables': False,
}, {
'testcase_name': 'dont_use_safe_embedding_lookup',
'use_safe_embedding_lookup': False,
'partition_variables': False,
}, {
'testcase_name': 'use_safe_embedding_lookup_partitioned',
'use_safe_embedding_lookup': True,
'partition_variables': True,
}, {
'testcase_name': 'dont_use_safe_embedding_lookup_partitioned',
'use_safe_embedding_lookup': False,
'partition_variables': True,
})
@test_util.run_deprecated_v1
def test_dense_features(self, use_safe_embedding_lookup, partition_variables):
# Inputs.
vocabulary_size = 4
sparse_input = sparse_tensor.SparseTensorValue(
# example 0, ids [2]
# example 1, ids [0, 1]
# example 2, ids []
# example 3, ids [1]
indices=((0, 0), (1, 0), (1, 4), (3, 0)),
values=(2, 0, 1, 1),
dense_shape=(4, 5))
# Embedding variable.
embedding_dimension = 2
embedding_values = (
(1., 2.), # id 0
(3., 5.), # id 1
(7., 11.), # id 2
(9., 13.) # id 3
)
def _initializer(shape, dtype, partition_info=None):
if partition_variables:
self.assertEqual([vocabulary_size, embedding_dimension],
partition_info.full_shape)
self.assertAllEqual((2, embedding_dimension), shape)
else:
self.assertAllEqual((vocabulary_size, embedding_dimension), shape)
self.assertIsNone(partition_info)
self.assertEqual(dtypes.float32, dtype)
return embedding_values
# Expected lookup result, using combiner='mean'.
expected_lookups = (
# example 0, ids [2], embedding = [7, 11]
(7., 11.),
# example 1, ids [0, 1], embedding = mean([1, 2] + [3, 5]) = [2, 3.5]
(2., 3.5),
# example 2, ids [], embedding = [0, 0]
(0., 0.),
# example 3, ids [1], embedding = [3, 5]
(3., 5.),
)
# Build columns.
categorical_column = fc.categorical_column_with_identity(
key='aaa', num_buckets=vocabulary_size)
partitioner = None
if partition_variables:
partitioner = partitioned_variables.fixed_size_partitioner(2, axis=0)
with variable_scope.variable_scope('vars', partitioner=partitioner):
embedding_column = fc.embedding_column(
categorical_column,
dimension=embedding_dimension,
initializer=_initializer,
use_safe_embedding_lookup=use_safe_embedding_lookup)
# Provide sparse input and get dense result.
l = df.DenseFeatures((embedding_column,))
dense_features = l({'aaa': sparse_input})
# Assert expected embedding variable and lookups.
global_vars = ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)
if partition_variables:
self.assertCountEqual(
('vars/dense_features/aaa_embedding/embedding_weights/part_0:0',
'vars/dense_features/aaa_embedding/embedding_weights/part_1:0'),
tuple([v.name for v in global_vars]))
else:
self.assertCountEqual(
('vars/dense_features/aaa_embedding/embedding_weights:0',),
tuple([v.name for v in global_vars]))
for v in global_vars:
self.assertIsInstance(v, variables_lib.Variable)
trainable_vars = ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES)
if partition_variables:
self.assertCountEqual(
('vars/dense_features/aaa_embedding/embedding_weights/part_0:0',
'vars/dense_features/aaa_embedding/embedding_weights/part_1:0'),
tuple([v.name for v in trainable_vars]))
else:
self.assertCountEqual(
('vars/dense_features/aaa_embedding/embedding_weights:0',),
tuple([v.name for v in trainable_vars]))
self.evaluate(variables_lib.global_variables_initializer())
self.evaluate(lookup_ops.tables_initializer())
self.assertAllEqual(embedding_values, self.evaluate(trainable_vars[0]))
self.assertAllEqual(expected_lookups, self.evaluate(dense_features))
if use_safe_embedding_lookup:
self.assertIn('SparseFillEmptyRows',
[x.type for x in ops.get_default_graph().get_operations()])
else:
self.assertNotIn(
'SparseFillEmptyRows',
[x.type for x in ops.get_default_graph().get_operations()])
@test_util.run_deprecated_v1
def test_dense_features_not_trainable(self):
# Inputs.
vocabulary_size = 3
sparse_input = sparse_tensor.SparseTensorValue(
# example 0, ids [2]
# example 1, ids [0, 1]
# example 2, ids []
# example 3, ids [1]
indices=((0, 0), (1, 0), (1, 4), (3, 0)),
values=(2, 0, 1, 1),
dense_shape=(4, 5))
# Embedding variable.
embedding_dimension = 2
embedding_values = (
(1., 2.), # id 0
(3., 5.), # id 1
(7., 11.) # id 2
)
def _initializer(shape, dtype, partition_info=None):
self.assertAllEqual((vocabulary_size, embedding_dimension), shape)
self.assertEqual(dtypes.float32, dtype)
self.assertIsNone(partition_info)
return embedding_values
# Expected lookup result, using combiner='mean'.
expected_lookups = (
# example 0, ids [2], embedding = [7, 11]
(7., 11.),
# example 1, ids [0, 1], embedding = mean([1, 2] + [3, 5]) = [2, 3.5]
(2., 3.5),
# example 2, ids [], embedding = [0, 0]
(0., 0.),
# example 3, ids [1], embedding = [3, 5]
(3., 5.),
)
# Build columns.
categorical_column = fc.categorical_column_with_identity(
key='aaa', num_buckets=vocabulary_size)
embedding_column = fc.embedding_column(
categorical_column,
dimension=embedding_dimension,
initializer=_initializer,
trainable=False)
# Provide sparse input and get dense result.
dense_features = df.DenseFeatures((embedding_column,))({
'aaa': sparse_input
})
# Assert expected embedding variable and lookups.
global_vars = ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)
self.assertCountEqual(('dense_features/aaa_embedding/embedding_weights:0',),
tuple([v.name for v in global_vars]))
self.assertCountEqual([],
ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES))
self.evaluate(variables_lib.global_variables_initializer())
self.evaluate(lookup_ops.tables_initializer())
self.assertAllEqual(embedding_values, self.evaluate(global_vars[0]))
self.assertAllEqual(expected_lookups, self.evaluate(dense_features))
class SharedEmbeddingColumnTest(test.TestCase, parameterized.TestCase):
def _test_dense_features(self, trainable=True):
# Inputs.
vocabulary_size = 3
sparse_input_a = sparse_tensor.SparseTensorValue(
# example 0, ids [2]
# example 1, ids [0, 1]
indices=((0, 0), (1, 0), (1, 4)),
values=(2, 0, 1),
dense_shape=(2, 5))
sparse_input_b = sparse_tensor.SparseTensorValue(
# example 0, ids [0]
# example 1, ids []
indices=((0, 0),),
values=(0,),
dense_shape=(2, 5))
sparse_input_c = sparse_tensor.SparseTensorValue(
# example 0, ids [2]
# example 1, ids [0, 1]
indices=((0, 1), (1, 1), (1, 3)),
values=(2, 0, 1),
dense_shape=(2, 5))
sparse_input_d = sparse_tensor.SparseTensorValue(
# example 0, ids [2]
# example 1, ids []
indices=((0, 1),),
values=(2,),
dense_shape=(2, 5))
# Embedding variable.
embedding_dimension = 2
embedding_values = (
(1., 2.), # id 0
(3., 5.), # id 1
(7., 11.) # id 2
)
def _initializer(shape, dtype, partition_info=None):
self.assertAllEqual((vocabulary_size, embedding_dimension), shape)
self.assertEqual(dtypes.float32, dtype)
self.assertIsNone(partition_info)
return embedding_values
# Expected lookup result, using combiner='mean'.
expected_lookups = (
# example 0:
# A ids [2], embedding = [7, 11]
# B ids [0], embedding = [1, 2]
# C ids [2], embedding = [7, 11]
# D ids [2], embedding = [7, 11]
(7., 11., 1., 2., 7., 11., 7., 11.),
# example 1:
# A ids [0, 1], embedding = mean([1, 2] + [3, 5]) = [2, 3.5]
# B ids [], embedding = [0, 0]
# C ids [0, 1], embedding = mean([1, 2] + [3, 5]) = [2, 3.5]
# D ids [], embedding = [0, 0]
(2., 3.5, 0., 0., 2., 3.5, 0., 0.),
)
# Build columns.
categorical_column_a = fc.categorical_column_with_identity(
key='aaa', num_buckets=vocabulary_size)
categorical_column_b = fc.categorical_column_with_identity(
key='bbb', num_buckets=vocabulary_size)
categorical_column_c = fc.categorical_column_with_identity(
key='ccc', num_buckets=vocabulary_size)
categorical_column_d = fc.categorical_column_with_identity(
key='ddd', num_buckets=vocabulary_size)
embedding_column_a, embedding_column_b = fc.shared_embedding_columns_v2(
[categorical_column_a, categorical_column_b],
dimension=embedding_dimension,
initializer=_initializer,
trainable=trainable)
embedding_column_c, embedding_column_d = fc.shared_embedding_columns_v2(
[categorical_column_c, categorical_column_d],
dimension=embedding_dimension,
initializer=_initializer,
trainable=trainable)
features = {
'aaa': sparse_input_a,
'bbb': sparse_input_b,
'ccc': sparse_input_c,
'ddd': sparse_input_d
}
# Provide sparse input and get dense result.
dense_features = df.DenseFeatures(
feature_columns=(embedding_column_b, embedding_column_a,
embedding_column_c, embedding_column_d))(
features)
# Assert expected embedding variable and lookups.
global_vars = ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)
self.assertCountEqual(
['aaa_bbb_shared_embedding:0', 'ccc_ddd_shared_embedding:0'],
tuple([v.name for v in global_vars]))
for v in global_vars:
self.assertIsInstance(v, variables_lib.Variable)
trainable_vars = ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES)
if trainable:
self.assertCountEqual(
['aaa_bbb_shared_embedding:0', 'ccc_ddd_shared_embedding:0'],
tuple([v.name for v in trainable_vars]))
else:
self.assertCountEqual([], tuple([v.name for v in trainable_vars]))
shared_embedding_vars = global_vars
self.evaluate(variables_lib.global_variables_initializer())
self.evaluate(lookup_ops.tables_initializer())
self.assertAllEqual(embedding_values,
self.evaluate(shared_embedding_vars[0]))
self.assertAllEqual(expected_lookups, self.evaluate(dense_features))
@test_util.run_deprecated_v1
def test_dense_features(self):
self._test_dense_features()
@test_util.run_deprecated_v1
def test_dense_features_no_trainable(self):
self._test_dense_features(trainable=False)
@combinations.generate(combinations.combine(mode=['graph', 'eager']))
class DenseFeaturesSerializationTest(test.TestCase, parameterized.TestCase):
@parameterized.named_parameters(
('default', None, None),
('trainable', True, 'trainable'),
('not_trainable', False, 'frozen'))
def test_get_config(self, trainable, name):
cols = [fc.numeric_column('a'),
fc.embedding_column(fc.categorical_column_with_identity(
key='b', num_buckets=3), dimension=2)]
orig_layer = df.DenseFeatures(
cols, trainable=trainable, name=name)
config = orig_layer.get_config()
self.assertEqual(config['name'], orig_layer.name)
self.assertEqual(config['trainable'], trainable)
self.assertLen(config['feature_columns'], 2)
self.assertEqual(
config['feature_columns'][0]['class_name'], 'NumericColumn')
self.assertEqual(config['feature_columns'][0]['config']['shape'], (1,))
self.assertEqual(
config['feature_columns'][1]['class_name'], 'EmbeddingColumn')
@parameterized.named_parameters(
('default', None, None),
('trainable', True, 'trainable'),
('not_trainable', False, 'frozen'))
def test_from_config(self, trainable, name):
cols = [fc.numeric_column('a'),
fc.embedding_column(fc.categorical_column_with_vocabulary_list(
'b', vocabulary_list=['1', '2', '3']), dimension=2),
fc.indicator_column(fc.categorical_column_with_hash_bucket(
key='c', hash_bucket_size=3))]
orig_layer = df.DenseFeatures(
cols, trainable=trainable, name=name)
config = orig_layer.get_config()
new_layer = df.DenseFeatures.from_config(config)
self.assertEqual(new_layer.name, orig_layer.name)
self.assertEqual(new_layer.trainable, trainable)
self.assertLen(new_layer._feature_columns, 3)
self.assertEqual(new_layer._feature_columns[0].name, 'a')
self.assertEqual(new_layer._feature_columns[1].initializer.mean, 0.0)
self.assertEqual(new_layer._feature_columns[1].categorical_column.name, 'b')
self.assertIsInstance(new_layer._feature_columns[2], fc.IndicatorColumn)
def test_crossed_column(self):
a = fc.categorical_column_with_vocabulary_list(
'a', vocabulary_list=['1', '2', '3'])
b = fc.categorical_column_with_vocabulary_list(
'b', vocabulary_list=['1', '2', '3'])
ab = fc.crossed_column([a, b], hash_bucket_size=2)
cols = [fc.indicator_column(ab)]
orig_layer = df.DenseFeatures(cols)
config = orig_layer.get_config()
new_layer = df.DenseFeatures.from_config(config)
self.assertLen(new_layer._feature_columns, 1)
self.assertEqual(new_layer._feature_columns[0].name, 'a_X_b_indicator')
@combinations.generate(combinations.combine(mode=['graph', 'eager']))
class SequenceFeatureColumnsTest(test.TestCase):
"""Tests DenseFeatures with sequence feature columns."""
def test_embedding_column(self):
"""Tests that error is raised for sequence embedding column."""
vocabulary_size = 3
sparse_input = sparse_tensor.SparseTensorValue(
# example 0, ids [2]
# example 1, ids [0, 1]
indices=((0, 0), (1, 0), (1, 1)),
values=(2, 0, 1),
dense_shape=(2, 2))
categorical_column_a = sfc.sequence_categorical_column_with_identity(
key='aaa', num_buckets=vocabulary_size)
embedding_column_a = fc.embedding_column(
categorical_column_a, dimension=2)
input_layer = df.DenseFeatures([embedding_column_a])
with self.assertRaisesRegex(
ValueError,
r'In embedding_column: aaa_embedding\. categorical_column must not be '
r'of type SequenceCategoricalColumn\.'):
_ = input_layer({'aaa': sparse_input})
def test_indicator_column(self):
"""Tests that error is raised for sequence indicator column."""
vocabulary_size = 3
sparse_input = sparse_tensor.SparseTensorValue(
# example 0, ids [2]
# example 1, ids [0, 1]
indices=((0, 0), (1, 0), (1, 1)),
values=(2, 0, 1),
dense_shape=(2, 2))
categorical_column_a = sfc.sequence_categorical_column_with_identity(
key='aaa', num_buckets=vocabulary_size)
indicator_column_a = fc.indicator_column(categorical_column_a)
input_layer = df.DenseFeatures([indicator_column_a])
with self.assertRaisesRegex(
ValueError,
r'In indicator_column: aaa_indicator\. categorical_column must not be '
r'of type SequenceCategoricalColumn\.'):
_ = input_layer({'aaa': sparse_input})
if __name__ == '__main__':
test.main()
| |
import time
import sys
import serial
import os
import time
import datetime
import cwiid
# Button
'''
https://github.com/abstrakraft/cwiid/blob/master/libcwiid/cwiid.h
'''
CWIID_BTN_2 = 0x0001
CWIID_BTN_1 = 0x0002
CWIID_BTN_B = 0x0004
CWIID_BTN_A = 0x0008
CWIID_BTN_MINUS = 0x0010
CWIID_BTN_HOME = 0x0080
CWIID_BTN_LEFT = 0x0100
CWIID_BTN_RIGHT = 0x0200
CWIID_BTN_DOWN = 0x0400
CWIID_BTN_UP = 0x0800
CWIID_BTN_PLUS = 0x1000
CWIID_NUNCHUK_BTN_Z = 0x01
CWIID_NUNCHUK_BTN_C =0x02
CWIID_CLASSIC_BTN_UP = 0x0001
CWIID_CLASSIC_BTN_LEFT = 0x0002
CWIID_CLASSIC_BTN_ZR = 0x0004
CWIID_CLASSIC_BTN_X = 0x0008
CWIID_CLASSIC_BTN_A = 0x0010
CWIID_CLASSIC_BTN_Y = 0x0020
CWIID_CLASSIC_BTN_B = 0x0040
CWIID_CLASSIC_BTN_ZL = 0x0080
CWIID_CLASSIC_BTN_R = 0x0200
CWIID_CLASSIC_BTN_PLUS = 0x0400
CWIID_CLASSIC_BTN_HOME = 0x0800
CWIID_CLASSIC_BTN_MINUS = 0x1000
CWIID_CLASSIC_BTN_L = 0x2000
CWIID_CLASSIC_BTN_DOWN = 0x4000
CWIID_CLASSIC_BTN_RIGHT = 0x8000
but2act = {
0: {'type':'NON', 'pressed':'#M00'},
CWIID_BTN_2: {'type':'BTN_2', 'pressed':'#M08'},
CWIID_BTN_1: {'type':'BTN_1', 'pressed':'#M07'},
CWIID_BTN_B: {'type':'BTN_B', 'pressed':'#M00'},
CWIID_BTN_A: {'type':'BTN_A', 'pressed':'#M05'},
CWIID_BTN_MINUS:{'type':'BTN_MINUS','pressed':'#M09'},
CWIID_BTN_HOME: {'type':'BTN_HOME', 'pressed':'#M10'},
CWIID_BTN_LEFT: {'type':'BTN_LEFT', 'pressed':'#M04'},
CWIID_BTN_RIGHT:{'type':'BTN_RIGHT','pressed':'#M03'},
CWIID_BTN_DOWN: {'type':'BTN_DOWN', 'pressed':'#M02'},
CWIID_BTN_UP: {'type':'BTN_UP', 'pressed':'#M01'},
CWIID_BTN_PLUS: {'type':'BTN_PLUS', 'pressed':'#M06'},
CWIID_BTN_PLUS|
CWIID_BTN_MINUS:{'type':'BTN_PLUS&BTN_MINUS', 'pressed':'#M06'}
}
cbut2act = {
0: {'type':'NON', 'pressed':'#M00'},
CWIID_CLASSIC_BTN_ZR: {'type':'CBTN_ZR', 'pressed':'#M00'},
CWIID_CLASSIC_BTN_ZL: {'type':'CBTN_ZL', 'pressed':'#M00'},
CWIID_CLASSIC_BTN_R: {'type':'CBTN_R', 'pressed':'#M00'},
CWIID_CLASSIC_BTN_L: {'type':'CBTN_L', 'pressed':'#M00'},
CWIID_CLASSIC_BTN_Y: {'type':'CBTN_2', 'pressed':'#M08'},
CWIID_CLASSIC_BTN_X: {'type':'CBTN_1', 'pressed':'#M07'},
CWIID_CLASSIC_BTN_B: {'type':'CBTN_B', 'pressed':'#M00'},
CWIID_CLASSIC_BTN_A: {'type':'CBTN_A', 'pressed':'#M05'},
CWIID_CLASSIC_BTN_MINUS:{'type':'CBTN_MINUS','pressed':'#M09'},
CWIID_CLASSIC_BTN_HOME: {'type':'CBTN_HOME', 'pressed':'#M10'},
CWIID_CLASSIC_BTN_LEFT: {'type':'CBTN_LEFT', 'pressed':'#M04'},
CWIID_CLASSIC_BTN_RIGHT:{'type':'CBTN_RIGHT','pressed':'#M03'},
CWIID_CLASSIC_BTN_DOWN: {'type':'CBTN_DOWN', 'pressed':'#M02'},
CWIID_CLASSIC_BTN_UP: {'type':'CBTN_UP', 'pressed':'#M01'},
CWIID_CLASSIC_BTN_PLUS: {'type':'CBTN_PLUS', 'pressed':'#M06'},
CWIID_CLASSIC_BTN_PLUS|
CWIID_CLASSIC_BTN_MINUS:{'type':'CBTN_PLUS&CBTN_MINUS', 'pressed':'#M06'}
}
#Serial connection for interfacting with Arduino board on Rapiro
rapiro = serial.Serial('/dev/ttyAMA0', 57600, timeout = 10)
#
BTN_STATE = 0
BTN_PREV = 0
#Container for joystik input
data = []
#Define colors codes and maximum intensity for the RGB LED
MAXRED = 255
MAXGREEN = 225
MAXBLUE = 255
MAXTIME = 005
RED = MAXRED
GREEN = MAXGREEN
BLUE = MAXBLUE
TIME = MAXTIME
#RGB COLOR program with timing.
def led(RED,GREEN,BLUE,TIME):
s = "#PR" + str(RED).zfill(3) + "G" + str(GREEN).zfill(3) + "B" + str(BLUE).zfill(3) + "T" + str(TIME).zfill(3)
return (s)
def PS(RUD, RLR, LUD, LLR):
s = "#PS02A" + str(RUD).zfill(3) + "S03A" + str(RLR).zfill(3) + "S05A" + str(LUD).zfill(3) + "S06A" + str(LLR).zfill(3) + "T002\r\n"
return (s)
#Print Max values, and Changing colors. All max= White.
#TIME is the fading speed 000 change the color instantaneously, 255 very slowly.
rapiro.write(led(RED,GREEN,BLUE,TIME))
print(led(RED,GREEN,BLUE,TIME))
time.sleep(0.2)
rapiro.write(led(147,023,239,020))
print rapiro.write('#H')
print 'now we play with the Wiimote..\n'
time.sleep(0.5)
LLRLIMIT = 70 #20 #S06 Left analog stick Left - Right
LUDLIMIT = 180 #120 #S05 Left analog stick UP - DOWN
RLRLIMIT = 110 #100 #S03 Right analog stick Left - Right
RUDLIMIT = 0 #S02 Right analog stick UP - DOWN
LLR = LLRLIMIT
LUD = LUDLIMIT
RLR = RLRLIMIT
RUD = RUDLIMIT
LSX = 32
LSY = 32
RSX = 15
RSY = 15
befor_LSX = 32
befor_LSY = 32
befor_RSX = 15
befor_RSY = 15
before_time = 0
now_time = 0
#connecting to the wiimote. This allows several attempts
# as first few often fail.
print 'Press 1 + 2 on your Wii Remote now ...'
time.sleep(1)
wm = None
i=2
while not wm:
try:
wm=cwiid.Wiimote()
except RuntimeError:
if (i>5):
print("cannot create connection")
quit()
print "Error opening wiimote connection"
print "attempt " + str(i)
i +=1
print 'Wii Remote connected...\n'
print 'Press PLUS and MINUS together to disconnect and quit.\n'
wm.rumble = 1
time.sleep(0.5)
wm.rumble = 0
#set wiimote to report button presses and accelerometer state
wm.rpt_mode = cwiid.RPT_BTN | cwiid.RPT_ACC | cwiid.RPT_CLASSIC | cwiid.RPT_NUNCHUK
#turn on led to show connection has been established
wm.led = 1
button_delay = 0.3
wiibuttons = 0
before_wiibuttons = 0
classicbuttons = 0
before_classicbuttons = 0
wiiacc = [0,0,0]
before_wiiacc = [0,0,0]
acc_state = 0
CLASSIC_BTN_STATE = 'released'
print 'connected, starting the loop........'
while True:
#wiimote
before_wiibuttons = wiibuttons
before_wiiacc = wiiacc
wiibuttons = wm.state['buttons']
wiiacc = wm.state['acc']
acc_state = 0
for acc0,acc1 in zip(before_wiiacc, wiiacc):
if abs(acc0-acc1)>2 :
acc_state += 1
if wm.state['ext_type']==cwiid.EXT_CLASSIC:
if wm.state.has_key('classic'):
before_classicbuttons = classicbuttons
classicbuttons = wm.state['classic']['buttons']
if (classicbuttons != 0):
CLASSIC_BTN_STATE = 'pressed'
else:
CLASSIC_BTN_STATE = 'released'
LSX = wm.state['classic']['l_stick'][0]
LSY = wm.state['classic']['l_stick'][1]
RSX = wm.state['classic']['r_stick'][0]
RSY = wm.state['classic']['r_stick'][1]
if ((LSX>33)|(LSX<31)|
(LSY>33)|(LSY<31)|
(RSX>16)|(RSX<14)|
(RSY>16)|(RSY<14)):
joy = True
else:
joy = False
else:
joy = False
if (wiibuttons != 0):
BTN_STATE = 'pressed'
else:
BTN_STATE = 'released'
if (BTN_STATE == 'pressed'):
try:
if (before_wiibuttons!= wiibuttons):
print but2act[wiibuttons]['type']
rapiro.write(but2act[wiibuttons]['pressed'])
except:
pass
elif (CLASSIC_BTN_STATE=='pressed'):
#try:
if (before_classicbuttons!= classicbuttons):
print cbut2act[classicbuttons]['type']
rapiro.write(cbut2act[classicbuttons]['pressed'])
#except:
# pass
elif joy:
now = datetime.datetime.now()
now_time = now.minute * 60000 + now.second * 1000 + now.microsecond/1000
if LSX < 30:
LLR += abs(30-LSX)
if LLR > 180:
LLR = 180
elif LSX > 33:
LLR -= abs(33-LSX)
if LLR < LLRLIMIT:
LLR = LLRLIMIT
if LSY < 30:
LUD += abs(30-LSY)
if LUD > 180:
LUD = 180
elif LSY > 33:
LUD -= abs(33-LSY)
if LUD < 0:
LUD = 0
if RSX < 14:
RLR += abs(14-RSX)
if RLR > RLRLIMIT:
RLR = RLRLIMIT
elif RSX > 16:
RLR -= abs(16-RSX)
if RLR < 0:
RLR = 0
if RSY > 16:
RUD += abs(16-RSY)
if RUD > 180:
RUD = 180
elif RSY < 14:
RUD -= abs(14-RSY)
if RUD < 0:
RUD = 0
#print RSX, RSY, LSX, LSY, LLR, LUD, RLR, RUD
dif = now_time - before_time
if dif > 110 and joy == True:
rapiro.write(PS(RUD,RLR,LUD,LLR))
#rapiro.write("ms : " + str(dif) + "\r\n")
now = datetime.datetime.now()
before_time = now.minute * 60000 + now.second * 1000 + now.microsecond/1000
elif acc_state != 0:
rapiro.write(led(wiiacc[0],wiiacc[1],wiiacc[2],TIME))
'''
if (buttons & cwiid.BTN_1):
print (wm.state)
time.sleep(0.8)
if (buttons & cwiid.BTN_2):
print (wm.state)
time.sleep(0.2)
if (buttons - cwiid.BTN_PLUS - cwiid.BTN_MINUS == 0):
print '\nClosing connection ...'
wm.rumble = 1
time.sleep(0.4)
wm.rumble = 0
rapiro.write('#M08')
time.sleep(5)
rapiro.write('#M00')
time.sleep(3)
print '\nExiting program ...'
rapiro.write('#H')
exit(wm)
if (buttons - cwiid.BTN_A - cwiid.BTN_B == 0):
print '\nExtra rapiro movement STOP'
time.sleep(1)
rapiro.write('#H')
if (buttons & cwiid.BTN_HOME):
print 'Home Button pressed'
time.sleep(button_delay)
rapiro.write("#H")
if (buttons & cwiid.BTN_LEFT):
print 'Left pressed'
time.sleep(button_delay)
if(buttons & cwiid.BTN_RIGHT):
print 'Right pressed'
time.sleep(button_delay)
if (buttons & cwiid.BTN_UP):
print 'Up pressed'
time.sleep(button_delay)
if (buttons & cwiid.BTN_DOWN):
print 'Down pressed'
time.sleep(button_delay)
if (buttons & cwiid.BTN_A):
print 'Button A pressed'
time.sleep(button_delay)
if (buttons & cwiid.BTN_B):
print 'INFORMATION YOU NEED TO HACK'
print(wm.state)
time.sleep(button_delay)
print('\nThis is nupposed to change the ligh so adjust the colors to match 0 to 255\n'+"#PR" + str(RED) + "G" + str(GREEN) + "B" + str(BLUE) + 'T' + str(TIME))
print str(wiiacc) + 'wii ACC data in str format\n'
rapiro.write(led(wiiacc[0],wiiacc[1],wiiacc[2],'010'))
if (buttons & cwiid.BTN_MINUS):
print 'Minus Button pressed'
time.sleep(button_delay)
if (buttons & cwiid.BTN_PLUS):
print 'Plus Button pressed'
time.sleep(button_delay)
'''
| |
import os
import time
import random
import re
import copy
import tensorflow as tf
import numpy as np
from utils import *
from data_pipeline import *
class cgan(object):
def __init__(
self,
sess,
epoch,
batch_size,
predicate,
neurons_per_layer,
checkpoint_dir,
result_dir,
log_dir,
input_size):
self.sess = sess
self.checkpoint_dir = checkpoint_dir
self.result_dir = result_dir
self.log_dir = log_dir
self.epoch = epoch
self.batch_size = batch_size
self.model_name = "CGAN"
self.input_size = input_size
self.predicate = predicate
# generate data
datasets = synthetic_data_generator(
predicate, 10000, -50, 50, input_size)
# train
self.dprob = 0.5
self.learning_rate = 0.001
self.beta1 = 0.5
# test
self.sample_num = 64 # number of generated vectors to saved
# load datasets
self.train_vectors = datasets._vectors
self.train_labels = datasets._labels
self.vector_dim = len(datasets._vectors[0])
self.label_dim = len(datasets._labels[0])
# get number of batches for a single epoch
self.num_batches = len(self.train_vectors) // self.batch_size
input_shape = self.vector_dim + self.label_dim
d_output_shape = self.label_dim
g_output_shape = self.vector_dim
cnpl = []
previous_neurons = 0
for index, neurons in enumerate(neurons_per_layer):
if index == 0:
cnpl.append([input_shape, neurons])
else:
cnpl.append([previous_neurons, neurons])
previous_neurons = neurons
dnpl = copy.deepcopy(cnpl)
dnpl.append([previous_neurons, d_output_shape])
gnpl = copy.deepcopy(cnpl)
gnpl.append([previous_neurons, g_output_shape])
self.dnpl = dnpl
self.gnpl = gnpl
def discriminator(self, x, y, layer_shapes, is_training=True, reuse=False):
with tf.variable_scope(self.predicate.__name__ + "discriminator", reuse=reuse):
hidden_layer = []
x = concat(x, y)
for index, shape in enumerate(layer_shapes):
weight, bias = layer_initialization(
shape, scope="d_layer_" + str(index + 1))
if index == 0:
hidden_layer.append(
tf.nn.dropout(
tf.nn.relu(
tf.matmul(
x,
weight) +
bias),
self.dprob))
elif index != (len(layer_shapes) - 1):
hidden_layer.append(tf.nn.dropout(tf.nn.relu(tf.matmul(
hidden_layer[index - 1], weight) + bias), self.dprob))
else:
d_logit = tf.matmul(hidden_layer[index - 1], weight) + bias
d_prob = tf.nn.sigmoid(d_logit)
return d_prob, d_logit
def generator(self, z, y, layer_shapes, is_training=True, reuse=False):
with tf.variable_scope(self.predicate.__name__ + "generator", reuse=reuse):
hidden_layer = []
z = concat(z, y)
for index, shape in enumerate(layer_shapes):
weight, bias = layer_initialization(
shape, scope="g_layer_" + str(index + 1))
if index == 0:
hidden_layer.append(
tf.nn.dropout(
tf.nn.relu(
tf.matmul(
z,
weight) +
bias),
self.dprob))
elif index != (len(layer_shapes) - 1):
hidden_layer.append(tf.nn.dropout(tf.nn.relu(tf.matmul(
hidden_layer[index - 1], weight) + bias), self.dprob))
else:
g_prob = tf.matmul(hidden_layer[index - 1], weight) + bias
return g_prob
def construct_model(self):
# vectors
self.vectors = tf.placeholder(
tf.float32, [
self.batch_size, self.vector_dim], name="vectors")
# labels
self.labels = tf.placeholder(
tf.float32, [
self.batch_size, self.label_dim], name="labels")
# generate labels
self.generate_labels = tf.placeholder(
tf.float32, [
self.batch_size, self.label_dim], name="generate_labels")
# predicate_labels
self.predicate_labels = tf.placeholder(
tf.float32, [
self.batch_size, self.label_dim], name="predicate_labels")
# noises
self.noise = tf.placeholder(
tf.float32, [
self.batch_size, self.vector_dim], name="noise")
""" Loss functions """
# real vectors
d_real, d_real_logits = self.discriminator(
self.vectors, self.labels, self.dnpl, is_training=True, reuse=False)
# fake vectors
g_out = self.generator(
self.noise,
self.generate_labels,
self.gnpl,
is_training=True,
reuse=False)
d_fake, d_fake_logits = self.discriminator(
g_out, self.predicate_labels, self.dnpl, is_training=True, reuse=True)
# get loss for discriminator
d_loss_real = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(
logits=d_real_logits, labels=self.labels))
d_loss_fake = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(
logits=d_fake_logits, labels=self.predicate_labels))
self.d_loss = d_loss_real + d_loss_fake
# get loss for generator
self.g_loss = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(
logits=d_fake_logits, labels=self.generate_labels))
""" Training """
t_vars = tf.trainable_variables()
d_vars = [d for d in t_vars if d.name.startswith(self.predicate.__name__ + "discriminator")]
g_vars = [g for g in t_vars if g.name.startswith(self.predicate.__name__ + "generator")]
# Optimizer
with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):
self.d_optim = tf.train.AdamOptimizer(
self.learning_rate, beta1=self.beta1).minimize(
self.d_loss, var_list=d_vars)
self.g_optim = tf.train.AdamOptimizer(
self.learning_rate, beta1=self.beta1).minimize(
self.g_loss, var_list=g_vars)
""" Testing """
self.fake_vectors = self.generator(
self.noise,
self.generate_labels,
self.gnpl,
is_training=False,
reuse=True)
""" Summary """
d_loss_real_sum = tf.summary.scalar("d_loss_real", d_loss_real)
d_loss_fake_sum = tf.summary.scalar("d_loss_fake", d_loss_fake)
d_loss_sum = tf.summary.scalar("d_loss", self.d_loss)
g_loss_sum = tf.summary.scalar("g_loss", self.g_loss)
# final summary operations
self.d_sum = tf.summary.merge([d_loss_real_sum, d_loss_sum])
self.g_sum = tf.summary.merge([d_loss_fake_sum, g_loss_sum])
def train(self):
tf.global_variables_initializer().run()
# graph inputs for visualize training results
self.sample_z = np.random.uniform(-1, 1,
size=(self.batch_size, self.vector_dim))
# saver to save the model
self.saver = tf.train.Saver()
# summary writer
self.writer = tf.summary.FileWriter(
self.log_dir + "/" + self.model_name, self.sess.graph)
# restore check-point if it exists
could_load, checkpoint_counter = self.load(self.checkpoint_dir)
if could_load:
start_epoch = (int)(checkpoint_counter / self.num_batches)
start_batch_id = checkpoint_counter - start_epoch * self.num_batches
counter = checkpoint_counter
print("Restore checkpoint successfully")
else:
start_epoch = 0
start_batch_id = 0
counter = 1
print("Restore checkpoint unsuccessful")
percentage_corrects = []
percentage_corrects_0 = []
percentage_corrects_1 = []
# loop for epoch
start_time = time.time()
for epoch in range(start_epoch, self.epoch):
# get batch data
for idx in range(start_batch_id, self.num_batches):
batch_vectors = self.train_vectors[idx *
self.batch_size:(idx + 1) * self.batch_size]
batch_labels = self.train_labels[idx *
self.batch_size:(idx + 1) * self.batch_size]
batch_z = np.random.uniform(-1,
1,
[self.batch_size,
self.vector_dim]).astype(np.float32)
labels = np.random.randint(
2, size=(self.batch_size, self.label_dim))
samples = self.sess.run(
self.fake_vectors,
feed_dict={
self.generate_labels: labels,
self.noise: batch_z})
samples_predicate_labels = get_preidcate_labels(self.predicate, samples)
# update discriminator network
_, summary_str, d_loss = self.sess.run([self.d_optim, self.d_sum, self.d_loss],
feed_dict={self.vectors: batch_vectors,
self.labels: batch_labels,
self.generate_labels: labels,
self.predicate_labels: samples_predicate_labels,
self.noise: batch_z})
self.writer.add_summary(summary_str, counter)
# update generator network
_, summary_str, g_loss = self.sess.run ([self.g_optim, self.g_sum, self.g_loss],
feed_dict={self.generate_labels: labels,
self.predicate_labels: samples_predicate_labels,
self.noise: batch_z})
self.writer.add_summary(summary_str, counter)
# display training status
counter += 1
# print(
# "Epoch: [%2d] [%4d/%4d] time: %4.4f, d_loss: %.8f, g_loss: %.8f" %
# (epoch, idx, self.num_batches, time.time() - start_time, d_loss, g_loss))
# save training result for every 100 steps
if np.mod(counter, 100) == 0:
number = 0
samples_array =[]
labels_array = []
while number < 100:
sample_z = np.random.uniform(-1,
1,
size=(self.batch_size,
self.vector_dim))
sample_labels = np.random.randint(
2, size=(self.batch_size, self.label_dim))
samples = self.sess.run(
self.fake_vectors,
feed_dict={
self.generate_labels: sample_labels,
self.noise: sample_z})
for i in range(len(samples)):
if samples[i] not in self.train_vectors and number < 100:
number = number + 1
samples_array.append(samples[i])
labels_array.append(sample_labels[i])
correct, correct_0, correct_1 = evaluate_samples(
self.predicate, samples_array, labels_array)
percentage_corrects.append(correct)
percentage_corrects_0.append(correct_0)
percentage_corrects_1.append(correct_1)
# after an epoch, start_batch_id is set to zero
# non-zero value is only for the first epoch after loading
# pre-trained model
start_batch_id = 0
# save model
self.save(self.checkpoint_dir, counter)
# save model for final step
self.save(self.checkpoint_dir, counter)
print(self.predicate.__name__)
index = percentage_corrects.index(max(percentage_corrects))
print("Highest accuracy:", max(percentage_corrects), "(0:", percentage_corrects_0[index], " 1:",
percentage_corrects_1[index],") ", index)
print("Final accuracy:", percentage_corrects[-1], "(0:", percentage_corrects_0[-1], " 1:", percentage_corrects_1[-1],")")
print("time:", time.time() - start_time)
# visualize_results(percentage_corrects)
save_results(percentage_corrects, self.predicate.__name__)
@property
def model_dir(self):
return "datasetname{}_batchsize{}".format(
self.predicate.__name__, self.batch_size)
def save(self, checkpoint_dir, step):
checkpoint_dir = os.path.join(
checkpoint_dir, self.model_dir, self.model_name)
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
self.saver.save(
self.sess,
os.path.join(
checkpoint_dir,
self.model_name +
'.model'),
global_step=step)
def load(self, checkpoint_dir):
print("Reading checkpoints...")
checkpoint_dir = os.path.join(
checkpoint_dir, self.model_dir, self.model_name)
ckpt = tf.train.get_checkpoint_state(checkpoint_dir)
if ckpt and ckpt.model_checkpoint_path:
ckpt_name = os.path.basename(ckpt.model_checkpoint_path)
self.saver.restore(
self.sess, os.path.join(
checkpoint_dir, ckpt_name))
counter = int(
next(
re.finditer(
"(\d+)(?!.*\d)",
ckpt_name)).group(0))
print("Read {} successfully...".format(ckpt_name))
return True, counter
else:
print("Failed to find checkpoint...")
return False, 0
| |
'''
Created on Nov 7, 2011
@author: cryan
'''
import unittest
import numpy as np
from scipy.constants import pi
import matplotlib.pyplot as plt
from PySim.SystemParams import SystemParams
from PySim.PulseSequence import PulseSequence
from PySim.Simulation import simulate_sequence_stack, simulate_sequence
from PySim.QuantumSystems import SCQubit, Hamiltonian, Dissipator
class SingleQubit(unittest.TestCase):
def setUp(self):
#Setup the system
self.systemParams = SystemParams()
self.qubit = SCQubit(2,0e9, name='Q1', T1=1e-6)
self.systemParams.add_sub_system(self.qubit)
#self.systemParams.add_control_ham(inphase = Hamiltonian(0.5*(self.qubit.loweringOp + self.qubit.raisingOp)), quadrature = Hamiltonian(0.5*(-1j*self.qubit.loweringOp + 1j*self.qubit.raisingOp)))
self.systemParams.add_control_ham(inphase = Hamiltonian(0.5*self.qubit.pauliX), quadrature = Hamiltonian(0.5*self.qubit.pauliY))
self.systemParams.measurement = self.qubit.pauliZ
self.systemParams.create_full_Ham()
#Define Rabi frequency and pulse lengths
self.rabiFreq = 10e6
self.pulseLengths = np.linspace(0,100e-9,40)
#Define the initial state as the ground state
self.rhoIn = self.qubit.levelProjector(0)
def tearDown(self):
pass
def testRabiRotatingFrame(self):
'''
Test Rabi oscillations in the rotating frame, i.e. with zero drift Hamiltonian drive frequency of zero.
'''
#Setup the pulseSequences
pulseSeqs = []
for pulseLength in self.pulseLengths:
tmpPulseSeq = PulseSequence()
tmpPulseSeq.add_control_line(freq=0e9, phase=0)
tmpPulseSeq.controlAmps = self.rabiFreq*np.array([[1]], dtype=np.float64)
tmpPulseSeq.timeSteps = np.array([pulseLength])
tmpPulseSeq.maxTimeStep = pulseLength
tmpPulseSeq.H_int = None
pulseSeqs.append(tmpPulseSeq)
results = simulate_sequence_stack(pulseSeqs, self.systemParams, self.rhoIn, simType='unitary')[0]
expectedResults = np.cos(2*pi*self.rabiFreq*self.pulseLengths)
if plotResults:
plt.figure()
plt.plot(self.pulseLengths,results)
plt.plot(self.pulseLengths, expectedResults, color='r', linestyle='--', linewidth=2)
plt.title('10MHz Rabi Oscillations in Rotating Frame')
plt.xlabel('Pulse Length')
plt.ylabel(r'$\sigma_z$')
plt.legend(('Simulated Results', '10MHz Cosine'))
plt.show()
np.testing.assert_allclose(results, expectedResults , atol = 1e-4)
def testRabiInteractionFrame(self):
'''
Test Rabi oscillations after moving into an interaction frame that is different to the pulsing frame and with an irrational timestep for good measure.
'''
#Setup the system
self.systemParams.subSystems[0] = SCQubit(2,5e9, 'Q1')
self.systemParams.create_full_Ham()
#Setup the pulseSequences
pulseSeqs = []
for pulseLength in self.pulseLengths:
tmpPulseSeq = PulseSequence()
tmpPulseSeq.add_control_line(freq=-5.0e9, phase=0)
tmpPulseSeq.controlAmps = self.rabiFreq*np.array([[1]], dtype=np.float64)
tmpPulseSeq.timeSteps = np.array([pulseLength])
tmpPulseSeq.maxTimeStep = pi/2*1e-10
tmpPulseSeq.H_int = Hamiltonian(np.array([[0,0], [0, 5.005e9]], dtype = np.complex128))
pulseSeqs.append(tmpPulseSeq)
results = simulate_sequence_stack(pulseSeqs, self.systemParams, self.rhoIn, simType='unitary')[0]
expectedResults = np.cos(2*pi*self.rabiFreq*self.pulseLengths)
if plotResults:
plt.figure()
plt.plot(self.pulseLengths,results)
plt.plot(self.pulseLengths, expectedResults, color='r', linestyle='--', linewidth=2)
plt.title('10MHz Rabi Oscillations in Interaction Frame')
plt.xlabel('Pulse Length')
plt.ylabel(r'$\sigma_z$')
plt.legend(('Simulated Results', '10MHz Cosine'))
plt.show()
np.testing.assert_allclose(results, expectedResults , atol = 1e-4)
def testRamsey(self):
'''
Just look at Ramsey decay to make sure we get the off-resonance right.
'''
#Setup the system
self.systemParams.subSystems[0] = SCQubit(2,5e9, 'Q1')
self.systemParams.create_full_Ham()
self.systemParams.dissipators = [Dissipator(self.qubit.T1Dissipator)]
#Setup the pulseSequences
delays = np.linspace(0,8e-6,200)
t90 = 0.25*(1/self.rabiFreq)
offRes = 0.56789e6
pulseSeqs = []
for delay in delays:
tmpPulseSeq = PulseSequence()
#Shift the pulsing frequency down by offRes
tmpPulseSeq.add_control_line(freq=-(5.0e9-offRes), phase=0)
#Pulse sequence is X90, delay, X90
tmpPulseSeq.controlAmps = self.rabiFreq*np.array([[1, 0, 1]], dtype=np.float64)
tmpPulseSeq.timeSteps = np.array([t90, delay, t90])
#Interaction frame with some odd frequency
tmpPulseSeq.H_int = Hamiltonian(np.array([[0,0], [0, 5.00e9]], dtype = np.complex128))
pulseSeqs.append(tmpPulseSeq)
results = simulate_sequence_stack(pulseSeqs, self.systemParams, self.rhoIn, simType='lindblad')[0]
expectedResults = -np.cos(2*pi*offRes*(delays+t90))*np.exp(-delays/(2*self.qubit.T1))
if plotResults:
plt.figure()
plt.plot(1e6*delays,results)
plt.plot(1e6*delays, expectedResults, color='r', linestyle='--', linewidth=2)
plt.title('Ramsey Fringes 0.56789MHz Off-Resonance')
plt.xlabel('Pulse Spacing (us)')
plt.ylabel(r'$\sigma_z$')
plt.legend(('Simulated Results', '0.57MHz Cosine with T1 limited decay.'))
plt.show()
def testYPhase(self):
'''
Make sure the frame-handedness matches what we expect: i.e. if the qubit frequency is
greater than the driver frequency this corresponds to a positive rotation.
'''
#Setup the system
self.systemParams.subSystems[0] = SCQubit(2,5e9, 'Q1')
self.systemParams.create_full_Ham()
#Add a Y control Hamiltonian
self.systemParams.add_control_ham(inphase = Hamiltonian(0.5*self.qubit.pauliX), quadrature = Hamiltonian(0.5*self.qubit.pauliY))
#Setup the pulseSequences
delays = np.linspace(0,8e-6,200)
t90 = 0.25*(1/self.rabiFreq)
offRes = 1.2345e6
pulseSeqs = []
for delay in delays:
tmpPulseSeq = PulseSequence()
#Shift the pulsing frequency down by offRes
tmpPulseSeq.add_control_line(freq=-(5.0e9-offRes), phase=0)
tmpPulseSeq.add_control_line(freq=-(5.0e9-offRes), phase=-pi/2)
#Pulse sequence is X90, delay, Y90
tmpPulseSeq.controlAmps = self.rabiFreq*np.array([[1, 0, 0],[0,0,1]], dtype=np.float64)
tmpPulseSeq.timeSteps = np.array([t90, delay, t90])
#Interaction frame with some odd frequency
tmpPulseSeq.H_int = Hamiltonian(np.array([[0,0], [0, 5.00e9]], dtype = np.complex128))
pulseSeqs.append(tmpPulseSeq)
results = simulate_sequence_stack(pulseSeqs, self.systemParams, self.rhoIn, simType='lindblad')[0]
expectedResults = -np.sin(2*pi*offRes*(delays+t90))
if plotResults:
plt.figure()
plt.plot(1e6*delays,results)
plt.plot(1e6*delays, expectedResults, color='r', linestyle='--', linewidth=2)
plt.title('Ramsey Fringes {0:.2f} MHz Off-Resonance'.format(offRes/1e6))
plt.xlabel('Pulse Spacing (us)')
plt.ylabel(r'$\sigma_z$')
plt.legend(('Simulated Results', ' {0:.2f} MHz -Sin.'.format(offRes/1e6) ))
plt.show()
def testT1Recovery(self):
'''
Test a simple T1 recovery without any pulses. Start in the first excited state and watch recovery down to ground state.
'''
self.systemParams.dissipators = [Dissipator(self.qubit.T1Dissipator)]
#Just setup a series of delays
delays = np.linspace(0,5e-6,40)
pulseSeqs = []
for tmpDelay in delays:
tmpPulseSeq = PulseSequence()
tmpPulseSeq.add_control_line()
tmpPulseSeq.controlAmps = np.array([[0]])
tmpPulseSeq.timeSteps = np.array([tmpDelay])
tmpPulseSeq.maxTimeStep = tmpDelay
tmpPulseSeq.H_int = None
pulseSeqs.append(tmpPulseSeq)
results = simulate_sequence_stack(pulseSeqs, self.systemParams, np.array([[0,0],[0,1]], dtype=np.complex128), simType='lindblad')[0]
expectedResults = 1-2*np.exp(-delays/self.qubit.T1)
if plotResults:
plt.figure()
plt.plot(1e6*delays,results)
plt.plot(1e6*delays, expectedResults, color='r', linestyle='--', linewidth=2)
plt.xlabel(r'Recovery Time ($\mu$s)')
plt.ylabel(r'Expectation Value of $\sigma_z$')
plt.title(r'$T_1$ Recovery to the Ground State')
plt.legend(('Simulated Results', 'Exponential T1 Recovery'))
plt.show()
np.testing.assert_allclose(results, expectedResults, atol=1e-4)
class SingleQutrit(unittest.TestCase):
def setUp(self):
#Setup the system
self.systemParams = SystemParams()
self.qubit = SCQubit(3, 5e9, -100e6, name='Q1', T1=2e-6)
self.systemParams.add_sub_system(self.qubit)
self.systemParams.add_control_ham(inphase = Hamiltonian(0.5*(self.qubit.loweringOp + self.qubit.raisingOp)), quadrature = Hamiltonian(-0.5*(-1j*self.qubit.loweringOp + 1j*self.qubit.raisingOp)))
self.systemParams.measurement = self.qubit.pauliZ
self.systemParams.create_full_Ham()
#Add the 2us T1 dissipator
self.systemParams.dissipators = [Dissipator(self.qubit.T1Dissipator)]
#Define the initial state as the ground state
self.rhoIn = self.qubit.levelProjector(0)
def tearDown(self):
pass
def testTwoPhoton(self):
'''
Test spectroscopy and the two photon transition from the ground to the second excited state.
'''
freqSweep = 1e9*np.linspace(4.9, 5.1, 1000)
rabiFreq = 1e6
#Setup the pulseSequences as a series of 10us low-power pulses
pulseSeqs = []
for freq in freqSweep:
tmpPulseSeq = PulseSequence()
tmpPulseSeq.add_control_line(freq=freq, phase=0)
tmpPulseSeq.controlAmps = np.array([[rabiFreq]], dtype=np.float64)
tmpPulseSeq.timeSteps = np.array([10e-6])
tmpPulseSeq.maxTimeStep = np.Inf
tmpPulseSeq.H_int = Hamiltonian(np.diag(freq*np.arange(3, dtype=np.complex128)))
pulseSeqs.append(tmpPulseSeq)
results = simulate_sequence_stack(pulseSeqs, self.systemParams, self.rhoIn, simType='lindblad')[0]
if plotResults:
plt.figure()
plt.plot(freqSweep/1e9,results)
plt.xlabel('Frequency')
plt.ylabel(r'$\sigma_z$')
plt.title('Qutrit Spectroscopy')
plt.show()
class TwoQubit(unittest.TestCase):
def setUp(self):
#Setup a simple non-coupled two qubit system
self.systemParams = SystemParams()
self.Q1 = SCQubit(2, 5e9, name='Q1')
self.systemParams.add_sub_system(self.Q1)
self.Q2 = SCQubit(2, 6e9, name='Q2')
self.systemParams.add_sub_system(self.Q2)
X = 0.5*(self.Q1.loweringOp + self.Q1.raisingOp)
Y = 0.5*(-1j*self.Q1.loweringOp + 1j*self.Q2.raisingOp)
self.systemParams.add_control_ham(inphase = Hamiltonian(self.systemParams.expand_operator('Q1', X)), quadrature = Hamiltonian(self.systemParams.expand_operator('Q1', Y)))
self.systemParams.add_control_ham(inphase = Hamiltonian(self.systemParams.expand_operator('Q2', X)), quadrature = Hamiltonian(self.systemParams.expand_operator('Q2', Y)))
self.systemParams.measurement = self.systemParams.expand_operator('Q1', self.Q1.pauliZ) + self.systemParams.expand_operator('Q2', self.Q2.pauliZ)
self.systemParams.create_full_Ham()
#Define Rabi frequency and pulse lengths
self.rabiFreq = 10e6
#Define the initial state as the ground state
self.rhoIn = np.zeros((self.systemParams.dim, self.systemParams.dim))
self.rhoIn[0,0] = 1
def tearDown(self):
pass
def testZZGate(self):
'''Test whether the ZZ interaction performs as expected'''
#Take the bare Hamiltonian as the interaction Hamiltonian
H_int = Hamiltonian(self.systemParams.Hnat.matrix)
#First add a 2MHz ZZ interaction and add it to the system
self.systemParams.add_interaction('Q1', 'Q2', 'ZZ', 2e6)
self.systemParams.create_full_Ham()
#Setup the pulseSequences
delays = np.linspace(0,4e-6,100)
pulseSeqs = []
for delay in delays:
tmpPulseSeq = PulseSequence()
tmpPulseSeq.add_control_line(freq=-5.0e9, phase=0)
tmpPulseSeq.add_control_line(freq=-6.0e9, phase=0)
tmpPulseSeq.controlAmps = self.rabiFreq*np.array([[1, 0], [0,0]], dtype=np.float64)
tmpPulseSeq.timeSteps = np.array([25e-9, delay])
tmpPulseSeq.maxTimeStep = np.Inf
tmpPulseSeq.H_int = H_int
pulseSeqs.append(tmpPulseSeq)
self.systemParams.measurement = np.kron(self.Q1.pauliX, self.Q2.pauliZ)
resultsXZ = simulate_sequence_stack(pulseSeqs, self.systemParams, self.rhoIn, simType='unitary')[0]
self.systemParams.measurement = np.kron(self.Q1.pauliY, self.Q2.pauliZ)
resultsYZ = simulate_sequence_stack(pulseSeqs, self.systemParams, self.rhoIn, simType='unitary')[0]
if plotResults:
plt.figure()
plt.plot(delays*1e6, resultsXZ)
plt.plot(delays*1e6, resultsYZ, 'g')
plt.legend(('XZ','YZ'))
plt.xlabel('Coupling Time')
plt.ylabel('Operator Expectation Value')
plt.title('ZZ Coupling Evolution After a X90 on Q1')
plt.show()
if __name__ == "__main__":
plotResults = True
unittest.main()
# singleTest = unittest.TestSuite()
# singleTest.addTest(SingleQubit("testRabiRotatingFrame"))
# unittest.TextTestRunner(verbosity=2).run(singleTest)
| |
# Copyright 2018 PerfKitBenchmarker Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Module containing class for GCP's cloud redis instances.
Instances can be created and deleted.
"""
import json
import logging
import time
from absl import flags
from google.cloud import monitoring_v3
from google.cloud.monitoring_v3.types import TimeInterval
from perfkitbenchmarker import errors
from perfkitbenchmarker import managed_memory_store
from perfkitbenchmarker import providers
from perfkitbenchmarker import vm_util
from perfkitbenchmarker.providers.gcp import flags as gcp_flags
from perfkitbenchmarker.providers.gcp import util
FLAGS = flags.FLAGS
STANDARD_TIER = 'STANDARD'
BASIC_TIER = 'BASIC'
COMMAND_TIMEOUT = 600 # 10 minutes
# Default redis api endpoint
API_ENDPOINT = 'https://redis.googleapis.com/'
class CloudRedis(managed_memory_store.BaseManagedMemoryStore):
"""Object representing a GCP cloud redis instance."""
CLOUD = providers.GCP
MEMORY_STORE = managed_memory_store.REDIS
def __init__(self, spec):
super(CloudRedis, self).__init__(spec)
self.project = FLAGS.project
self.size = FLAGS.gcp_redis_gb
self.redis_region = FLAGS.cloud_redis_region
self.redis_version = spec.config.cloud_redis.redis_version
self.failover_style = FLAGS.redis_failover_style
if self.failover_style == managed_memory_store.Failover.FAILOVER_NONE:
self.tier = BASIC_TIER
elif self.failover_style == managed_memory_store.Failover.FAILOVER_SAME_REGION:
self.tier = STANDARD_TIER
cmd = util.GcloudCommand(self, 'config', 'set',
'api_endpoint_overrides/redis',
gcp_flags.API_OVERRIDE.value)
cmd.Issue()
@staticmethod
def CheckPrerequisites(benchmark_config):
if FLAGS.redis_failover_style == managed_memory_store.Failover.FAILOVER_SAME_ZONE:
raise errors.Config.InvalidValue(
'GCP cloud redis does not support same zone failover')
if (FLAGS.managed_memory_store_version and
FLAGS.managed_memory_store_version
not in managed_memory_store.REDIS_VERSIONS):
raise errors.Config.InvalidValue('Invalid Redis version.')
def GetResourceMetadata(self):
"""Returns a dict containing metadata about the instance.
Returns:
dict mapping string property key to value.
"""
result = {
'cloud_redis_failover_style': self.failover_style,
'cloud_redis_size': self.size,
'cloud_redis_tier': self.tier,
'cloud_redis_region': self.redis_region,
'cloud_redis_version': self.ParseReadableVersion(self.redis_version),
}
return result
@staticmethod
def ParseReadableVersion(version):
"""Parses Redis major and minor version number."""
if version.count('_') < 2:
logging.info(
'Could not parse version string correctly, '
'full Redis version returned: %s', version)
return version
return '.'.join(version.split('_')[1:])
def _Create(self):
"""Creates the instance."""
cmd = util.GcloudCommand(self, 'redis', 'instances', 'create', self.name)
cmd.flags['region'] = self.redis_region
cmd.flags['zone'] = FLAGS.zone[0]
cmd.flags['network'] = FLAGS.gce_network_name
cmd.flags['tier'] = self.tier
cmd.flags['size'] = self.size
cmd.flags['redis-version'] = self.redis_version
cmd.flags['labels'] = util.MakeFormattedDefaultTags()
cmd.Issue(timeout=COMMAND_TIMEOUT)
def _IsReady(self):
"""Returns whether cluster is ready."""
instance_details, _, _ = self.DescribeInstance()
return json.loads(instance_details).get('state') == 'READY'
def _Delete(self):
"""Deletes the instance."""
cmd = util.GcloudCommand(self, 'redis', 'instances', 'delete', self.name)
cmd.flags['region'] = self.redis_region
cmd.Issue(timeout=COMMAND_TIMEOUT, raise_on_failure=False)
reset_cmd = util.GcloudCommand(self, 'config', 'set',
'api_endpoint_overrides/redis',
'https://redis.googleapis.com/')
reset_cmd.Issue(timeout=COMMAND_TIMEOUT, raise_on_failure=False)
def _Exists(self):
"""Returns true if the instance exists."""
_, _, retcode = self.DescribeInstance()
return retcode == 0
def DescribeInstance(self):
"""Calls describe instance using the gcloud tool.
Returns:
stdout, stderr, and retcode.
"""
cmd = util.GcloudCommand(self, 'redis', 'instances', 'describe', self.name)
cmd.flags['region'] = self.redis_region
stdout, stderr, retcode = cmd.Issue(
suppress_warning=True, raise_on_failure=False)
if retcode != 0:
logging.info('Could not find redis instance %s', self.name)
return stdout, stderr, retcode
@vm_util.Retry(max_retries=5)
def _PopulateEndpoint(self):
"""Populates endpoint information about the instance.
Raises:
errors.Resource.RetryableGetError:
Failed to retrieve information on instance
"""
stdout, _, retcode = self.DescribeInstance()
if retcode != 0:
raise errors.Resource.RetryableGetError(
'Failed to retrieve information on {}'.format(self.name))
self._ip = json.loads(stdout)['host']
self._port = json.loads(stdout)['port']
def MeasureCpuUtilization(self, interval_length):
"""Measure the average CPU utilization on GCP instance in percentage."""
now = time.time()
seconds = int(now)
interval = TimeInterval()
interval.end_time.seconds = seconds
interval.start_time.seconds = seconds - interval_length
client = monitoring_v3.MetricServiceClient()
api_filter = (
'metric.type = "redis.googleapis.com/stats/cpu_utilization" '
'AND resource.labels.instance_id = "projects/'
) + self.project + '/locations/' + self.redis_region + '/instances/' + self.name + '"'
time_series = client.list_time_series(
name='projects/' + self.project,
filter_=api_filter,
interval=interval,
view=monitoring_v3.enums.ListTimeSeriesRequest.TimeSeriesView.FULL)
return self._ParseMonitoringTimeSeries(time_series)
def _ParseMonitoringTimeSeries(self, time_series):
"""Parses time series data and returns average CPU across intervals in %.
For example, an interval of 3 minutes would be represented as [x, y, z],
where x, y, and z are cpu seconds.
average CPU usage per minute in cpu seconds = (x + y + z) / 3
average cpu usage in percentage = [(x + y + z) / 3] / 60
Args:
time_series: time series of cpu seconds returned by monitoring.
Returns:
Percentage CPU use.
"""
intervals = []
# For each of the four types of load, sum the CPU across all intervals
for i, time_interval in enumerate(time_series):
for j, interval in enumerate(time_interval.points):
if i == 0:
intervals.append(interval.value.double_value)
else:
intervals[j] += interval.value.double_value
if intervals:
# Average over all minute intervals captured
averaged = sum(intervals) / len(intervals)
# averaged is in the unit of cpu seconds per minute.
# So divide by 60sec in 1 min to get a percentage usage over the minute.
return averaged / 60
return None
def GetInstanceSize(self):
"""Return the size of the GCP instance in gigabytes."""
return self.size
| |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 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.
import testtools
from tempest.api import compute
from tempest.api.compute import base
from tempest.common.utils.data_utils import rand_int_id
from tempest.common.utils.data_utils import rand_name
from tempest import exceptions
from tempest.test import attr
class FlavorsAdminTestJSON(base.BaseComputeAdminTest):
"""
Tests Flavors API Create and Delete that require admin privileges
"""
_interface = 'json'
@classmethod
def setUpClass(cls):
super(FlavorsAdminTestJSON, cls).setUpClass()
if not compute.FLAVOR_EXTRA_DATA_ENABLED:
msg = "FlavorExtraData extension not enabled."
raise cls.skipException(msg)
cls.client = cls.os_adm.flavors_client
cls.user_client = cls.os.flavors_client
cls.flavor_name_prefix = 'test_flavor_'
cls.ram = 512
cls.vcpus = 1
cls.disk = 10
cls.ephemeral = 10
cls.swap = 1024
cls.rxtx = 2
def flavor_clean_up(self, flavor_id):
resp, body = self.client.delete_flavor(flavor_id)
self.assertEqual(resp.status, 202)
self.client.wait_for_resource_deletion(flavor_id)
@attr(type='gate')
def test_create_flavor(self):
# Create a flavor and ensure it is listed
# This operation requires the user to have 'admin' role
flavor_name = rand_name(self.flavor_name_prefix)
new_flavor_id = rand_int_id(start=1000)
# Create the flavor
resp, flavor = self.client.create_flavor(flavor_name,
self.ram, self.vcpus,
self.disk,
new_flavor_id,
ephemeral=self.ephemeral,
swap=self.swap,
rxtx=self.rxtx)
self.addCleanup(self.flavor_clean_up, flavor['id'])
self.assertEqual(200, resp.status)
self.assertEqual(flavor['name'], flavor_name)
self.assertEqual(flavor['vcpus'], self.vcpus)
self.assertEqual(flavor['disk'], self.disk)
self.assertEqual(flavor['ram'], self.ram)
self.assertEqual(int(flavor['id']), new_flavor_id)
self.assertEqual(flavor['swap'], self.swap)
self.assertEqual(flavor['rxtx_factor'], self.rxtx)
self.assertEqual(flavor['OS-FLV-EXT-DATA:ephemeral'],
self.ephemeral)
if self._interface == "xml":
XMLNS_OS_FLV_ACCESS = "http://docs.openstack.org/compute/ext/"\
"flavor_access/api/v2"
key = "{" + XMLNS_OS_FLV_ACCESS + "}is_public"
self.assertEqual(flavor[key], "True")
if self._interface == "json":
self.assertEqual(flavor['os-flavor-access:is_public'], True)
# Verify flavor is retrieved
resp, flavor = self.client.get_flavor_details(new_flavor_id)
self.assertEqual(resp.status, 200)
self.assertEqual(flavor['name'], flavor_name)
@attr(type='gate')
def test_create_flavor_verify_entry_in_list_details(self):
# Create a flavor and ensure it's details are listed
# This operation requires the user to have 'admin' role
flavor_name = rand_name(self.flavor_name_prefix)
new_flavor_id = rand_int_id(start=1000)
# Create the flavor
resp, flavor = self.client.create_flavor(flavor_name,
self.ram, self.vcpus,
self.disk,
new_flavor_id,
ephemeral=self.ephemeral,
swap=self.swap,
rxtx=self.rxtx)
self.addCleanup(self.flavor_clean_up, flavor['id'])
flag = False
# Verify flavor is retrieved
resp, flavors = self.client.list_flavors_with_detail()
self.assertEqual(resp.status, 200)
for flavor in flavors:
if flavor['name'] == flavor_name:
flag = True
self.assertTrue(flag)
@attr(type=['negative', 'gate'])
def test_get_flavor_details_for_deleted_flavor(self):
# Delete a flavor and ensure it is not listed
# Create a test flavor
flavor_name = rand_name(self.flavor_name_prefix)
new_flavor_id = rand_int_id(start=1000)
resp, flavor = self.client.create_flavor(flavor_name,
self.ram,
self.vcpus, self.disk,
new_flavor_id,
ephemeral=self.ephemeral,
swap=self.swap,
rxtx=self.rxtx)
# Delete the flavor
new_flavor_id = flavor['id']
resp_delete, body = self.client.delete_flavor(new_flavor_id)
self.assertEqual(200, resp.status)
self.assertEqual(202, resp_delete.status)
# Deleted flavors can be seen via detailed GET
resp, flavor = self.client.get_flavor_details(new_flavor_id)
self.assertEqual(resp.status, 200)
self.assertEqual(flavor['name'], flavor_name)
# Deleted flavors should not show up in a list however
resp, flavors = self.client.list_flavors_with_detail()
self.assertEqual(resp.status, 200)
flag = True
for flavor in flavors:
if flavor['name'] == flavor_name:
flag = False
self.assertTrue(flag)
@attr(type='gate')
def test_create_list_flavor_without_extra_data(self):
# Create a flavor and ensure it is listed
# This operation requires the user to have 'admin' role
flavor_name = rand_name(self.flavor_name_prefix)
new_flavor_id = rand_int_id(start=1000)
# Create the flavor
resp, flavor = self.client.create_flavor(flavor_name,
self.ram, self.vcpus,
self.disk,
new_flavor_id)
self.addCleanup(self.flavor_clean_up, flavor['id'])
self.assertEqual(200, resp.status)
self.assertEqual(flavor['name'], flavor_name)
self.assertEqual(flavor['ram'], self.ram)
self.assertEqual(flavor['vcpus'], self.vcpus)
self.assertEqual(flavor['disk'], self.disk)
self.assertEqual(int(flavor['id']), new_flavor_id)
self.assertEqual(flavor['swap'], '')
self.assertEqual(int(flavor['rxtx_factor']), 1)
self.assertEqual(int(flavor['OS-FLV-EXT-DATA:ephemeral']), 0)
if self._interface == "xml":
XMLNS_OS_FLV_ACCESS = "http://docs.openstack.org/compute/ext/"\
"flavor_access/api/v2"
key = "{" + XMLNS_OS_FLV_ACCESS + "}is_public"
self.assertEqual(flavor[key], "True")
if self._interface == "json":
self.assertEqual(flavor['os-flavor-access:is_public'], True)
# Verify flavor is retrieved
resp, flavor = self.client.get_flavor_details(new_flavor_id)
self.assertEqual(resp.status, 200)
self.assertEqual(flavor['name'], flavor_name)
# Check if flavor is present in list
resp, flavors = self.client.list_flavors_with_detail()
self.assertEqual(resp.status, 200)
for flavor in flavors:
if flavor['name'] == flavor_name:
flag = True
self.assertTrue(flag)
@testtools.skip("Skipped until the Bug #1209101 is resolved")
@attr(type='gate')
def test_list_non_public_flavor(self):
# Create a flavor with os-flavor-access:is_public false should
# be present in list_details.
# This operation requires the user to have 'admin' role
flavor_name = rand_name(self.flavor_name_prefix)
new_flavor_id = rand_int_id(start=1000)
# Create the flavor
resp, flavor = self.client.create_flavor(flavor_name,
self.ram, self.vcpus,
self.disk,
new_flavor_id,
is_public="False")
self.addCleanup(self.flavor_clean_up, flavor['id'])
# Verify flavor is retrieved
flag = False
resp, flavors = self.client.list_flavors_with_detail()
self.assertEqual(resp.status, 200)
for flavor in flavors:
if flavor['name'] == flavor_name:
flag = True
self.assertTrue(flag)
# Verify flavor is not retrieved with other user
flag = False
resp, flavors = self.user_client.list_flavors_with_detail()
self.assertEqual(resp.status, 200)
for flavor in flavors:
if flavor['name'] == flavor_name:
flag = True
self.assertFalse(flag)
@attr(type='gate')
def test_create_server_with_non_public_flavor(self):
# Create a flavor with os-flavor-access:is_public false
flavor_name = rand_name(self.flavor_name_prefix)
new_flavor_id = rand_int_id(start=1000)
# Create the flavor
resp, flavor = self.client.create_flavor(flavor_name,
self.ram, self.vcpus,
self.disk,
new_flavor_id,
is_public="False")
self.addCleanup(self.flavor_clean_up, flavor['id'])
self.assertEqual(200, resp.status)
# Verify flavor is not used by other user
self.assertRaises(exceptions.BadRequest,
self.os.servers_client.create_server,
'test', self.image_ref, flavor['id'])
@attr(type='gate')
def test_list_public_flavor_with_other_user(self):
# Create a Flavor with public access.
# Try to List/Get flavor with another user
flavor_name = rand_name(self.flavor_name_prefix)
new_flavor_id = rand_int_id(start=1000)
# Create the flavor
resp, flavor = self.client.create_flavor(flavor_name,
self.ram, self.vcpus,
self.disk,
new_flavor_id,
is_public="True")
self.addCleanup(self.flavor_clean_up, flavor['id'])
flag = False
self.new_client = self.flavors_client
# Verify flavor is retrieved with new user
resp, flavors = self.new_client.list_flavors_with_detail()
self.assertEqual(resp.status, 200)
for flavor in flavors:
if flavor['name'] == flavor_name:
flag = True
self.assertTrue(flag)
@attr(type='gate')
def test_is_public_string_variations(self):
flavor_id_not_public = rand_int_id(start=1000)
flavor_name_not_public = rand_name(self.flavor_name_prefix)
flavor_id_public = rand_int_id(start=1000)
flavor_name_public = rand_name(self.flavor_name_prefix)
# Create a non public flavor
resp, flavor = self.client.create_flavor(flavor_name_not_public,
self.ram, self.vcpus,
self.disk,
flavor_id_not_public,
is_public="False")
self.addCleanup(self.flavor_clean_up, flavor['id'])
# Create a public flavor
resp, flavor = self.client.create_flavor(flavor_name_public,
self.ram, self.vcpus,
self.disk,
flavor_id_public,
is_public="True")
self.addCleanup(self.flavor_clean_up, flavor['id'])
def _flavor_lookup(flavors, flavor_name):
for flavor in flavors:
if flavor['name'] == flavor_name:
return flavor
return None
def _test_string_variations(variations, flavor_name):
for string in variations:
params = {'is_public': string}
r, flavors = self.client.list_flavors_with_detail(params)
self.assertEqual(r.status, 200)
flavor = _flavor_lookup(flavors, flavor_name)
self.assertIsNotNone(flavor)
_test_string_variations(['f', 'false', 'no', '0'],
flavor_name_not_public)
_test_string_variations(['t', 'true', 'yes', '1'],
flavor_name_public)
@attr(type='gate')
def test_create_flavor_using_string_ram(self):
flavor_name = rand_name(self.flavor_name_prefix)
new_flavor_id = rand_int_id(start=1000)
ram = " 1024 "
resp, flavor = self.client.create_flavor(flavor_name,
ram, self.vcpus,
self.disk,
new_flavor_id)
self.addCleanup(self.flavor_clean_up, flavor['id'])
self.assertEqual(200, resp.status)
self.assertEqual(flavor['name'], flavor_name)
self.assertEqual(flavor['vcpus'], self.vcpus)
self.assertEqual(flavor['disk'], self.disk)
self.assertEqual(flavor['ram'], int(ram))
self.assertEqual(int(flavor['id']), new_flavor_id)
@attr(type=['negative', 'gate'])
def test_invalid_is_public_string(self):
self.assertRaises(exceptions.BadRequest,
self.client.list_flavors_with_detail,
{'is_public': 'invalid'})
@attr(type=['negative', 'gate'])
def test_create_flavor_as_user(self):
flavor_name = rand_name(self.flavor_name_prefix)
new_flavor_id = rand_int_id(start=1000)
self.assertRaises(exceptions.Unauthorized,
self.user_client.create_flavor,
flavor_name, self.ram, self.vcpus, self.disk,
new_flavor_id, ephemeral=self.ephemeral,
swap=self.swap, rxtx=self.rxtx)
@attr(type=['negative', 'gate'])
def test_delete_flavor_as_user(self):
self.assertRaises(exceptions.Unauthorized,
self.user_client.delete_flavor,
self.flavor_ref_alt)
@attr(type=['negative', 'gate'])
def test_create_flavor_using_invalid_ram(self):
flavor_name = rand_name(self.flavor_name_prefix)
new_flavor_id = rand_int_id(start=1000)
self.assertRaises(exceptions.BadRequest,
self.client.create_flavor,
flavor_name, -1, self.vcpus,
self.disk, new_flavor_id)
@attr(type=['negative', 'gate'])
def test_create_flavor_using_invalid_vcpus(self):
flavor_name = rand_name(self.flavor_name_prefix)
new_flavor_id = rand_int_id(start=1000)
self.assertRaises(exceptions.BadRequest,
self.client.create_flavor,
flavor_name, self.ram, 0,
self.disk, new_flavor_id)
class FlavorsAdminTestXML(FlavorsAdminTestJSON):
_interface = 'xml'
| |
import warnings
import pytest
import pandas as pd
from pandas import MultiIndex
import pandas.util.testing as tm
def test_dtype_str(indices):
with tm.assert_produces_warning(FutureWarning):
dtype = indices.dtype_str
assert isinstance(dtype, str)
assert dtype == str(indices.dtype)
def test_format(idx):
idx.format()
idx[:0].format()
def test_format_integer_names():
index = MultiIndex(
levels=[[0, 1], [0, 1]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]], names=[0, 1]
)
index.format(names=True)
def test_format_sparse_config(idx):
warn_filters = warnings.filters
warnings.filterwarnings("ignore", category=FutureWarning, module=".*format")
# GH1538
pd.set_option("display.multi_sparse", False)
result = idx.format()
assert result[1] == "foo two"
tm.reset_display_options()
warnings.filters = warn_filters
def test_format_sparse_display():
index = MultiIndex(
levels=[[0, 1], [0, 1], [0, 1], [0]],
codes=[
[0, 0, 0, 1, 1, 1],
[0, 0, 1, 0, 0, 1],
[0, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0],
],
)
result = index.format()
assert result[3] == "1 0 0 0"
def test_repr_with_unicode_data():
with pd.option_context("display.encoding", "UTF-8"):
d = {"a": ["\u05d0", 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}
index = pd.DataFrame(d).set_index(["a", "b"]).index
assert "\\" not in repr(index) # we don't want unicode-escaped
def test_repr_roundtrip_raises():
mi = MultiIndex.from_product([list("ab"), range(3)], names=["first", "second"])
with pytest.raises(TypeError):
eval(repr(mi))
def test_unicode_string_with_unicode():
d = {"a": ["\u05d0", 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}
idx = pd.DataFrame(d).set_index(["a", "b"]).index
str(idx)
def test_repr_max_seq_item_setting(idx):
# GH10182
idx = idx.repeat(50)
with pd.option_context("display.max_seq_items", None):
repr(idx)
assert "..." not in str(idx)
class TestRepr:
def test_repr(self, idx):
result = idx[:1].__repr__()
expected = """\
MultiIndex([('foo', 'one')],
names=['first', 'second'])"""
assert result == expected
result = idx.__repr__()
expected = """\
MultiIndex([('foo', 'one'),
('foo', 'two'),
('bar', 'one'),
('baz', 'two'),
('qux', 'one'),
('qux', 'two')],
names=['first', 'second'])"""
assert result == expected
with pd.option_context("display.max_seq_items", 5):
result = idx.__repr__()
expected = """\
MultiIndex([('foo', 'one'),
('foo', 'two'),
...
('qux', 'one'),
('qux', 'two')],
names=['first', 'second'], length=6)"""
assert result == expected
def test_rjust(self, narrow_multi_index):
mi = narrow_multi_index
result = mi[:1].__repr__()
expected = """\
MultiIndex([('a', 9, '2000-01-01 00:00:00')],
names=['a', 'b', 'dti'])"""
assert result == expected
result = mi[::500].__repr__()
expected = """\
MultiIndex([( 'a', 9, '2000-01-01 00:00:00'),
( 'a', 9, '2000-01-01 00:08:20'),
('abc', 10, '2000-01-01 00:16:40'),
('abc', 10, '2000-01-01 00:25:00')],
names=['a', 'b', 'dti'])"""
assert result == expected
result = mi.__repr__()
expected = """\
MultiIndex([( 'a', 9, '2000-01-01 00:00:00'),
( 'a', 9, '2000-01-01 00:00:01'),
( 'a', 9, '2000-01-01 00:00:02'),
( 'a', 9, '2000-01-01 00:00:03'),
( 'a', 9, '2000-01-01 00:00:04'),
( 'a', 9, '2000-01-01 00:00:05'),
( 'a', 9, '2000-01-01 00:00:06'),
( 'a', 9, '2000-01-01 00:00:07'),
( 'a', 9, '2000-01-01 00:00:08'),
( 'a', 9, '2000-01-01 00:00:09'),
...
('abc', 10, '2000-01-01 00:33:10'),
('abc', 10, '2000-01-01 00:33:11'),
('abc', 10, '2000-01-01 00:33:12'),
('abc', 10, '2000-01-01 00:33:13'),
('abc', 10, '2000-01-01 00:33:14'),
('abc', 10, '2000-01-01 00:33:15'),
('abc', 10, '2000-01-01 00:33:16'),
('abc', 10, '2000-01-01 00:33:17'),
('abc', 10, '2000-01-01 00:33:18'),
('abc', 10, '2000-01-01 00:33:19')],
names=['a', 'b', 'dti'], length=2000)"""
assert result == expected
def test_tuple_width(self, wide_multi_index):
mi = wide_multi_index
result = mi[:1].__repr__()
expected = """MultiIndex([('a', 9, '2000-01-01 00:00:00', '2000-01-01 00:00:00', ...)],
names=['a', 'b', 'dti_1', 'dti_2', 'dti_3'])"""
assert result == expected
result = mi[:10].__repr__()
expected = """\
MultiIndex([('a', 9, '2000-01-01 00:00:00', '2000-01-01 00:00:00', ...),
('a', 9, '2000-01-01 00:00:01', '2000-01-01 00:00:01', ...),
('a', 9, '2000-01-01 00:00:02', '2000-01-01 00:00:02', ...),
('a', 9, '2000-01-01 00:00:03', '2000-01-01 00:00:03', ...),
('a', 9, '2000-01-01 00:00:04', '2000-01-01 00:00:04', ...),
('a', 9, '2000-01-01 00:00:05', '2000-01-01 00:00:05', ...),
('a', 9, '2000-01-01 00:00:06', '2000-01-01 00:00:06', ...),
('a', 9, '2000-01-01 00:00:07', '2000-01-01 00:00:07', ...),
('a', 9, '2000-01-01 00:00:08', '2000-01-01 00:00:08', ...),
('a', 9, '2000-01-01 00:00:09', '2000-01-01 00:00:09', ...)],
names=['a', 'b', 'dti_1', 'dti_2', 'dti_3'])"""
assert result == expected
result = mi.__repr__()
expected = """\
MultiIndex([( 'a', 9, '2000-01-01 00:00:00', '2000-01-01 00:00:00', ...),
( 'a', 9, '2000-01-01 00:00:01', '2000-01-01 00:00:01', ...),
( 'a', 9, '2000-01-01 00:00:02', '2000-01-01 00:00:02', ...),
( 'a', 9, '2000-01-01 00:00:03', '2000-01-01 00:00:03', ...),
( 'a', 9, '2000-01-01 00:00:04', '2000-01-01 00:00:04', ...),
( 'a', 9, '2000-01-01 00:00:05', '2000-01-01 00:00:05', ...),
( 'a', 9, '2000-01-01 00:00:06', '2000-01-01 00:00:06', ...),
( 'a', 9, '2000-01-01 00:00:07', '2000-01-01 00:00:07', ...),
( 'a', 9, '2000-01-01 00:00:08', '2000-01-01 00:00:08', ...),
( 'a', 9, '2000-01-01 00:00:09', '2000-01-01 00:00:09', ...),
...
('abc', 10, '2000-01-01 00:33:10', '2000-01-01 00:33:10', ...),
('abc', 10, '2000-01-01 00:33:11', '2000-01-01 00:33:11', ...),
('abc', 10, '2000-01-01 00:33:12', '2000-01-01 00:33:12', ...),
('abc', 10, '2000-01-01 00:33:13', '2000-01-01 00:33:13', ...),
('abc', 10, '2000-01-01 00:33:14', '2000-01-01 00:33:14', ...),
('abc', 10, '2000-01-01 00:33:15', '2000-01-01 00:33:15', ...),
('abc', 10, '2000-01-01 00:33:16', '2000-01-01 00:33:16', ...),
('abc', 10, '2000-01-01 00:33:17', '2000-01-01 00:33:17', ...),
('abc', 10, '2000-01-01 00:33:18', '2000-01-01 00:33:18', ...),
('abc', 10, '2000-01-01 00:33:19', '2000-01-01 00:33:19', ...)],
names=['a', 'b', 'dti_1', 'dti_2', 'dti_3'], length=2000)""" # noqa
assert result == expected
| |
from sympy.core import Basic, S, sympify, Expr, Rational, Symbol
from sympy.core import Add, Mul
from sympy.core.cache import cacheit
from sympy.core.compatibility import cmp_to_key
class Order(Expr):
""" Represents the limiting behavior of some function
The order of a function characterizes the function based on the limiting
behavior of the function as it goes to some limit. Only taking the limit
point to be 0 is currently supported. This is expressed in big O notation
[1]_.
The formal definition for the order of a function `g(x)` about a point `a`
is such that `g(x) = O(f(x))` as `x \\rightarrow a` if and only if for any
`\delta > 0` there exists a `M > 0` such that `|g(x)| \leq M|f(x)|` for
`|x-a| < \delta`. This is equivalent to `\lim_{x \\rightarrow a}
|g(x)/f(x)| < \infty`.
Let's illustrate it on the following example by taking the expansion of
`\sin(x)` about 0:
.. math ::
\sin(x) = x - x^3/3! + O(x^5)
where in this case `O(x^5) = x^5/5! - x^7/7! + \cdots`. By the definition
of `O`, for any `\delta > 0` there is an `M` such that:
.. math ::
|x^5/5! - x^7/7! + ....| <= M|x^5| \\text{ for } |x| < \delta
or by the alternate definition:
.. math ::
\lim_{x \\rightarrow 0} | (x^5/5! - x^7/7! + ....) / x^5| < \infty
which surely is true, because
.. math ::
\lim_{x \\rightarrow 0} | (x^5/5! - x^7/7! + ....) / x^5| = 1/5!
As it is usually used, the order of a function can be intuitively thought
of representing all terms of powers greater than the one specified. For
example, `O(x^3)` corresponds to any terms proportional to `x^3,
x^4,\ldots` and any higher power. For a polynomial, this leaves terms
proportional to `x^2`, `x` and constants.
Examples
========
>>> from sympy import O
>>> from sympy.abc import x
>>> O(x)
O(x)
>>> O(x)*x
O(x**2)
>>> O(x)-O(x)
O(x)
References
==========
.. [1] `Big O notation <http://en.wikipedia.org/wiki/Big_O_notation>`_
Notes
=====
In ``O(f(x), x)`` the expression ``f(x)`` is assumed to have a leading
term. ``O(f(x), x)`` is automatically transformed to
``O(f(x).as_leading_term(x),x)``.
``O(expr*f(x), x)`` is ``O(f(x), x)``
``O(expr, x)`` is ``O(1)``
``O(0, x)`` is 0.
Multivariate O is also supported:
``O(f(x, y), x, y)`` is transformed to
``O(f(x, y).as_leading_term(x,y).as_leading_term(y), x, y)``
In the multivariate case, it is assumed the limits w.r.t. the various
symbols commute.
If no symbols are passed then all symbols in the expression are used:
"""
is_Order = True
__slots__ = []
@cacheit
def __new__(cls, expr, *symbols, **assumptions):
expr = sympify(expr).expand()
if expr is S.NaN:
return S.NaN
if symbols:
symbols = map(sympify, symbols)
if not all(isinstance(s, Symbol) for s in symbols):
raise NotImplementedError('Order at points other than 0 not supported.')
else:
symbols = list(expr.free_symbols)
if expr.is_Order:
new_symbols = list(expr.variables)
for s in symbols:
if s not in new_symbols:
new_symbols.append(s)
if len(new_symbols) == len(expr.variables):
return expr
symbols = new_symbols
elif symbols:
if expr.is_Add:
lst = expr.extract_leading_order(*symbols)
expr = Add(*[f.expr for (e,f) in lst])
elif expr:
if len(symbols) > 1:
# TODO
# We cannot use compute_leading_term because that only
# works in one symbol.
expr = expr.as_leading_term(*symbols)
else:
expr = expr.compute_leading_term(symbols[0])
terms = expr.as_coeff_mul(*symbols)[1]
s = set(symbols)
expr = Mul(*[t for t in terms if s & t.free_symbols])
if expr is S.Zero:
return expr
elif not expr.has(*symbols):
expr = S.One
# create Order instance:
symbols.sort(key=cmp_to_key(Basic.compare))
obj = Expr.__new__(cls, expr, *symbols, **assumptions)
return obj
def _hashable_content(self):
return self.args
def oseries(self, order):
return self
def _eval_nseries(self, x, n, logx):
return self
@property
def expr(self):
return self._args[0]
@property
def variables(self):
return self._args[1:]
@property
def free_symbols(self):
return self.expr.free_symbols
def _eval_power(b, e):
if e.is_Number:
return Order(b.expr ** e, *b.variables)
return
def as_expr_variables(self, order_symbols):
if order_symbols is None:
order_symbols = self.variables
else:
for s in self.variables:
if s not in order_symbols:
order_symbols = order_symbols + (s,)
return self.expr, order_symbols
def removeO(self):
return S.Zero
def getO(self):
return self
@cacheit
def contains(self, expr):
"""
Return True if expr belongs to Order(self.expr, \*self.variables).
Return False if self belongs to expr.
Return None if the inclusion relation cannot be determined
(e.g. when self and expr have different symbols).
"""
# NOTE: when multiplying out series a lot of queries like
# O(...).contains(a*x**b) with many a and few b are made.
# Separating out the independent part allows for better caching.
c, m = expr.as_coeff_mul(*self.variables)
if m != ():
return self._contains(Mul(*m))
else:
# Mul(*m) == 1, and O(1) treatment is somewhat peculiar ...
# some day this else should not be necessary
return self._contains(expr)
@cacheit
def _contains(self, expr):
from sympy import powsimp, limit
if expr is S.Zero:
return True
if expr is S.NaN:
return False
if expr.is_Order:
if self.variables and expr.variables:
common_symbols = tuple([s for s in self.variables if s in expr.variables])
elif self.variables:
common_symbols = self.variables
else:
common_symbols = expr.variables
if not common_symbols:
if not (self.variables or expr.variables): # O(1),O(1)
return True
return None
r = None
for s in common_symbols:
l = limit(powsimp(self.expr/expr.expr, deep=True,\
combine='exp'), s, 0) != 0
if r is None:
r = l
else:
if r != l:
return
return r
obj = Order(expr, *self.variables)
return self.contains(obj)
def _eval_subs(self, old, new):
if old.is_Symbol and old in self.variables:
i = list(self.variables).index(old)
if isinstance(new, Symbol):
return Order(self.expr._subs(old, new), *(self.variables[:i]+(new,)+self.variables[i+1:]))
return Order(self.expr._subs(old, new), *(self.variables[:i]+self.variables[i+1:]))
return Order(self.expr._subs(old, new), *self.variables)
def _eval_derivative(self, x):
return self.func(self.expr.diff(x), *self.variables) or self
def _sage_(self):
#XXX: SAGE doesn't have Order yet. Let's return 0 instead.
return Rational(0)._sage_()
O = Order
| |
#!/usr/bin/env python
import os
import sys
lib_path = os.path.realpath(os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', 'lib'))
if lib_path not in sys.path:
sys.path[0:0] = [lib_path]
import utils
import os
import argparse
import processors
import tokenizers
import analyzers
import clusterers
import collections
import numpy as np
from sklearn.feature_extraction import DictVectorizer
from sklearn import svm, preprocessing, cross_validation
from sklearn.metrics import precision_recall_curve, auc, classification_report, precision_recall_fscore_support
import random
def main(args):
extractor = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'label.py')
path = utils.get_data_path(args.site[0])
urls = utils.load_urls(path)
# load each JSON file from chaos.
# Read each block of that file.
# [P2] Sort the blocks by their size.
# Also load the gold-text of that file.
# If matching between gold-text and that element text is
# above a certain threshold, label that block as 1.
# [P2] remove the matching part from gold-text.
# Rewrite the blocks to another json file.
# extract data from each url
# load data
pages = []
domains = collections.defaultdict(lambda: 0)
for id, url in enumerate(urls):
if not url.strip():
continue
host = url.split('/', 3)[2]
#if domains[host] > 2:
# continue
domains[host] += 1
print host
page = utils.load_data(path, id)
processor = processors.Processor([page], tokenizer=tokenizers.GenericTokenizer, analyzer=analyzers.LongestAnalyzer)
features = processor.extract()
clusterer = clusterers.DBSCAN()
labels = clusterer.cluster(features).labels_
clusters = collections.defaultdict(list)
for text, label in zip(processor.texts, labels):
clusters[int(label)].append(text)
gold_text = utils.load_gold_text(path, id)
gold_text = processor.tokenizer.tokenize(gold_text)
max_score = 0
best_label = None
for label, texts in clusters.iteritems():
tokens = ''
for text in texts:
tokens += text['tokens']
score = processor.analyzer.get_similarity(tokens, gold_text)
if score > max_score:
max_score = score
best_label = label
for text in clusters[best_label]:
text['label'] = 1
page_texts = []
for label, texts in clusters.iteritems():
page_texts += texts
random.shuffle(page_texts)
pages.append(page_texts)
#random.shuffle(pages)
continuous_features = []
discrete_features = []
labels = []
for page in pages:
for text in page:
text_length = len(text['tokens'])
area = text['bound']['height'] * text['bound']['width']
text_density = float(text_length) / float(area)
# continuous_feature
continuous_feature = [] #text_length, text_density]
continuous_features.append(continuous_feature)
# discrete features
discrete_feature = dict()
discrete_feature = dict(text['computed'].items())
discrete_feature['path'] = ' > '.join(text['path'])
"""
discrete_feature['selector'] = ' > '.join([
'%s%s%s' % (
selector['name'],
'#' + selector['id'] if selector['id'] else '',
'.' + '.'.join(selector['classes']) if selector['classes'] else '',
)
for selector in text['selector']
])
"""
discrete_feature['class'] = ' > '.join([
'%s%s' % (
selector['name'],
'.' + '.'.join(selector['classes']) if selector['classes'] else '',
)
for selector in text['selector']
])
"""
discrete_feature['id'] = ' > '.join([
'%s%s' % (
selector['name'],
'#' + selector['id'] if selector['id'] else '',
)
for selector in text['selector']
])
"""
discrete_features.append(discrete_feature)
# label
labels.append(text['label'])
vectorizer = DictVectorizer()
discrete_features = vectorizer.fit_transform(discrete_features).toarray()
continuous_features = np.array(continuous_features)
labels = np.array(labels).astype(np.float32)
# scale features
features = preprocessing.scale(features)
features = np.hstack([continuous_features, discrete_features]).astype(np.float32)
print features.shape
precisions = []
recalls = []
f1scores = []
supports = []
rs = cross_validation.KFold(len(labels), n_folds=4, shuffle=False, random_state=0)
for train_index, test_index in rs:
print 'training size = %d, testing size = %d' % (len(train_index), len(test_index))
clf = svm.SVC(verbose=False, kernel='linear', probability=False, random_state=0, cache_size=2000, class_weight='auto')
clf.fit(features[train_index], labels[train_index])
print clf.n_support_
"""
negatives = []
for i in clf.support_[:clf.n_support_[0]]:
negatives.append(all_texts[i])
positives = []
for i in clf.support_[clf.n_support_[0]:]:
positives.append(all_texts[i])
stats(negatives, positives)
"""
print "training:"
predicted = clf.predict(features[train_index])
print classification_report(labels[train_index], predicted)
print "testing:"
predicted = clf.predict(features[test_index])
print classification_report(labels[test_index], predicted)
precision, recall, f1score, support = precision_recall_fscore_support(labels[test_index], predicted)
precisions.append(precision)
recalls.append(recall)
f1scores.append(f1score)
supports.append(support)
precisions = np.mean(np.array(precisions), axis=0)
recalls = np.mean(np.array(recalls), axis=0)
f1scores = np.mean(np.array(f1scores), axis=0)
supports = np.mean(np.array(supports), axis=0)
for label in range(2):
print '%f\t%f\t%f\t%f' % (precisions[label], recalls[label], f1scores[label], supports[label])
return
def stats(negatives, positives):
negative_features = set()
positives_features = set()
negative_counts = collections.defaultdict(lambda: 0)
positives_counts = collections.defaultdict(lambda: 0)
for text in negatives:
negative_features |= set(text['computed'].items())
for text in positives:
positives_features |= set(text['computed'].items())
common = negative_features & positives_features
for text in negatives:
for key, value in text['computed'].iteritems():
if (key, value) not in common:
negative_counts[(key, value)] += 1
for text in positives:
for key, value in text['computed'].iteritems():
if (key, value) not in common:
positives_counts[(key, value)] += 1
print 'negatives: '
print list(reversed(sorted(filter(lambda x: x[1] > 1, negative_counts.items()), key=lambda pair: pair[1])))[:10]
print 'positives: '
print list(reversed(sorted(filter(lambda x: x[1] > 1, positives_counts.items()), key=lambda pair: pair[1])))[:10]
def parse_args():
"""
Parse command line arguments
"""
parser = argparse.ArgumentParser(description='Extract site pages.')
parser.add_argument('site', metavar='site', type=str, nargs=1, help='site id, for example: theverge, npr, nytimes')
return parser.parse_args()
if __name__ == '__main__':
main(parse_args())
| |
from typing import Dict, Optional, TYPE_CHECKING
from ray.rllib.env import BaseEnv
from ray.rllib.policy import Policy
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.evaluation import MultiAgentEpisode
from ray.rllib.utils.annotations import PublicAPI
from ray.rllib.utils.deprecation import deprecation_warning
from ray.rllib.utils.typing import AgentID, PolicyID
from ray.util.debug import log_once
if TYPE_CHECKING:
from ray.rllib.evaluation import RolloutWorker
@PublicAPI
class DefaultCallbacks:
"""Abstract base class for RLlib callbacks (similar to Keras callbacks).
These callbacks can be used for custom metrics and custom postprocessing.
By default, all of these callbacks are no-ops. To configure custom training
callbacks, subclass DefaultCallbacks and then set
{"callbacks": YourCallbacksClass} in the trainer config.
"""
def __init__(self, legacy_callbacks_dict: Dict[str, callable] = None):
if legacy_callbacks_dict:
deprecation_warning(
"callbacks dict interface",
"a class extending rllib.agents.callbacks.DefaultCallbacks")
self.legacy_callbacks = legacy_callbacks_dict or {}
def on_episode_start(self,
*,
worker: "RolloutWorker",
base_env: BaseEnv,
policies: Dict[PolicyID, Policy],
episode: MultiAgentEpisode,
env_index: Optional[int] = None,
**kwargs) -> None:
"""Callback run on the rollout worker before each episode starts.
Args:
worker (RolloutWorker): Reference to the current rollout worker.
base_env (BaseEnv): BaseEnv running the episode. The underlying
env object can be gotten by calling base_env.get_unwrapped().
policies (dict): Mapping of policy id to policy objects. In single
agent mode there will only be a single "default" policy.
episode (MultiAgentEpisode): Episode object which contains episode
state. You can use the `episode.user_data` dict to store
temporary data, and `episode.custom_metrics` to store custom
metrics for the episode.
env_index (EnvID): Obsoleted: The ID of the environment, which the
episode belongs to.
kwargs: Forward compatibility placeholder.
"""
if env_index is not None:
if log_once("callbacks_env_index_deprecated"):
deprecation_warning("env_index", "episode.env_id", error=False)
if self.legacy_callbacks.get("on_episode_start"):
self.legacy_callbacks["on_episode_start"]({
"env": base_env,
"policy": policies,
"episode": episode,
})
def on_episode_step(self,
*,
worker: "RolloutWorker",
base_env: BaseEnv,
episode: MultiAgentEpisode,
env_index: Optional[int] = None,
**kwargs) -> None:
"""Runs on each episode step.
Args:
worker (RolloutWorker): Reference to the current rollout worker.
base_env (BaseEnv): BaseEnv running the episode. The underlying
env object can be gotten by calling base_env.get_unwrapped().
episode (MultiAgentEpisode): Episode object which contains episode
state. You can use the `episode.user_data` dict to store
temporary data, and `episode.custom_metrics` to store custom
metrics for the episode.
env_index (EnvID): Obsoleted: The ID of the environment, which the
episode belongs to.
kwargs: Forward compatibility placeholder.
"""
if env_index is not None:
if log_once("callbacks_env_index_deprecated"):
deprecation_warning("env_index", "episode.env_id", error=False)
if self.legacy_callbacks.get("on_episode_step"):
self.legacy_callbacks["on_episode_step"]({
"env": base_env,
"episode": episode
})
def on_episode_end(self,
*,
worker: "RolloutWorker",
base_env: BaseEnv,
policies: Dict[PolicyID, Policy],
episode: MultiAgentEpisode,
env_index: Optional[int] = None,
**kwargs) -> None:
"""Runs when an episode is done.
Args:
worker (RolloutWorker): Reference to the current rollout worker.
base_env (BaseEnv): BaseEnv running the episode. The underlying
env object can be gotten by calling base_env.get_unwrapped().
policies (dict): Mapping of policy id to policy objects. In single
agent mode there will only be a single "default" policy.
episode (MultiAgentEpisode): Episode object which contains episode
state. You can use the `episode.user_data` dict to store
temporary data, and `episode.custom_metrics` to store custom
metrics for the episode.
env_index (EnvID): Obsoleted: The ID of the environment, which the
episode belongs to.
kwargs: Forward compatibility placeholder.
"""
if env_index is not None:
if log_once("callbacks_env_index_deprecated"):
deprecation_warning("env_index", "episode.env_id", error=False)
if self.legacy_callbacks.get("on_episode_end"):
self.legacy_callbacks["on_episode_end"]({
"env": base_env,
"policy": policies,
"episode": episode,
})
def on_postprocess_trajectory(
self, *, worker: "RolloutWorker", episode: MultiAgentEpisode,
agent_id: AgentID, policy_id: PolicyID,
policies: Dict[PolicyID, Policy], postprocessed_batch: SampleBatch,
original_batches: Dict[AgentID, SampleBatch], **kwargs) -> None:
"""Called immediately after a policy's postprocess_fn is called.
You can use this callback to do additional postprocessing for a policy,
including looking at the trajectory data of other agents in multi-agent
settings.
Args:
worker (RolloutWorker): Reference to the current rollout worker.
episode (MultiAgentEpisode): Episode object.
agent_id (str): Id of the current agent.
policy_id (str): Id of the current policy for the agent.
policies (dict): Mapping of policy id to policy objects. In single
agent mode there will only be a single "default" policy.
postprocessed_batch (SampleBatch): The postprocessed sample batch
for this agent. You can mutate this object to apply your own
trajectory postprocessing.
original_batches (dict): Mapping of agents to their unpostprocessed
trajectory data. You should not mutate this object.
kwargs: Forward compatibility placeholder.
"""
if self.legacy_callbacks.get("on_postprocess_traj"):
self.legacy_callbacks["on_postprocess_traj"]({
"episode": episode,
"agent_id": agent_id,
"pre_batch": original_batches[agent_id],
"post_batch": postprocessed_batch,
"all_pre_batches": original_batches,
})
def on_sample_end(self, *, worker: "RolloutWorker", samples: SampleBatch,
**kwargs) -> None:
"""Called at the end of RolloutWorker.sample().
Args:
worker (RolloutWorker): Reference to the current rollout worker.
samples (SampleBatch): Batch to be returned. You can mutate this
object to modify the samples generated.
kwargs: Forward compatibility placeholder.
"""
if self.legacy_callbacks.get("on_sample_end"):
self.legacy_callbacks["on_sample_end"]({
"worker": worker,
"samples": samples,
})
def on_learn_on_batch(self, *, policy: Policy, train_batch: SampleBatch,
**kwargs) -> None:
"""Called at the beginning of Policy.learn_on_batch().
Note: This is called before the Model's `preprocess_train_batch()`
is called.
Args:
policy (Policy): Reference to the current Policy object.
train_batch (SampleBatch): SampleBatch to be trained on. You can
mutate this object to modify the samples generated.
kwargs: Forward compatibility placeholder.
"""
pass
def on_train_result(self, *, trainer, result: dict, **kwargs) -> None:
"""Called at the end of Trainable.train().
Args:
trainer (Trainer): Current trainer instance.
result (dict): Dict of results returned from trainer.train() call.
You can mutate this object to add additional metrics.
kwargs: Forward compatibility placeholder.
"""
if self.legacy_callbacks.get("on_train_result"):
self.legacy_callbacks["on_train_result"]({
"trainer": trainer,
"result": result,
})
| |
# -*- 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):
# Adding model 'Card'
db.create_table(u'uppsell_card', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('customer', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['uppsell.Customer'])),
('holder', self.gf('django.db.models.fields.CharField')(max_length=255)),
('reference', self.gf('django.db.models.fields.CharField')(max_length=30, null=True, blank=True)),
('pan', self.gf('django.db.models.fields.CharField')(max_length=30, null=True, blank=True)),
('last4', self.gf('django.db.models.fields.CharField')(max_length=4, null=True, blank=True)),
('network', self.gf('django.db.models.fields.CharField')(default='UNKNOWN', max_length=12)),
('expiry', self.gf('django.db.models.fields.DateField')(null=True, blank=True)),
))
db.send_create_signal(u'uppsell', ['Card'])
def backwards(self, orm):
# Deleting model 'Card'
db.delete_table(u'uppsell_card')
models = {
u'uppsell.address': {
'Meta': {'object_name': 'Address', 'db_table': "'addresses'"},
'city': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'country': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'country_code': ('django.db.models.fields.CharField', [], {'max_length': '3'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'customer': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Customer']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_used': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'line1': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'line2': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'line3': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'other': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'province': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'zip': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'})
},
u'uppsell.card': {
'Meta': {'object_name': 'Card'},
'customer': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Customer']"}),
'expiry': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'holder': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last4': ('django.db.models.fields.CharField', [], {'max_length': '4', 'null': 'True', 'blank': 'True'}),
'network': ('django.db.models.fields.CharField', [], {'default': "'UNKNOWN'", 'max_length': '12'}),
'pan': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}),
'reference': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'})
},
u'uppsell.cart': {
'Meta': {'object_name': 'Cart', 'db_table': "'carts'"},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'customer': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Customer']", 'null': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'store': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Store']"}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
u'uppsell.cartitem': {
'Meta': {'unique_together': "(('cart', 'product'),)", 'object_name': 'CartItem', 'db_table': "'cart_items'"},
'cart': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Cart']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Listing']"}),
'quantity': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'})
},
u'uppsell.coupon': {
'Meta': {'object_name': 'Coupon', 'db_table': "'coupons'"},
'code': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'customer': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Customer']", 'null': 'True', 'blank': 'True'}),
'discount_amount': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '8', 'decimal_places': '2', 'blank': 'True'}),
'discount_pct': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'max_uses': ('django.db.models.fields.PositiveIntegerField', [], {}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Listing']", 'null': 'True', 'blank': 'True'}),
'product_group': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.ProductGroup']", 'null': 'True', 'blank': 'True'}),
'relation': ('django.db.models.fields.CharField', [], {'max_length': '16'}),
'remaining': ('django.db.models.fields.PositiveIntegerField', [], {}),
'store': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Store']"}),
'type': ('django.db.models.fields.CharField', [], {'max_length': '16'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'valid_from': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'valid_until': ('django.db.models.fields.DateTimeField', [], {})
},
u'uppsell.couponspend': {
'Meta': {'unique_together': "(('customer', 'coupon'),)", 'object_name': 'CouponSpend', 'db_table': "'coupon_spends'"},
'coupon': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Coupon']"}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'customer': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Customer']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
u'uppsell.customer': {
'Meta': {'object_name': 'Customer', 'db_table': "'customers'"},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'db_index': 'True', 'max_length': '75', 'blank': 'True'}),
'full_name': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_logged_in_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'phone': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '30', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'uppsell.invoice': {
'Meta': {'object_name': 'Invoice', 'db_table': "'invoices'"},
'billing_address': ('django.db.models.fields.CharField', [], {'max_length': '1000'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'currency': ('django.db.models.fields.CharField', [], {'max_length': '3'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'order_id': ('django.db.models.fields.IntegerField', [], {'unique': 'True'}),
'order_shipping_total': ('django.db.models.fields.DecimalField', [], {'max_digits': '8', 'decimal_places': '2'}),
'order_total': ('django.db.models.fields.DecimalField', [], {'max_digits': '8', 'decimal_places': '2'}),
'payment_made_ts': ('django.db.models.fields.DateTimeField', [], {}),
'product_id': ('django.db.models.fields.IntegerField', [], {}),
'psp_id': ('django.db.models.fields.IntegerField', [], {}),
'psp_response_code': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'psp_response_text': ('django.db.models.fields.CharField', [], {'max_length': '10000'}),
'psp_type': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'quantity': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'shipping_address': ('django.db.models.fields.CharField', [], {'max_length': '1000'}),
'store_id': ('django.db.models.fields.IntegerField', [], {}),
'transaction_id': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'user_email': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'user_fullname': ('django.db.models.fields.CharField', [], {'max_length': '1000'}),
'user_jid': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'user_mobile_msisdn': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
u'uppsell.linkedaccount': {
'Meta': {'object_name': 'LinkedAccount', 'db_table': "'linked_accounts'"},
'account_id': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'customer': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Customer']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '2000'}),
'linked_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'provider': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.LinkedAccountType']"}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
u'uppsell.linkedaccounttype': {
'Meta': {'object_name': 'LinkedAccountType', 'db_table': "'linked_account_types'"},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'type': ('django.db.models.fields.CharField', [], {'max_length': '32'})
},
u'uppsell.listing': {
'Meta': {'object_name': 'Listing', 'db_table': "'listings'"},
'description': ('django.db.models.fields.CharField', [], {'max_length': '10000', 'null': 'True', 'blank': 'True'}),
'features': ('django.db.models.fields.CharField', [], {'max_length': '10000', 'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'price': ('django.db.models.fields.DecimalField', [], {'default': '0.0', 'max_digits': '24', 'decimal_places': '12'}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Product']"}),
'shipping': ('django.db.models.fields.DecimalField', [], {'default': '0.0', 'max_digits': '24', 'decimal_places': '12'}),
'state': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
'store': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Store']"}),
'subtitle': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'tax_rate': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.SalesTaxRate']"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'})
},
u'uppsell.order': {
'Meta': {'object_name': 'Order', 'db_table': "'orders'"},
'billing_address': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'billing_address'", 'null': 'True', 'to': u"orm['uppsell.Address']"}),
'coupon': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Coupon']", 'null': 'True'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'currency': ('django.db.models.fields.CharField', [], {'max_length': '3'}),
'customer': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Customer']"}),
'fraud_state': ('django.db.models.fields.CharField', [], {'max_length': '30'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'order_state': ('django.db.models.fields.CharField', [], {'default': "'init'", 'max_length': '30'}),
'payment_made_ts': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'payment_state': ('django.db.models.fields.CharField', [], {'default': "'init'", 'max_length': '30'}),
'shipping_address': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'shipping_address'", 'null': 'True', 'to': u"orm['uppsell.Address']"}),
'store': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Store']"}),
'transaction_id': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
u'uppsell.orderevent': {
'Meta': {'object_name': 'OrderEvent', 'db_table': "'order_events'"},
'action_type': ('django.db.models.fields.CharField', [], {'max_length': '30'}),
'comment': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'blank': 'True'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'event': ('django.db.models.fields.CharField', [], {'max_length': '30'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'order': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Order']"}),
'state_after': ('django.db.models.fields.CharField', [], {'max_length': '30'}),
'state_before': ('django.db.models.fields.CharField', [], {'max_length': '30'})
},
u'uppsell.orderitem': {
'Meta': {'object_name': 'OrderItem', 'db_table': "'order_items'"},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'order': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Order']"}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Listing']"}),
'quantity': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'})
},
u'uppsell.product': {
'Meta': {'object_name': 'Product', 'db_table': "'products'"},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '10000'}),
'features': ('django.db.models.fields.CharField', [], {'max_length': '10000', 'null': 'True', 'blank': 'True'}),
'group': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.ProductGroup']"}),
'has_stock': ('django.db.models.fields.BooleanField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'provisioning_codes': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'shipping': ('django.db.models.fields.BooleanField', [], {}),
'sku': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'stock_units': ('django.db.models.fields.FloatField', [], {'default': '0.0'}),
'subtitle': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
u'uppsell.productcode': {
'Meta': {'object_name': 'ProductCode', 'db_table': "'product_codes'"},
'code': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.ProductGroup']"}),
'type': ('django.db.models.fields.CharField', [], {'max_length': '20'})
},
u'uppsell.productgroup': {
'Meta': {'object_name': 'ProductGroup', 'db_table': "'product_groups'"},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'uppsell.salestaxrate': {
'Meta': {'object_name': 'SalesTaxRate'},
'abbreviation': ('django.db.models.fields.CharField', [], {'max_length': "'10'"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': "'20'"}),
'rate': ('django.db.models.fields.DecimalField', [], {'default': '0.0', 'max_digits': '6', 'decimal_places': '5'}),
'store': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['uppsell.Store']"})
},
u'uppsell.store': {
'Meta': {'object_name': 'Store', 'db_table': "'stores'"},
'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'default_currency': ('django.db.models.fields.CharField', [], {'max_length': '3'}),
'default_lang': ('django.db.models.fields.CharField', [], {'max_length': '3'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
}
}
complete_apps = ['uppsell']
| |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import DataMigration
from django.db import IntegrityError, models, transaction, connection
from sentry.utils.query import RangeQuerySetWrapperWithProgressBar
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
qs = orm.Release.objects.all().select_related('project')
for r in RangeQuerySetWrapperWithProgressBar(qs):
if not r.organization_id:
orm.Release.objects.filter(id=r.id).update(organization=r.project.organization_id)
try:
with transaction.atomic():
orm.ReleaseProject.objects.create(release=r, project=r.project)
except IntegrityError:
pass
def backwards(self, orm):
"Write your backwards methods here."
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'
}),
'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.apitoken': {
'Meta': {
'object_name': 'ApiToken'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.ApiKey']",
'null': 'True'
}
),
'scopes': ('django.db.models.fields.BigIntegerField', [], {
'default': 'None'
}),
'token':
('django.db.models.fields.CharField', [], {
'unique': 'True',
'max_length': '64'
}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'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.authenticator': {
'Meta': {
'unique_together': "(('user', 'type'),)",
'object_name': 'Authenticator',
'db_table': "'auth_authenticator'"
},
'config': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}),
'created_at':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id': ('sentry.db.models.fields.bounded.BoundedAutoField', [], {
'primary_key': 'True'
}),
'last_used_at': ('django.db.models.fields.DateTimeField', [], {
'null': 'True'
}),
'type': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'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': ('sentry.db.models.fields.jsonfield.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': ('sentry.db.models.fields.jsonfield.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(2016, 12, 10, 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.commit': {
'Meta': {
'unique_together': "(('repository_id', 'key'),)",
'object_name': 'Commit',
'index_together': "(('repository_id', 'date_added'),)"
},
'author': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.CommitAuthor']",
'null': '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', [], {
'max_length': '64'
}),
'message': ('django.db.models.fields.TextField', [], {
'null': 'True'
}),
'organization_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'repository_id':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {})
},
'sentry.commitauthor': {
'Meta': {
'unique_together': "(('organization_id', 'email'),)",
'object_name': 'CommitAuthor'
},
'email': ('django.db.models.fields.EmailField', [], {
'max_length': '75'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name':
('django.db.models.fields.CharField', [], {
'max_length': '128',
'null': 'True'
}),
'organization_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
)
},
'sentry.commitfilechange': {
'Meta': {
'unique_together': "(('commit', 'filename'),)",
'object_name': 'CommitFileChange'
},
'commit': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Commit']"
}
),
'filename': ('django.db.models.fields.CharField', [], {
'max_length': '255'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'organization_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'type': ('django.db.models.fields.CharField', [], {
'max_length': '1'
})
},
'sentry.counter': {
'Meta': {
'object_name': 'Counter',
'db_table': "'sentry_projectcounter'"
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']",
'unique': 'True'
}
),
'value': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {})
},
'sentry.dsymbundle': {
'Meta': {
'object_name': 'DSymBundle'
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'object': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.DSymObject']"
}
),
'sdk': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.DSymSDK']"
}
)
},
'sentry.dsymobject': {
'Meta': {
'object_name': 'DSymObject'
},
'cpu_name': ('django.db.models.fields.CharField', [], {
'max_length': '40'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'object_path': ('django.db.models.fields.TextField', [], {
'db_index': 'True'
}),
'uuid':
('django.db.models.fields.CharField', [], {
'max_length': '36',
'db_index': 'True'
}),
'vmaddr':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True'
}),
'vmsize':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True'
})
},
'sentry.dsymsdk': {
'Meta': {
'object_name':
'DSymSDK',
'index_together':
"[('version_major', 'version_minor', 'version_patchlevel', 'version_build')]"
},
'dsym_type':
('django.db.models.fields.CharField', [], {
'max_length': '20',
'db_index': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'sdk_name': ('django.db.models.fields.CharField', [], {
'max_length': '20'
}),
'version_build': ('django.db.models.fields.CharField', [], {
'max_length': '40'
}),
'version_major': ('django.db.models.fields.IntegerField', [], {}),
'version_minor': ('django.db.models.fields.IntegerField', [], {}),
'version_patchlevel': ('django.db.models.fields.IntegerField', [], {})
},
'sentry.dsymsymbol': {
'Meta': {
'unique_together': "[('object', 'address')]",
'object_name': 'DSymSymbol'
},
'address':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'db_index': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'object': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.DSymObject']"
}
),
'symbol': ('django.db.models.fields.TextField', [], {})
},
'sentry.environment': {
'Meta': {
'unique_together': "(('project_id', 'name'),)",
'object_name': 'Environment'
},
'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': '64'
}),
'project_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {})
},
'sentry.event': {
'Meta': {
'unique_together': "(('project_id', 'event_id'),)",
'object_name': 'Event',
'db_table': "'sentry_message'",
'index_together': "(('group_id', '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_id': (
'sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True',
'blank': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'message': ('django.db.models.fields.TextField', [], {}),
'platform':
('django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True'
}),
'project_id': (
'sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True',
'blank': 'True'
}
),
'time_spent':
('sentry.db.models.fields.bounded.BoundedIntegerField', [], {
'null': 'True'
})
},
'sentry.eventmapping': {
'Meta': {
'unique_together': "(('project_id', '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_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {})
},
'sentry.eventtag': {
'Meta': {
'unique_together':
"(('event_id', 'key_id', 'value_id'),)",
'object_name':
'EventTag',
'index_together':
"(('project_id', 'key_id', 'value_id'), ('group_id', 'key_id', 'value_id'))"
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'event_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}),
'group_id':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}),
'project_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}),
'value_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {})
},
'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', [], {
'related_name': "'legacy_blob'",
'null': 'True',
'to': "orm['sentry.FileBlob']"
}
),
'blobs': (
'django.db.models.fields.related.ManyToManyField', [], {
'to': "orm['sentry.FileBlob']",
'through': "orm['sentry.FileBlobIndex']",
'symmetrical': 'False'
}
),
'checksum':
('django.db.models.fields.CharField', [], {
'max_length': '40',
'null': 'True'
}),
'headers': ('sentry.db.models.fields.jsonfield.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.fileblobindex': {
'Meta': {
'unique_together': "(('file', 'blob', 'offset'),)",
'object_name': 'FileBlobIndex'
},
'blob': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.FileBlob']"
}
),
'file': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.File']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'offset': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {})
},
'sentry.globaldsymfile': {
'Meta': {
'object_name': 'GlobalDSymFile'
},
'cpu_name': ('django.db.models.fields.CharField', [], {
'max_length': '40'
}),
'file': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.File']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'object_name': ('django.db.models.fields.TextField', [], {}),
'uuid':
('django.db.models.fields.CharField', [], {
'unique': 'True',
'max_length': '36'
})
},
'sentry.group': {
'Meta': {
'unique_together': "(('project', 'short_id'),)",
'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',
'on_delete': 'models.PROTECT'
}
),
'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'
}),
'short_id':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True'
}),
'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.groupredirect': {
'Meta': {
'object_name': 'GroupRedirect'
},
'group_id':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'db_index': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'previous_group_id':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'unique': 'True'
})
},
'sentry.grouprelease': {
'Meta': {
'unique_together': "(('group_id', 'release_id', 'environment'),)",
'object_name': 'GroupRelease'
},
'environment':
('django.db.models.fields.CharField', [], {
'default': "''",
'max_length': '64'
}),
'first_seen':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'group_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'last_seen': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'project_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'release_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
)
},
'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.groupsubscription': {
'Meta': {
'unique_together': "(('group', 'user'),)",
'object_name': 'GroupSubscription'
},
'date_added': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'null': 'True'
}
),
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'subscription_set'",
'to': "orm['sentry.Group']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'is_active': ('django.db.models.fields.BooleanField', [], {
'default': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'subscription_set'",
'to': "orm['sentry.Project']"
}
),
'reason':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'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': "(('group', 'key', 'value'),)",
'object_name': 'GroupTagValue',
'db_table': "'sentry_messagefiltervalue'",
'index_together': "(('project', 'key', 'value', 'last_seen'),)"
},
'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.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'
},
'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'
}
),
'token': (
'django.db.models.fields.CharField', [], {
'max_length': '64',
'unique': 'True',
'null': 'True',
'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.organizationonboardingtask': {
'Meta': {
'unique_together': "(('organization', 'task'),)",
'object_name': 'OrganizationOnboardingTask'
},
'data': ('sentry.db.models.fields.jsonfield.JSONField', [], {
'default': '{}'
}),
'date_completed':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Organization']"
}
),
'project_id': (
'sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True',
'blank': 'True'
}
),
'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'task': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']",
'null': 'True'
}
)
},
'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'
}),
'forced_color': (
'django.db.models.fields.CharField', [], {
'max_length': '6',
'null': 'True',
'blank': '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.projectbookmark': {
'Meta': {
'unique_together': "(('project_id', 'user'),)",
'object_name': 'ProjectBookmark'
},
'date_added': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'null': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project_id': (
'sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True',
'blank': 'True'
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'sentry.projectdsymfile': {
'Meta': {
'unique_together': "(('project', 'uuid'),)",
'object_name': 'ProjectDSymFile'
},
'cpu_name': ('django.db.models.fields.CharField', [], {
'max_length': '40'
}),
'file': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.File']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'object_name': ('django.db.models.fields.TextField', [], {}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']",
'null': 'True'
}
),
'uuid': ('django.db.models.fields.CharField', [], {
'max_length': '36'
})
},
'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.projectplatform': {
'Meta': {
'unique_together': "(('project_id', 'platform'),)",
'object_name': 'ProjectPlatform'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'last_seen':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'platform': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'project_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {})
},
'sentry.release': {
'Meta': {
'unique_together': "(('project', 'version'),)",
'object_name': 'Release'
},
'data': ('sentry.db.models.fields.jsonfield.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'
}),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Organization']",
'null': 'True',
'blank': 'True'
}
),
'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']"
}
),
'projects': (
'django.db.models.fields.related.ManyToManyField', [], {
'related_name': "'releases'",
'symmetrical': 'False',
'through': "orm['sentry.ReleaseProject']",
'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.releasecommit': {
'Meta': {
'unique_together': "(('release', 'commit'), ('release', 'order'))",
'object_name': 'ReleaseCommit'
},
'commit': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Commit']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'order': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'project_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'release': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Release']"
}
)
},
'sentry.releaseenvironment': {
'Meta': {
'unique_together': "(('project_id', 'release_id', 'environment_id'),)",
'object_name': 'ReleaseEnvironment',
'db_table': "'sentry_environmentrelease'"
},
'environment_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'first_seen':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'last_seen': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'project_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'release_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
)
},
'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.releaseproject': {
'Meta': {
'unique_together': "(('project', 'release'),)",
'object_name': 'ReleaseProject',
'db_table': "'sentry_release_project'"
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'release': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Release']"
}
)
},
'sentry.repository': {
'Meta': {
'unique_together':
"(('organization_id', 'name'), ('organization_id', 'provider', 'external_id'))",
'object_name':
'Repository'
},
'config': ('sentry.db.models.fields.jsonfield.JSONField', [], {
'default': '{}'
}),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'external_id':
('django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name': ('django.db.models.fields.CharField', [], {
'max_length': '200'
}),
'organization_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'provider':
('django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True'
}),
'status': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0',
'db_index': 'True'
}
),
'url': ('django.db.models.fields.URLField', [], {
'max_length': '200',
'null': 'True'
})
},
'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']"
}
),
'status': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0',
'db_index': 'True'
}
)
},
'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'
}),
'is_default': ('django.db.models.fields.BooleanField', [], {
'default': 'False'
}),
'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.savedsearchuserdefault': {
'Meta': {
'unique_together': "(('project', 'user'),)",
'object_name': 'SavedSearchUserDefault',
'db_table': "'sentry_savedsearch_userdefault'"
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'savedsearch': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.SavedSearch']"
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'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'
}),
'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_password_expired':
('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_password_change': ('django.db.models.fields.DateTimeField', [], {
'null': 'True'
}),
'name': (
'django.db.models.fields.CharField', [], {
'max_length': '200',
'db_column': "'first_name'",
'blank': 'True'
}
),
'password': ('django.db.models.fields.CharField', [], {
'max_length': '128'
}),
'session_nonce':
('django.db.models.fields.CharField', [], {
'max_length': '12',
'null': 'True'
}),
'username':
('django.db.models.fields.CharField', [], {
'unique': 'True',
'max_length': '128'
})
},
'sentry.useravatar': {
'Meta': {
'object_name': 'UserAvatar'
},
'avatar_type':
('django.db.models.fields.PositiveSmallIntegerField', [], {
'default': '0'
}),
'file': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.File']",
'unique': 'True',
'null': 'True',
'on_delete': 'models.SET_NULL'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'ident': (
'django.db.models.fields.CharField', [], {
'unique': 'True',
'max_length': '32',
'db_index': 'True'
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'avatar'",
'unique': 'True',
'to': "orm['sentry.User']"
}
)
},
'sentry.useremail': {
'Meta': {
'unique_together': "(('user', 'email'),)",
'object_name': 'UserEmail'
},
'date_hash_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'email': ('django.db.models.fields.EmailField', [], {
'max_length': '75'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'is_verified': ('django.db.models.fields.BooleanField', [], {
'default': 'False'
}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'emails'",
'to': "orm['sentry.User']"
}
),
'validation_hash': (
'django.db.models.fields.CharField', [], {
'default': "u'ncR7oP5gQkHMtbuggkvu38x6MgCv3NRw'",
'max_length': '32'
}
)
},
'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': {
'unique_together': "(('project', 'event_id'),)",
'object_name': 'UserReport',
'index_together': "(('project', 'event_id'), ('project', 'date_added'))"
},
'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']
symmetrical = True
| |
#
# Copyright (c) 2014 Chris Jerdonek. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
from contextlib import contextmanager
import os
import tempfile
from tempfile import TemporaryDirectory
from openrcv import streams
from openrcv.streams import (tracked, FilePathResource,
ReadWriteFileResource, StringResource)
from openrcv.utiltest.helpers import UnitCase
class _Exception(Exception):
pass
class TrackedTest(UnitCase):
"""Tests of tracked()."""
def test(self):
stream = ['a', 'b', 'c']
gen = tracked("foo", stream)
items = list(gen)
self.assertEqual(items, ['a', 'b', 'c'])
# Check that the return value exhausts (i.e. is an iterator object).
items = list(gen)
self.assertEqual(items, [])
def test__exception(self):
stream = ['a', 'b', 'c']
gen = tracked("foo", stream)
first = next(gen)
self.assertEqual(first, "a")
second = next(gen)
with self.assertRaises(ValueError) as cm:
gen.throw(ValueError("foo"))
# Check the exception text.
err = cm.exception
self.assertEqual(str(err), "last read item from 'foo' (number=2): 'b'")
# TODO: check that "foo" is also in the exception.
class StreamResourceTestMixin(object):
"""Base mixin for StreamResource tests."""
@property
def class_name(self):
return self.cls.__name__
def test_reading(self):
with self.resource() as resource:
with resource.reading() as stream:
items = list(stream)
self.assertEqual(items, ["a\n", "b\n"])
# Check that you can read again.
with resource.reading() as stream2:
items = list(stream2)
self.assertEqual(items, ["a\n", "b\n"])
# Sanity-check that reading() doesn't return the same object each time.
self.assertIsNot(stream, stream2)
def test_reading__closes(self):
"""Check that the context manager closes the generator."""
with self.resource() as resource:
with resource.reading() as gen:
# We deliberately read only one of the two items.
item = next(gen)
self.assertEqual(item, "a\n")
self.assertGeneratorClosed(gen)
def test_reading__iterator(self):
"""Check that reading() returns an iterator [1].
[1]: https://docs.python.org/3/glossary.html#term-iterator
"""
with self.resource() as resource:
with resource.reading() as stream:
# Check that __iter__() returns itself.
self.assertIs(iter(stream), stream)
# Check that the iterable exhausts after iteration.
items = tuple(stream)
with self.assertRaises(StopIteration):
next(stream)
self.assertEqual(items, ("a\n", "b\n"))
def test_reading__error(self):
"""Check that an error while reading shows the line number."""
with self.assertRaises(_Exception) as cm:
with self.resource() as resource:
with resource.reading() as stream:
item = next(stream)
self.assertEqual(item, "a\n")
raise _Exception()
# Check the exception text.
err = cm.exception
self.assertStartsWith(str(err), "last read item from <%s:" % self.class_name)
self.assertEndsWith(str(err), "(number=1): 'a\\n'")
def test_writing(self):
with self.resource() as resource:
with resource.writing() as target:
target.send('c\n')
target.send('d\n')
self.assertResourceContents(resource, ['c\n', 'd\n'])
def test_writing__closes(self):
"""Check that the context manager closes the generator."""
with self.resource() as resource:
with resource.writing() as gen:
gen.send('c\n')
self.assertGeneratorClosed(gen)
def test_writing__deletes(self):
"""Check that writing() deletes the current data."""
with self.resource() as resource:
self.assertResourceContents(resource, ['a\n', 'b\n'])
with resource.writing() as gen:
pass
self.assertResourceContents(resource, [])
class ListResourceTest(StreamResourceTestMixin, UnitCase):
"""ListResource tests."""
cls = streams.ListResource
@contextmanager
def resource(self):
yield self.cls(["a\n", "b\n"])
def test_temp(self):
with self.cls.temp() as temp_resource:
with temp_resource.writing() as gen:
gen.send("f\n")
self.assertResourceContents(temp_resource, ["f\n"])
# Check that the temp resource was deleted.
self.assertResourceContents(temp_resource, [])
def test_replacement(self):
with self.resource() as resource:
with resource.replacement() as temp_resource:
with temp_resource.writing() as gen:
gen.send("f\n")
self.assertResourceContents(resource, ["a\n", "b\n"])
self.assertResourceContents(temp_resource, ["f\n"])
# Check after replacement.
self.assertResourceContents(resource, ["f\n"])
self.assertResourceContents(temp_resource, [])
class FilePathResourceTest(StreamResourceTestMixin, UnitCase):
"""FilePathResource tests."""
cls = streams.FilePathResource
@contextmanager
def resource(self):
with TemporaryDirectory() as dirname:
path = os.path.join(dirname, 'temp.txt')
with open(path, 'w') as f:
f.write('a\nb\n')
yield FilePathResource(path)
class ReadWriteFileResourceTest(StreamResourceTestMixin, UnitCase):
"""ReadWriteFileResource tests."""
cls = streams.ReadWriteFileResource
@contextmanager
def resource(self):
with tempfile.TemporaryFile(mode='w+t', encoding='ascii') as f:
f.write('a\nb\n')
yield ReadWriteFileResource(f)
class SpooledReadWriteFileResourceTest(StreamResourceTestMixin, UnitCase):
"""ReadWriteFileResource tests (using tempfile.SpooledTemporaryFile)."""
cls = streams.ReadWriteFileResource
@contextmanager
def resource(self):
with tempfile.SpooledTemporaryFile(mode='w+t', encoding='ascii') as f:
f.write('a\nb\n')
yield ReadWriteFileResource(f)
# TODO: add StandardResource tests.
class StringResourceTest(StreamResourceTestMixin, UnitCase):
"""StringResource tests."""
cls = streams.StringResource
@contextmanager
def resource(self):
yield StringResource('a\nb\n')
class _Converter(object):
def from_resource(self, item):
return 2 * item
def to_resource(self, item):
return 3 * item
class ConvertingResourceTest(UnitCase):
"""Tests of the ConvertingResource class."""
def test_reading(self):
backing = streams.ListResource([1, 2, 3])
converter = _Converter()
resource = streams.ConvertingResource(backing, converter=converter)
with resource.reading() as gen:
items = list(gen)
self.assertEqual(items, [2, 4, 6])
self.assertGeneratorClosed(gen)
def test_writing(self):
backing = streams.ListResource()
converter = _Converter()
resource = streams.ConvertingResource(backing, converter=converter)
with resource.writing() as gen:
for i in range(4):
gen.send(i)
self.assertGeneratorClosed(gen)
self.assertResourceContents(backing, [0, 3, 6, 9])
| |
import re
from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.test import TestCase
import LabtrackerCore.utils as utils
import LabtrackerCore.models as coreModels
from datetime import date, datetime
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["Machine.models.MacField"])
class MacField(models.CharField):
description = "A field for mac addresses"
default_error_messages = {
'invalid': (u'Enter a valid MAC address.'),
}
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 17
kwargs['help_text'] = 'Please use the following format: 00:AA:1B:00:00:00.'
super(MacField, self).__init__(*args, **kwargs)
def db_type(self, connection):
return 'char(17)'
def validate(self, value, model_instance):
if re.search('^([0-9a-fA-F]{2}([:]?|$)){6}$', value) == None:
raise ValidationError('Enter a valid MAC address.')
class Status(models.Model):
"""
Status of the machine
"""
ms_id = models.AutoField(primary_key=True)
name = models.SlugField(max_length=60, unique=True)
description = models.CharField(max_length=400, blank=True)
def __unicode__(self):
return self.name
class Meta:
verbose_name_plural="Status"
unique_together = (("ms_id", "name"),)
class Platform(models.Model):
"""
Machine Platform: windows XP, Vista, Mac OS X, Linux/Ubuntu, etc.
"""
platform_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=60, unique=True)
description = models.CharField(max_length=400, blank=True)
def __unicode__(self):
return self.name
class Type(models.Model):
"""
Type of Machine, not InventoryType, similar to a group
"""
mt_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=60, unique=True)
platform = models.ForeignKey(Platform)
model_name = models.CharField(max_length=60)
specs = models.TextField()
description = models.CharField(max_length=400, blank=True)
def __unicode__(self):
return self.name
class Location(models.Model):
ml_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=60, unique=True)
building = models.CharField(max_length=60, null=True)
floor = models.SmallIntegerField(null=True, blank=True)
room = models.CharField(max_length=30, null=True)
comment = models.CharField(max_length=600)
usable_threshold = models.IntegerField(default=95)
def __unicode__(self):
return self.name
class Item(coreModels.Item):
"""
The Machine
"""
core = models.OneToOneField(coreModels.Item, parent_link=True,
editable=False)
type = models.ForeignKey(Type, verbose_name='Machine Type')
verified = models.BooleanField()
unusable = models.BooleanField()
retired = models.BooleanField()
status = models.ManyToManyField(Status, related_name="machine_status", blank=True)
location = models.ForeignKey(Location, verbose_name='Location')
ip = models.IPAddressField(verbose_name="IP Address")
mac1 = MacField(verbose_name='MAC Address')
mac2 = MacField(verbose_name='Additional MAC Address', blank=True)
mac3 = MacField(verbose_name='Additional MAC Address', blank=True)
wall_port = models.CharField(max_length=25)
date_added = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
manu_tag = models.CharField(max_length=200,
verbose_name="Manufacturers tag")
uw_tag = models.CharField(max_length=200, verbose_name="UW tag",
blank=True, null=True)
purchase_date = models.DateField(null=True, blank=True)
warranty_date = models.DateField(null=True, blank=True)
stf_date = models.DateField(null=True, blank=True,
verbose_name='Student Tech Fee Contract Expiration')
comment = models.TextField(blank=True, null=True)
def usable(self):
return (not self.unusable)
usable.boolean = True
@models.permalink
def get_absolute_url(self):
return ('Machine-detail', [str(self.pk),])
def primaryContact(self):
"""
Returns the primary contact for this item, or None if no primary
contact exists
"""
# first check to see if item has groups, then fetch the groups, and
# call the groups primary contact function
return Contact.objects.filter(is_primary=True, mg__items__pk=self.pk)
def __unicode__(self):
return self.item.name
def delete(self):
self.core.delete() # delete the item in coreModels.Item
super(Item,self).delete() # delete self
def save(self, *args, **kwargs):
self.it = utils.getInventoryType(__name__)
super(Item,self).save(*args, **kwargs)
class Group(coreModels.Group):
"""
Expands on the coreModels.Group
"""
core = models.OneToOneField(coreModels.Group, parent_link=True, editable=False)
is_lab = models.BooleanField()
casting_server = models.IPAddressField()
gateway = models.IPAddressField()
def primaryContact(self):
"""
for this group find primary contact, returns set of users
"""
return self.contact_set.filter(is_primary=True)
def contacts(self):
"""
Returns the set of all contacts for this group
"""
return self.contact_set.filter()
def __unicode__(self):
return self.group.name
def delete(self):
self.group.delete()
super(Group,self).delete()
def save(self):
if (self.it == None):
self.it = utils.getInventoryType(__name__)
super(Group,self).save()
class History(models.Model):
mh_id = models.AutoField(primary_key=True)
machine = models.ForeignKey(Item)
ms = models.ManyToManyField(Status, null=True, blank=True)
user = models.ForeignKey(coreModels.LabUser)
session_time = models.DecimalField(max_digits=16, decimal_places=2, null=True, blank=True)
login_time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return "%s-%s-%s" % (self.machine.location,self.machine.name,self.login_time)
class Contact(models.Model):
contact_id = models.AutoField(primary_key=True)
mg = models.ForeignKey(Group)
user = models.ForeignKey(User)
is_primary = models.BooleanField(default=False)
def __unicode__(self):
extra = ("", " (Primary)")[self.is_primary]
return "%s - %s%s" % (self.mg, self.user, extra)
"""
Test Cases
"""
class PlatformTest(TestCase):
def setUp(self):
"""
Create a platform
"""
self.name = "ArchLinux"
self.platform = Platform.objects.create(
name = "ArchLinux",
description = "ArchLinux distribution"
)
def testExistance(self):
platforms = Platform.objects.filter(name="ArchLinux")
assert(len(platforms) == 1)
self.assertEquals(platforms[0], self.platform)
def tearDown(self):
self.platform.delete()
class TypeTest(TestCase):
def setUp(self):
"""
Create a test item
"""
self.name = "Gaming Station"
self.type = Type.objects.create(
name = "Gaming Station",
model_name = "Dell Optiplex 2002",
platform = Platform.objects.all()[0],
specs = "stuff",
description = ""
)
def tearDown(self):
self.type.delete()
class StatusTest(TestCase):
def setUp(self):
self.name = "test"
self.status = Status.objects.create(
description = "teststatus",
name = "test",
)
self.status.save()
def testExistance(self):
status = Status.objects.filter(name=self.name)
assert(len(status) == 1)
self.assertEquals(status[0], self.status)
class LocationTest(TestCase):
def setUp(self):
self.name = "test"
self.location = Location.objects.create(
building = "test",
comment = "test",
room = 101,
name = self.name,
floor = 1
)
self.location.save()
def testExistance(self):
location = Location.objects.filter(name=self.name)
assert(len(location) == 1)
self.assertEquals(location[0], self.location)
class MachineItemTest(TestCase):
def setUp(self):
"""
A create a machine item
"""
coreModels.InventoryType.objects.create(
name="Machine",
namespace="Machine",
description="Machine inv type"
)
self.platform = Platform.objects.create(
name = "ArchLinux",
description = "ArchLinux distribution"
)
self.platform.save()
self.type = Type.objects.create(
name = "Gaming Station",
model_name = "Dell Optiplex 2002",
platform = Platform.objects.all()[0],
specs = "stuff",
description = ""
)
self.type.save()
self.status = Status.objects.create(
description = "teststatus",
name = "test",
)
self.status.save()
self.location = Location.objects.create(
building = "test",
comment = "test",
room = 101,
name = "test",
floor = 1
)
self.location.save()
self.name = "test_name_abcd"
self.item = Item.objects.create(
name=self.name,
type=self.type,
location=self.location,
purchase_date = "2009-01-07",
warranty_date = "2009-01-07",
wall_port = "adj",
ip="18.121.342.11",
mac1="00:34:A3:DF:XA:90",
manu_tag="manufactuer tag",
uw_tag="uw tag",
comment="comment")
self.item.status.add(self.status)
self.item.save()
def testParent(self):
"""
Test and see if the parent exists
"""
parent = coreModels.Item.objects.get(name=self.name)
self.assertEquals(parent.item.name, self.name)
| |
from __future__ import division
# -*- coding: utf-8 -*-
"""
Written by Daniel M. Aukes.
Email: danaukes<at>seas.harvard.edu.
Please see LICENSE.txt for full license.
"""
import popupcad
import numpy
from popupcad.filetypes.popupcad_file import popupCADFile
try:
import itertools.izip as zip
except ImportError:
pass
import os
class GenericLaminate(popupCADFile):
filetypes = {'laminate': 'Laminate File'}
defaultfiletype = 'laminate'
def __init__(self, layerdef, geoms):
super(GenericLaminate, self).__init__()
self.layerdef = layerdef
self.geoms = geoms
def copy(self, identical=True):
geoms = {}
for key, value in self.geoms.items():
geoms[key] = [item.copy(identical) for item in value]
new = type(self)(self.layerdef, geoms)
if identical:
new.id = self.id
return new
def to_csg(self):
from popupcad.filetypes.laminate import Laminate
new = Laminate(self.layerdef)
for ii, layer in enumerate(self.layerdef.layers):
geoms = [item.to_shapely() for item in self.geoms[layer]]
new.replacelayergeoms(layer, geoms)
return new
def to_static(self):
display_geometry_2d = {}
for layer, geometry in self.geoms.items():
displaygeometry = [
geom.outputstatic(
brush_color=layer.color) for geom in geometry]
display_geometry_2d[layer] = displaygeometry
return display_geometry_2d
def to_triangles(self):
triangles_by_layer = {}
for layer, geoms in self.geoms.items():
triangles = []
for geom in geoms:
try:
triangles.extend(geom.triangles3())
except AttributeError:
pass
triangles_by_layer[layer] = triangles
return triangles_by_layer
def layers(self):
return self.layerdef.layers
def to_static_sorted(self):
items = []
display_geometry = self.to_static()
layers = self.layerdef.layers
for layer in layers:
items.extend(display_geometry[layer])
return items
def raster(
self,
filename,
filetype='PNG',
destination=None,
gv=None,
size=(
400,
300)):
if gv is None:
from popupcad.widgets.render_widget import RenderWidget
widget = RenderWidget(size)
gv = widget.gv
gv.scene().clear()
[gv.scene().addItem(item) for item in self.to_static_sorted()]
gv.zoomToFit(buffer=0)
filename_out = gv.raster(destination, filename, filetype)
return filename_out
def to_svg(self,filename,destination,gv=None,size=(400,300)):
if gv is None:
from popupcad.widgets.render_widget import RenderWidget
widget = RenderWidget(size)
gv = widget.gv
gv.scene().clear()
[gv.scene().addItem(item) for item in self.to_static_sorted()]
gv.zoomToFit(buffer=0)
import os
filename_out = os.path.join(destination,filename)
gv.scene().renderprocess(filename,1.0,False,0,False,destination)
return filename_out
def save_dxf(self,filename):
import ezdxf
ezdxf.options.template_dir = popupcad.supportfiledir
dwg = ezdxf.new('AC1015')
msp = dwg.modelspace()
for ii,layer in enumerate(self.layerdef.layers):
layername = '{:03.0f}_'.format(ii)+layer.name
dwg.layers.create(name=layername)
for item in self.geoms[layer]:
if not item.is_construction():
item.output_dxf(msp,layername)
dwg.saveas(filename)
def transform(self,T):
geoms = {}
for key, value in self.geoms.items():
geoms[key] = [item.transform(T) for item in value]
new = type(self)(self.layerdef, geoms)
return new
#Returns the thickness of the laminate
def getLaminateThickness(self):
return self.layerdef.zvalue[self.layerdef.layers[-1]]
def calculateTrueVolume(self):
layerdef = self.layerdef
volume = 0
for layer in layerdef.layers:
shapes = self.geoms[layer]
zvalue = layer.thickness
for shape in shapes:
area = shape.trueArea()
zvalue = zvalue / popupcad.SI_length_scaling
volume += area * zvalue
return volume
#This will calculate the centeroid #REMOVE DEPECRATED CODE
def calculateCentroid(self): #TODO reimplement using .get_center method()
layerdef = self.layerdef
xvalues = []
yvalues = []
zvalues = []
for layer in layerdef.layers:
shapes = self.geoms[layer]
zvalue = layer.thickness / popupcad.SI_length_scaling
for shape in shapes:
tris = shape.triangles3()
for tri in tris:
for point in tri:
#Scales the mesh properly
point = [float(a)/(popupcad.SI_length_scaling) for a in point]
xvalues.append(point[0])
yvalues.append(point[1])
zvalues.append(zvalue)
x = sum(xvalues) / len(xvalues)
y = sum(yvalues) / len(yvalues)
z = sum(zvalues) / len(zvalues)
out = (x, y, z)
return out#[float(a)/popupcad.SI_length_scaling for a in out]
def getDensity(self):
total_densities = sum([layer.density for layer in self.layers()])
return total_densities / len(self.layers())
def toSDFTag(self, tag, name_value):
from lxml import etree
layerdef = self.layerdef
tree_tags = []
scaling_factor = popupcad.SI_length_scaling
counter = 0
for layer in layerdef.layers:
layer_node = etree.Element(tag, name=name_value + "-" + str(counter))
layer_thickness = layer.thickness / scaling_factor
shapes = self.geoms[layer]
zvalue = layerdef.zvalue[layer] / scaling_factor
if (len(shapes) == 0) :
continue
for s in shapes:
center = s.get_center()
etree.SubElement(layer_node, "pose").text = str(center[0]) + " " + str(center[1]) + " " + str(zvalue) + " 0 0 0"
geometry = etree.SubElement(layer_node, "geometry")
line = etree.SubElement(geometry, "polyline")
points = s.exterior_points_from_center()
for point in points:
etree.SubElement(line, "point").text = str(point[0]) + " " + str(point[1])
etree.SubElement(line, "height").text = str(layer_thickness)
tree_tags.append(layer_node)
counter+=1
return tree_tags
#TODO Clean up variable names so it satisifes pylint and whatnot.
#Exports the mesh as an STL files
def toSTL(self):
"""
Exports the current laminate as an STL file
"""
from stl.mesh import Mesh #Requires numpy-stl
layerdef = self.layerdef
laminate_verts = []
for layer in layerdef.layers:
shapes = self.geoms[layer]#TODO Add it in for other shapes
zvalue = layerdef.zvalue[layer]
thickness = layer.thickness
if (len(shapes) == 0) : #In case there are no shapes.
print("No shapes skipping")
continue
for s in shapes:
shape_verts = s.extrudeVertices(thickness, z0=zvalue)
laminate_verts.extend(shape_verts)
laminate_verts = [point/popupcad.SI_length_scaling for point in laminate_verts]
# Or creating a new mesh (make sure not to overwrite the `mesh` import by
# naming it `mesh`):
VERTICE_COUNT = len(laminate_verts)//3 #Number of verticies
data = numpy.zeros(VERTICE_COUNT, dtype=Mesh.dtype) #We create an array full of zeroes. Will edit it later.
#Creates a mesh from the specified set of points
for dtype, points in zip(data, numpy.array(laminate_verts).reshape(-1,9)):
points = points.reshape(-1, 3) #Splits each triangle into points
numpy.copyto(dtype[1], points) #Copies the list of points into verticies index
data = Mesh.remove_duplicate_polygons(data)
#This constructs the mesh objects, generates the normals and all
your_mesh = Mesh(data, remove_empty_areas=True)
filename = str(self.id) + '.stl'
old_path = os.getcwd() #Save old directory
new_path = popupcad.exportdir + os.path.sep #Load export directory
os.chdir(new_path) #Change to export directory
print("Saving in " + str(new_path))
your_mesh.save(filename)#Apparently save does not like absolute paths
print(filename + " has been saved")
os.chdir(old_path) #Change back to old directory
#Allows the laminate to get exported as a DAE.
def toDAE(self):
"""
Exports the current lamiante to a DAE file format
"""
import collada
mesh = collada.Collada()
layerdef = self.layerdef
nodes = [] # Each node of the mesh scene. Typically one per layer.
for layer in layerdef.layers:
layer_thickness = layer.thickness
shapes = self.geoms[layer]
zvalue = layerdef.zvalue[layer]
height = float(zvalue) #* 100 #*
if (len(shapes) == 0) : #In case there are no shapes.
continue
for s in shapes:
geom = self.createDAEFromShape(s, height, mesh, layer_thickness)
mesh.geometries.append(geom)
effect = collada.material.Effect("effect", [], "phone", diffuse=(1,0,0), specular=(0,1,0))
mat = collada.material.Material("material", "mymaterial" + str(s.id), effect)
matnode = collada.scene.MaterialNode("materialref" + str(s.id), mat, inputs=[])
mesh.effects.append(effect)
mesh.materials.append(mat)
geomnode = collada.scene.GeometryNode(geom, [matnode])
node = collada.scene.Node("node" + str(s.id), children=[geomnode])
nodes.append(node)
myscene = collada.scene.Scene("myscene", nodes)
mesh.scenes.append(myscene)
mesh.scene = myscene
filename = popupcad.exportdir + os.path.sep + str(self.id) + '.dae' #
mesh.write(filename)
def createDAEFromShape(self, s, layer_num, mesh, thickness): #TODO Move this method into the shape class.
import collada
vertices = s.extrudeVertices(thickness, z0=layer_num)
#This scales the verticies properly. So that they are in millimeters.
vert_floats = [float(x)/(popupcad.SI_length_scaling) for x in vertices]
vert_src_name = str(self.get_basename()) + '|' + str(s.id) + "-array"
vert_src = collada.source.FloatSource(vert_src_name, numpy.array(vert_floats), ('X', 'Y', 'Z'))
geom = collada.geometry.Geometry(mesh, "geometry-" + str(s.id), str(self.get_basename()), [vert_src])
input_list = collada.source.InputList()
input_list.addInput(0, 'VERTEX', "#" + vert_src_name)
indices = numpy.array(range(0,(len(vertices) // 3)));
triset = geom.createTriangleSet(indices, input_list, "materialref" + str(s.id))
triset.generateNormals()
geom.primitives.append(triset)
return geom
def getBoundingBox(self):
all_shapes = []
layerdef = self.layerdef
for layer in layerdef.layers:
layer_thickness = layer.thickness
shapes = self.geoms[layer]
zvalue = layerdef.zvalue[layer]
height = float(zvalue) #* 100 #* 1/popupcad.internal_argument_scaling
if (len(shapes) == 0) : #In case there are no shapes.
continue
all_shapes.extend(shapes)
all_shapes = [shape.to_shapely() for shape in shapes]
master_shape = all_shapes[0]
for shape in all_shapes[1:]:
master_shape = master_shape.union(shape)
bounds = master_shape.bounds
bounds = [value/popupcad.csg_processing_scaling for value in bounds]
return bounds
def mass_properties(self,length_scaling = 1):
zvalues = self.layerdef.z_values()
volume_total = 0
center_of_mass_accumulator = 0
next_args = []
mass_total = 0
for layer in self.layers():
layer_volume = 0
density = layer.density
z_lower = zvalues[layer]['lower']
z_upper = zvalues[layer]['upper']
for geom in self.geoms[layer]:
area,centroid,volume,mass,tris = geom.mass_properties(density,z_lower,z_upper,length_scaling)
volume_total+=volume
layer_volume+=volume
center_of_mass_accumulator+=volume*centroid*density
next_args.append((geom,(density,z_lower,z_upper,tris)))
mass_total+=layer_volume*density
center_of_mass = center_of_mass_accumulator/mass_total
I = 0
for geom,args in next_args:
I+=geom.inertia_tensor(center_of_mass,*args)
return volume_total,mass_total,center_of_mass,I
def all_geoms(self):
allgeoms = []
for layer in self.layerdef.layers:
allgeoms.extend(self.geoms[layer])
return allgeoms
def __lt__(self,other):
return self.all_geoms()[0]<other.all_geoms()[1]
| |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Factories that create entities."""
# pylint: disable=too-many-arguments
# pylint: disable=invalid-name
# pylint: disable=redefined-builtin
import copy
import random
import re
from lib.constants import element, objects, roles, url as const_url
from lib.constants.element import AdminWidgetCustomAttrs
from lib.entities import entity
from lib.utils import string_utils
from lib.utils.string_utils import (random_list_strings, random_string,
random_uuid)
class EntitiesFactory(object):
"""Common factory class for entities."""
# pylint: disable=too-few-public-methods
obj_person = objects.get_singular(objects.PEOPLE)
obj_program = objects.get_singular(objects.PROGRAMS)
obj_control = objects.get_singular(objects.CONTROLS)
obj_audit = objects.get_singular(objects.AUDITS)
obj_asmt_tmpl = objects.get_singular(objects.ASSESSMENT_TEMPLATES)
obj_asmt = objects.get_singular(objects.ASSESSMENTS)
obj_issue = objects.get_singular(objects.ISSUES)
all_objs_attrs_names = tuple(entity.Entity().attrs_names_all_entities())
@classmethod
def update_obj_attrs_values(cls, obj, attrs_names=all_objs_attrs_names,
**arguments):
"""Update object's (obj) attributes values according to list of
unique possible objects' names and dictionary of arguments (key = value).
"""
# pylint: disable=expression-not-assigned
[setattr(obj, attr_name, arguments[attr_name]) for
attr_name in attrs_names if arguments.get(attr_name)]
return obj
@classmethod
def generate_title(cls, obj_type):
"""Generate title according object type and random data."""
special_chars = string_utils.SPECIAL
return "{obj_type}_{uuid}_{rand_str}".format(
obj_type=obj_type, uuid=random_uuid(),
rand_str=random_string(size=len(special_chars), chars=special_chars))
@classmethod
def generate_code(cls):
"""Generate code according str part and random data."""
return "{code}".format(code=random_uuid())
@classmethod
def generate_email(cls, domain=const_url.DEFAULT_EMAIL_DOMAIN):
"""Generate email according domain."""
return "{mail_name}@{domain}".format(
mail_name=random_uuid(), domain=domain)
class PersonsFactory(EntitiesFactory):
"""Factory class for Persons entities."""
@classmethod
def default(cls):
"""Create default system Person object."""
return cls.create(
title=roles.DEFAULT_USER, id=1, href=const_url.DEFAULT_USER_HREF,
email=const_url.DEFAULT_USER_EMAIL, authorizations=roles.SUPERUSER)
@classmethod
def create(cls, title=None, id=None, href=None, url=None, type=None,
email=None, authorizations=None):
"""Create Person object.
Random values will be used for title aka name.
Predictable values will be used for mail and system_wide_role.
"""
person_entity = cls._create_random_person()
person_entity = cls.update_obj_attrs_values(
obj=person_entity, title=title, id=id, href=href, url=url, type=type,
email=email, authorizations=authorizations)
return person_entity
@classmethod
def _create_random_person(cls):
"""Create Person entity with randomly filled fields."""
random_person = entity.PersonEntity()
random_person.title = cls.generate_title(cls.obj_person)
random_person.type = cls.obj_person
random_person.email = cls.generate_email()
random_person.authorizations = roles.NO_ROLE
return random_person
class CAFactory(EntitiesFactory):
"""Factory class for Custom Attributes entities."""
@classmethod
def create(cls, title=None, ca_type=None, definition_type=None, helptext="",
placeholder=None, multi_choice_options=None, is_mandatory=False,
ca_global=True):
"""Create CustomAttribute object.
Random values will be used for title, ca_type, definition_type and
multi_choice_options if they are None.
"""
ca_entity = cls._create_random_ca()
ca_entity = cls._fill_ca_entity_fields(
ca_entity, title=title,
ca_type=ca_type, definition_type=definition_type, helptext=helptext,
placeholder=placeholder, multi_choice_options=multi_choice_options,
is_mandatory=is_mandatory, ca_global=ca_global)
ca_entity = cls._normalize_ca_definition_type(ca_entity)
return ca_entity
@classmethod
def _create_random_ca(cls):
"""Create CustomAttribute entity with randomly filled fields."""
random_ca = entity.CustomAttributeEntity()
random_ca.ca_type = random.choice(AdminWidgetCustomAttrs.ALL_ATTRS_TYPES)
random_ca.title = cls.generate_title(random_ca.ca_type)
random_ca.definition_type = random.choice(objects.ALL_CA_OBJECTS)
return random_ca
@classmethod
def _fill_ca_entity_fields(cls, ca_object, **ca_object_fields):
"""Set CustomAttributes object's attributes."""
if ca_object_fields.get("ca_type"):
ca_object.ca_type = ca_object_fields["ca_type"]
ca_object.title = cls.generate_title(ca_object.ca_type)
if ca_object_fields.get("definition_type"):
ca_object.definition_type = ca_object_fields["definition_type"]
if ca_object_fields.get("title"):
ca_object.title = ca_object_fields["definition_type"]
# "Placeholder" field exists only for Text and Rich Text.
if (ca_object_fields.get("placeholder") and
ca_object.ca_type in (AdminWidgetCustomAttrs.TEXT,
AdminWidgetCustomAttrs.RICH_TEXT)):
ca_object.placeholder = ca_object_fields["placeholder"]
if ca_object_fields.get("helptext"):
ca_object.helptext = ca_object_fields["helptext"]
if ca_object_fields.get("is_mandatory"):
ca_object.is_mandatory = ca_object_fields["is_mandatory"]
if ca_object_fields.get("ca_global"):
ca_object.ca_global = ca_object_fields["ca_global"]
# "Possible Values" - is a mandatory field for dropdown CustomAttribute.
if ca_object.ca_type == AdminWidgetCustomAttrs.DROPDOWN:
if (ca_object_fields.get("multi_choice_options") and
ca_object_fields["multi_choice_options"] is not None):
ca_object.multi_choice_options =\
ca_object_fields["multi_choice_options"]
else:
ca_object.multi_choice_options = random_list_strings(list_len=3)
return ca_object
@classmethod
def _normalize_ca_definition_type(cls, ca_object):
"""Transform definition type to title form.
Title from used for UI operations.
For REST operations definition type should be interpreted as
objects.get_singular().get_object_name_form().
"""
ca_object.definition_type = objects.get_normal_form(
ca_object.definition_type
)
return ca_object
class ProgramsFactory(EntitiesFactory):
"""Factory class for Programs entities."""
@classmethod
def create_empty(cls):
"""Create blank Program object."""
empty_program = entity.ProgramEntity()
empty_program.type = cls.obj_program
return empty_program
@classmethod
def create(cls, title=None, id=None, href=None, url=None, type=None,
manager=None, primary_contact=None, code=None, state=None,
last_update=None):
"""Create Program object.
Random values will be used for title and code.
Predictable values will be used for type, manager, primary_contact, state.
"""
program_entity = cls._create_random_program()
program_entity = cls.update_obj_attrs_values(
obj=program_entity, title=title, id=id, href=href, url=url, type=type,
manager=manager, primary_contact=primary_contact, code=code,
state=state, last_update=last_update)
return program_entity
@classmethod
def _create_random_program(cls):
"""Create Program entity with randomly and predictably filled fields."""
random_program = entity.ProgramEntity()
random_program.title = cls.generate_title(cls.obj_program)
random_program.type = cls.obj_program
random_program.code = cls.generate_code()
random_program.manager = roles.DEFAULT_USER
random_program.primary_contact = roles.DEFAULT_USER
random_program.state = element.ObjectStates.DRAFT
return random_program
class ControlsFactory(EntitiesFactory):
"""Factory class for Controls entities."""
@classmethod
def create_empty(cls):
"""Create blank Control object."""
empty_control = entity.ControlEntity()
empty_control.type = cls.obj_control
return empty_control
@classmethod
def create(cls, title=None, id=None, href=None, url=None, type=None,
owner=None, primary_contact=None, code=None, state=None,
last_update=None):
"""Create Control object.
Random values will be used for title and code.
Predictable values will be used for type, owner, primary_contact, state.
"""
control_entity = cls._create_random_control()
control_entity = cls.update_obj_attrs_values(
obj=control_entity, title=title, id=id, href=href, url=url, type=type,
owner=owner, primary_contact=primary_contact, code=code, state=state,
last_update=last_update)
return control_entity
@classmethod
def _create_random_control(cls):
"""Create Control entity with randomly and predictably filled fields."""
random_control = entity.ControlEntity()
random_control.title = cls.generate_title(cls.obj_control)
random_control.type = cls.obj_control
random_control.code = cls.generate_code()
random_control.owner = roles.DEFAULT_USER
random_control.primary_contact = roles.DEFAULT_USER
random_control.state = element.ObjectStates.DRAFT
return random_control
class AuditsFactory(EntitiesFactory):
"""Factory class for Audit entity."""
@classmethod
def clone(cls, audit, count_to_clone=1):
"""Clone Audit object.
Predictable values will be used for title, id, href, url, code.
"""
# pylint: disable=anomalous-backslash-in-string
from lib.service.rest_service import ObjectsInfoService
actual_count_all_audits = ObjectsInfoService().get_total_count(
obj_name=objects.get_normal_form(cls.obj_audit, with_space=False))
if actual_count_all_audits == audit.id:
return [
cls.update_obj_attrs_values(
obj=copy.deepcopy(audit),
title=audit.title + " - copy " + str(num), id=audit.id + num,
href=re.sub("\d+$", str(audit.id + num), audit.href),
url=re.sub("\d+$", str(audit.id + num), audit.url),
code=(cls.obj_audit.upper() + "-" + str(audit.id + num))) for
num in xrange(1, count_to_clone + 1)]
@classmethod
def create_empty(cls):
"""Create blank Audit object."""
empty_audit = entity.AuditEntity()
empty_audit.type = cls.obj_audit
return empty_audit
@classmethod
def create(cls, title=None, id=None, href=None, url=None, type=None,
program=None, audit_lead=None, code=None, status=None,
last_update=None):
"""Create Audit object.
Random values will be used for title and code.
Predictable values will be used for type, audit_lead, status.
"""
audit_entity = cls._create_random_audit()
audit_entity = cls.update_obj_attrs_values(
obj=audit_entity, title=title, id=id, href=href, url=url, type=type,
program=program, audit_lead=audit_lead, code=code, status=status,
last_update=last_update)
return audit_entity
@classmethod
def _create_random_audit(cls):
"""Create Audit entity with randomly and predictably filled fields."""
random_audit = entity.AuditEntity()
random_audit.title = cls.generate_title(cls.obj_audit)
random_audit.type = cls.obj_audit
random_audit.code = cls.generate_code()
random_audit.audit_lead = roles.DEFAULT_USER
random_audit.status = element.AuditStates().PLANNED
return random_audit
class AssessmentTemplatesFactory(EntitiesFactory):
"""Factory class for Assessment Templates entities."""
@classmethod
def clone(cls, asmt_tmpl, count_to_clone=1):
"""Clone Assessment Template object.
Predictable values will be used for title, id, href, url, code.
"""
# pylint: disable=anomalous-backslash-in-string
from lib.service.rest_service import ObjectsInfoService
actual_count_all_asmt_tmpls = ObjectsInfoService().get_total_count(
obj_name=objects.get_normal_form(cls.obj_asmt_tmpl, with_space=False))
if actual_count_all_asmt_tmpls == asmt_tmpl.id:
return [
cls.update_obj_attrs_values(
obj=copy.deepcopy(asmt_tmpl), id=asmt_tmpl.id + num,
href=re.sub("\d+$", str(asmt_tmpl.id + num), asmt_tmpl.href),
url=re.sub("\d+$", str(asmt_tmpl.id + num), asmt_tmpl.url),
code=("TEMPLATE-" + str(asmt_tmpl.id + num))) for
num in xrange(1, count_to_clone + 1)]
@classmethod
def create_empty(cls):
"""Create blank Assessment Template object."""
empty_asmt_tmpl = entity.AssessmentTemplateEntity()
empty_asmt_tmpl.type = cls.obj_asmt_tmpl
return empty_asmt_tmpl
@classmethod
def create(cls, title=None, id=None, href=None, url=None, type=None,
audit=None, asmt_objects=None, def_assessors=None,
def_verifiers=None, code=None, last_update=None):
"""Create Assessment Template object.
Random values will be used for title and code.
Predictable values will be used for type, asmt_objects, def_assessors,
def_verifiers.
"""
asmt_tmpl_entity = cls._create_random_asmt_tmpl()
asmt_tmpl_entity = cls.update_obj_attrs_values(
obj=asmt_tmpl_entity, title=title, id=id, href=href, url=url,
type=type, audit=audit, asmt_objects=asmt_objects,
def_assessors=def_assessors, def_verifiers=def_verifiers, code=code,
last_update=last_update)
return asmt_tmpl_entity
@classmethod
def _create_random_asmt_tmpl(cls):
"""Create Assessment Template entity with randomly and predictably
filled fields.
"""
random_asmt_tmpl = entity.AssessmentTemplateEntity()
random_asmt_tmpl.title = cls.generate_title(cls.obj_asmt_tmpl)
random_asmt_tmpl.type = cls.obj_asmt_tmpl
random_asmt_tmpl.code = cls.generate_code()
random_asmt_tmpl.asmt_objects = objects.CONTROLS
random_asmt_tmpl.def_assessors = roles.OBJECT_OWNERS
random_asmt_tmpl.def_verifiers = roles.OBJECT_OWNERS
return random_asmt_tmpl
class AssessmentsFactory(EntitiesFactory):
"""Factory class for Assessments entities."""
@classmethod
def generate(cls, objs_under_asmt_tmpl, audit):
"""Generate Assessment object.
Predictable values will be used for title, code, audit.
"""
# pylint: disable=too-many-locals
from lib.service.rest_service import ObjectsInfoService
actual_count_all_asmts = ObjectsInfoService().get_total_count(
obj_name=objects.get_normal_form(cls.obj_asmt, with_space=False))
return [
cls.create(
title=obj_under_asmt_tmpl.title + " assessment for " + audit.title,
code=(cls.obj_asmt.upper() + "-" + str(asmt_number)),
audit=audit.title) for asmt_number, obj_under_asmt_tmpl in
enumerate(objs_under_asmt_tmpl, start=actual_count_all_asmts + 1)]
@classmethod
def create_empty(cls):
"""Create blank Assessment object."""
empty_asmt = entity.AssessmentEntity()
empty_asmt.type = cls.obj_asmt
return empty_asmt
@classmethod
def create(cls, title=None, id=None, href=None, url=None, type=None,
object=None, audit=None, creators=None, assignees=None,
primary_contact=None, is_verified=None, code=None, state=None,
last_update=None):
"""Create Assessment object.
Random values will be used for title and code.
Predictable values will be used for type, object, creators, assignees,
state, is_verified.
"""
# pylint: disable=too-many-locals
asmt_entity = cls._create_random_asmt()
asmt_entity = cls.update_obj_attrs_values(
obj=asmt_entity, title=title, id=id, href=href, url=url, type=type,
object=object, audit=audit, creators=creators, assignees=assignees,
primary_contact=primary_contact, is_verified=is_verified, code=code,
state=state, last_update=last_update)
return asmt_entity
@classmethod
def _create_random_asmt(cls):
"""Create Assessment entity with randomly and predictably filled fields."""
random_asmt = entity.AssessmentEntity()
random_asmt.title = cls.generate_title(cls.obj_asmt)
random_asmt.type = cls.obj_asmt
random_asmt.code = cls.generate_code()
random_asmt.object = roles.DEFAULT_USER
random_asmt.creators = roles.DEFAULT_USER
random_asmt.assignees = roles.DEFAULT_USER
random_asmt.state = element.AssessmentStates.NOT_STARTED
random_asmt.is_verified = element.Common.FALSE
return random_asmt
class IssuesFactory(EntitiesFactory):
"""Factory class for Issues entities."""
@classmethod
def create_empty(cls):
"""Create blank Issue object."""
empty_issue = entity.IssueEntity
empty_issue.type = cls.obj_issue
return empty_issue
@classmethod
def create(cls, title=None, id=None, href=None, url=None, type=None,
audit=None, owner=None, primary_contact=None, code=None,
state=None, last_update=None):
"""Create Issue object.
Random values will be used for title and code.
Predictable values will be used for type, owner, primary_contact, state.
"""
issue_entity = cls._create_random_issue()
issue_entity = cls.update_obj_attrs_values(
obj=issue_entity, title=title, id=id, href=href, url=url, type=type,
audit=audit, owner=owner, primary_contact=primary_contact, code=code,
state=state, last_update=last_update)
return issue_entity
@classmethod
def _create_random_issue(cls):
"""Create Issue entity with randomly and predictably filled fields."""
random_issue = entity.IssueEntity()
random_issue.title = cls.generate_title(cls.obj_issue)
random_issue.type = cls.obj_issue
random_issue.code = cls.generate_code()
random_issue.owner = roles.DEFAULT_USER
random_issue.primary_contact = roles.DEFAULT_USER
random_issue.state = element.IssueStates.DRAFT
return random_issue
| |
# -*- coding: utf-8 -*-
"""
Dynamic DynamoDB
Auto provisioning functionality for Amazon Web Service DynamoDB tables.
APACHE LICENSE 2.0
Copyright 2013-2014 Sebastian Dahlgren
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 re
import sys
import time
from boto.exception import JSONResponseError, BotoServerError
from dynamic_dynamodb.aws import dynamodb
from dynamic_dynamodb.core import gsi, table
from dynamic_dynamodb.daemon import Daemon
from dynamic_dynamodb.config_handler import get_global_option, get_table_option
from dynamic_dynamodb.log_handler import LOGGER as logger
CHECK_STATUS = {
'tables': {},
'gsis': {}
}
class DynamicDynamoDBDaemon(Daemon):
""" Daemon for Dynamic DynamoDB"""
def run(self):
""" Run the daemon
:type check_interval: int
:param check_interval: Delay in seconds between checks
"""
try:
while True:
execute()
except Exception as error:
logger.exception(error)
def main():
""" Main function called from dynamic-dynamodb """
try:
if get_global_option('daemon'):
daemon = DynamicDynamoDBDaemon(
'{0}/dynamic-dynamodb.{1}.pid'.format(
get_global_option('pid_file_dir'),
get_global_option('instance')))
if get_global_option('daemon') == 'start':
logger.debug('Starting daemon')
try:
daemon.start()
logger.info('Daemon started')
except IOError as error:
logger.error('Could not create pid file: {0}'.format(error))
logger.error('Daemon not started')
elif get_global_option('daemon') == 'stop':
logger.debug('Stopping daemon')
daemon.stop()
logger.info('Daemon stopped')
sys.exit(0)
elif get_global_option('daemon') == 'restart':
logger.debug('Restarting daemon')
daemon.restart()
logger.info('Daemon restarted')
elif get_global_option('daemon') in ['foreground', 'fg']:
logger.debug('Starting daemon in foreground')
daemon.run()
logger.info('Daemon started in foreground')
else:
print(
'Valid options for --daemon are start, '
'stop, restart, and foreground')
sys.exit(1)
else:
if get_global_option('run_once'):
execute()
else:
while True:
execute()
except Exception as error:
logger.exception(error)
def execute():
""" Ensure provisioning """
boto_server_error_retries = 3
# Ensure provisioning
for table_name, table_key in sorted(dynamodb.get_tables_and_gsis()):
try:
table_num_consec_read_checks = \
CHECK_STATUS['tables'][table_name]['reads']
except KeyError:
table_num_consec_read_checks = 0
try:
table_num_consec_write_checks = \
CHECK_STATUS['tables'][table_name]['writes']
except KeyError:
table_num_consec_write_checks = 0
try:
# The return var shows how many times the scale-down criteria
# has been met. This is coupled with a var in config,
# "num_intervals_scale_down", to delay the scale-down
table_num_consec_read_checks, table_num_consec_write_checks = \
table.ensure_provisioning(
table_name,
table_key,
table_num_consec_read_checks,
table_num_consec_write_checks)
CHECK_STATUS['tables'][table_name] = {
'reads': table_num_consec_read_checks,
'writes': table_num_consec_write_checks
}
gsi_names = set()
# Add regexp table names
for gst_instance in dynamodb.table_gsis(table_name):
gsi_name = gst_instance['IndexName']
try:
gsi_keys = get_table_option(table_key, 'gsis').keys()
except AttributeError:
# Continue if there are not GSIs configured
continue
for gsi_key in gsi_keys:
try:
if re.match(gsi_key, gsi_name):
logger.debug(
'Table {0} GSI {1} matches '
'GSI config key {2}'.format(
table_name, gsi_name, gsi_key))
gsi_names.add((gsi_name, gsi_key))
except re.error:
logger.error('Invalid regular expression: "{0}"'.format(
gsi_key))
sys.exit(1)
for gsi_name, gsi_key in sorted(gsi_names):
try:
gsi_num_consec_read_checks = \
CHECK_STATUS['tables'][table_name]['reads']
except KeyError:
gsi_num_consec_read_checks = 0
try:
gsi_num_consec_write_checks = \
CHECK_STATUS['tables'][table_name]['writes']
except KeyError:
gsi_num_consec_write_checks = 0
gsi_num_consec_read_checks, gsi_num_consec_write_checks = \
gsi.ensure_provisioning(
table_name,
table_key,
gsi_name,
gsi_key,
gsi_num_consec_read_checks,
gsi_num_consec_write_checks)
CHECK_STATUS['gsis'][gsi_name] = {
'reads': gsi_num_consec_read_checks,
'writes': gsi_num_consec_write_checks
}
except JSONResponseError as error:
exception = error.body['__type'].split('#')[1]
if exception == 'ResourceNotFoundException':
logger.error('{0} - Table {1} does not exist anymore'.format(
table_name,
table_name))
continue
except BotoServerError as error:
if boto_server_error_retries > 0:
logger.error(
'Unknown boto error. Status: "{0}". '
'Reason: "{1}". Message: {2}'.format(
error.status,
error.reason,
error.message))
logger.error(
'Please bug report if this error persists')
boto_server_error_retries -= 1
continue
else:
raise
# Sleep between the checks
if not get_global_option('run_once'):
logger.debug('Sleeping {0} seconds until next check'.format(
get_global_option('check_interval')))
time.sleep(get_global_option('check_interval'))
| |
# Create your views here.
from uuid import uuid4
import logging
import json
import zipfile
import os
import csv
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse, reverse_lazy
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response, redirect
from django.template import RequestContext
from django.views.generic.edit import CreateView, UpdateView
from django.views.generic.list import ListView
from django.contrib import messages
from django.views.generic.base import TemplateView
import requests
from requests.auth import HTTPBasicAuth
from django.http.response import Http404, HttpResponse
from rest_framework.authtoken.models import Token
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from general.models import Process, Task, Reward, Application, TaskInstance
from general.tasks import signal
from general.utils import startTask, createObject, forceFinish, startProcess, checkIfProcessFinished, \
forceProcessFinish
from requester.forms import ProcessForm, HumanTaskForm, MachineTaskForm, \
ValidationForm # , SplitDataTaskForm,FilterDataTaskForm
from requester.forms import UploadFileForm
from crowdcomputer import settings
log = logging.getLogger(__name__)
class TaskCreationHub(TemplateView):
template_name = "requester/task_creation_hub.html"
def get_context_data(self, **kwargs):
contex_data = TemplateView.get_context_data(self, **kwargs)
process = get_object_or_404(Process, pk=self.kwargs['process_id'], owner=self.request.user)
contex_data['process'] = process;
return contex_data
# @login_required
# def ProcessList(request):
# process_list = Process.objects.filter(user=request.user).order_by('date_created')
# return render_to_response('requester/process_list.html', {'process_list':process_list}, context_instance=RequestContext(request))
class ProcessList(ListView):
template_name = 'requester/process_list.html'
paginate_by = 10
def get_queryset(self, **kwargs):
process_list = Process.objects.filter(owner=self.request.user).filter(validates=None).order_by('-pk')
# .order_by('-status')
# process_list = sorted(process_list, key=lambda a: a.int_status)
return process_list
class TaskList(ListView):
# FIXME: do we need to call trigger task function?
# if so then extend render_to_response and add the function there.
template_name = 'requester/task_list.html'
paginate_by = 10
def get_queryset(self):
process = get_object_or_404(Process, pk=self.kwargs['process_id'], owner=self.request.user)
task_list = Task.objects.filter(owner=self.request.user, process=process).order_by('date_deadline')
# FIXME
# task_list = sorted(task_list, key=lambda a: a.int_status)
# task_list=process.task_set.all()
checkIfProcessFinished(process)
return task_list
def get_context_data(self, **kwargs):
contex_data = ListView.get_context_data(self, **kwargs)
process = get_object_or_404(Process, pk=self.kwargs['process_id'], owner=self.request.user)
contex_data['process'] = process;
# if process.validates:
# contex_data['prev_process_id'] = process.validates.task.process.pk
# contex_data['prev_task_id'] = process.validates.task.pk
# # check if it's bpmn providded and put th epicutre here
# bpmnprocess = process.processactiviti
# if bpmnprocess is not None:
# contex_data['picture']='ciao'
return contex_data
# def TaskList(request, process_id):
# #retrive list or 404, then short it
# # cant' use get_list_or_404 because at the first time list is empty!
# # task_list = get_list_or_404(Task,user=request.user).order_by('date_deadline')
# process = get_object_or_404(Process, pk=process_id, user=request.user)
# task_list = Task.objects.filter(user=request.user,process=process).order_by('date_deadline')
# task_list = sorted(task_list, key=lambda a: a.int_status)
#
# #stop_expired(task_list)
# #we can not just stop tasks, we should check if we should run other tasks, so we use trigger
# triggerTasks(process)
# return render_to_response('requester/task_list.html', {'task_list':task_list,'process':process}, context_instance=RequestContext(request))
# return render_to_response('requester/task_list.html', {'task_list':task_list, 'process_id':process_id}, context_instance=RequestContext(request))
# @login_required
# def ProcessCreation(request):
# if request.method == 'POST':
# form = ProcessForm(request.POST, user=request.user)
# if form.is_valid():
# #create a task
# process = Process(user_id=request.user.id,
# title=form.cleaned_data['title'],
# description=form.cleaned_data['description']
# )
# process.save()
# return redirect(ProcessList)
# else:
# #form error
# return render_to_response('requester/creation.html', {'form':form}, context_instance=RequestContext(request))
# else:
# #create form
# form = ProcessForm(None ,user=request.user)
# return render_to_response('requester/creation.html', {'form':form}, context_instance=RequestContext(request))
class ProcessCreation(CreateView):
template_name = 'requester/creation.html'
form_class = ProcessForm
success_url = reverse_lazy('r-process')
def get_initial(self):
initial = {}
initial['owner'] = self.request.user
app = Application.objects.get(name='crowdcomputer')
initial['application'] = app
return initial
# DOES NOT WORK
# the urls was wrong, this misses the model, get_queryset
class ProcessUpdate(UpdateView):
template_name = 'requester/creation.html'
form_class = ProcessForm
success_url = reverse_lazy('r-process')
model = Process
def get_initial(self):
initial = {}
initial['user'] = self.request.user
return initial
def get_queryset(self):
qs = super(ProcessUpdate, self).get_queryset()
return qs.filter(user=self.request.user)
@login_required
def ProcessDelete(request, process_id):
# this actually set the status to delete
# template = get_object_or_404(Template,pk=template_id,user=request.user)
# task=get_object_or_404(Task,pk=task_id, template=template)
# task.delete()
process = get_object_or_404(Process, pk=process_id, owner=request.user)
process.status = "DL"
process.save()
if process.processactiviti:
if settings.CELERY:
deleteInstance.delay(process)
else:
deleteInstance(process)
# if process.processactiviti:
# process.processactiviti.deplyment_id
# repository/deployments/
# redirect to the view, don't put logic if it's already implemented
return redirect(reverse('r-process'))
class HumanTaskCreation(CreateView):
template_name = 'requester/creation.html'
form_class = HumanTaskForm
def get_initial(self):
process = get_object_or_404(Process, pk=self.kwargs['process_id'], owner=self.request.user)
initial = {}
initial['process'] = process
initial['owner'] = self.request.user
return initial
def get_success_url(self):
return reverse('r-task-list', args=(self.kwargs['process_id'],))
def form_invalid(self, form):
log.debug("form is not valid")
log.debug(form.errors)
return CreateView.form_invalid(self, form)
def form_valid(self, form):
rew = Reward(type=form['type'].value(), quantity=form['quantity'].value())
rew.save()
task = form.save()
task.reward = rew
task.uuid = uuid4()
task.save()
log.debug("saved")
return HttpResponseRedirect(self.get_success_url())
class MachineTaskCreation(CreateView):
template_name = 'requester/creation.html'
form_class = MachineTaskForm
def get_initial(self):
process = get_object_or_404(Process, pk=self.kwargs['process_id'], owner=self.request.user)
initial = {}
initial['process'] = process
initial['owner'] = self.request.user
return initial
def get_success_url(self):
return reverse('r-task-list', args=(self.kwargs['process_id'],))
'''class SplitDataTaskCreation(CreateView):
template_name = 'requester/creation.html'
form_class = SplitDataTaskForm
def get_initial(self):
process = get_object_or_404(Process, pk=self.kwargs['process_id'], owner=self.request.user)
initial = {}
initial['process']=process
initial['owner']=self.request.user
return initial
def get_success_url(self):
return reverse('r-task-list',args=(self.kwargs['process_id'],))
class FilterDataTaskCreation(CreateView):
template_name = 'requester/creation.html'
form_class = FilterDataTaskForm
def get_initial(self):
process = get_object_or_404(Process, pk=self.kwargs['process_id'], owner=self.request.user)
initial = {}
initial['process']=process
initial['owner']=self.request.user
return initial
def get_success_url(self):
return reverse('r-task-list',args=(self.kwargs['process_id'],))
# def save(self):
# reward_form = RewardForm(self.request.POST)
# htform = HumanTaskForm(self.request.POST)
# reward = reward_form.save();
# ht=htform.save(commit=False);
# ht.reward=reward
# ht.uuid=uuid4()
# ht.save()
# log.debug('saved')
# return ht
'''
# class TaskCreation(CreateView):
# template_name = 'requester/creation.html'
# form_class = TaskForm
#
#
# def get_initial(self):
# process = get_object_or_404(Process, pk=self.kwargs['process_id'], owner=self.request.user)
# initial = {}
# initial['process']=process
# initial['owner']=self.request.user
# return initial
#
# def get_success_url(self):
# return reverse('r-task-list',args=(self.kwargs['process_id'],))
#
# def form_valid(self, form):
# # log.debug("type %s",form['reward_type'].value())
# rew = Reward(type=form['reward_type'].value(),quantity=form['reward_quantity'].value())
# rew.save()
# task = form.save()
# task.reward=rew
# task.uuid = uuid4()
# # crete the reward
# task.save()
# log.debug("saved")
# # check if superuser
# if task.isMturk:
# if self.request.user.is_superuser:
# mturkTask(task,form['reward_mturk'].value())
# else:
# messages.warning(self.request, 'You don\'t have grants to create tasks on AMT')
# return HttpResponseRedirect(self.get_success_url())
#
# @login_required
# def TaskCreation(request, process_id):
# process = get_object_or_404(Process, pk=process_id, user=request.user)
# if request.method == 'POST':
# form = TaskForm(request.POST, user=request.user)
# if form.is_valid():
# #create a task
# task = Task(user_id=request.user.id,
# title=form.cleaned_data['title'],
# description=form.cleaned_data['description'],
# process=process,
# input_url=form.cleaned_data['input_url'],
# input_task=form.cleaned_data['input_task'],
# redirect=form.cleaned_data['redirect'],
# instances_required=form.cleaned_data['instances_required'],
# date_deadline=form.cleaned_data['date_deadline'],
# uuid=uuid4())
# task.save()
# return redirect(TaskList)
# else:
# #form error
# return render_to_response('requester/creation.html', {'form':form}, context_instance=RequestContext(request))
# else:
# #create form
# form = TaskForm(None ,user=request.user)
# return render_to_response('requester/creation.html', {'form':form}, context_instance=RequestContext(request))
# @login_required
# def TaskDuplicate(request, task_id):
# task = get_object_or_404(Task, pk=task_id, user=request.user)
# task.pk = None
# task.uuid = uuid4()
# task.save()
# task.stop()
# return redirect(TaskList)
# This class does not work properly (does not save). I did not get how does it work.
# Not sure that it filter by user, because, i tryied to put there anything- the same result
# there's no checking of the fact that processs and tasks should be corrleated. you can put every process id on the top.
# FIXME: implement it, for all the cases code is below.
class TaskUpdate(UpdateView):
pass
# template_name = 'requester/creation.html'
# form_class = TaskForm
# model = Task
#
# def get_form(self, form_class):
# form = UpdateView.get_form(self, form_class)
# task=get_object_or_404(Task,process_id__exact=self.kwargs['process_id'],id=self.kwargs['pk'])
# form.fields['input_task'].queryset=Task.objects.filter(user=self.request.user).filter(process_id__exact=self.kwargs['process_id']).filter(~Q(id=self.kwargs['pk']))
# if task.reward:
# form.fields['reward_type'].initial=task.reward.type
# form.fields['reward_quantity'].initial=task.reward.quantity
# return form
#
#
# # def form_valid(self, form):
# # return UpdateView.form_valid(self, form)
# def form_valid(self, form):
# task = form.save()
# # log.debug("reward %s",form['reward'])
# rew = task.reward
# rew.type =form['reward_type'].value()
# rew.quantity=form['reward_quantity'].value()
# rew.save()
# return HttpResponseRedirect(self.get_success_url())
#
# def get_initial(self):
# initial = {}
# initial['user']=self.request.user
# return initial
#
# def get_queryset(self):
# qs = super(TaskUpdate, self).get_queryset()
# return qs.filter(user=self.request.user)
#
# def get_success_url(self):
# log.debug("process id %s "%self.kwargs['process_id'])
# return reverse_lazy('r-task-list',args=(int(self.kwargs['process_id']),))
# @login_required
# def TaskUpdate(request, task_id):
# task = get_object_or_404(Task, pk=task_id, user=request.user)
# form = TaskForm(request.POST or None, instance=task, user=request.user)
# if request.method == 'POST':
# if form.is_valid():
# form.save()
# return redirect(TaskList)
# return render_to_response('requester/task.html', {'form':form}, context_instance=RequestContext(request))
@login_required
def TaskDelete(request, task_id, process_id):
pass
# this actually set the status to delete
# template = get_object_or_404(Template,pk=template_id,user=request.user)
# task=get_object_or_404(Task,pk=task_id, template=template)
# task.delete()
task = get_object_or_404(Task, pk=task_id, owner=request.user)
task.delete()
# redirect to the view, don't put logic if it's already implemented
return redirect(reverse('r-task-list', kwargs={'process_id': process_id}))
@login_required
def ProcessStart(request, process_id):
pass
@login_required
def ProcessStop(request, process_id):
process = get_object_or_404(Process, pk=process_id, owner=request.user)
if request.method == 'POST':
# start and stop
# log.critical('startTask has to be fixed')
forceProcessFinish(process)
# redirect to the view, don't put logic if it's already implemented
return redirect(reverse('r-process'))
else:
return render_to_response('requester/confirm.html', {'process': process},
context_instance=RequestContext(request))
# #start and stop
# process = get_object_or_404(Process, pk=process_id, user=request.user)
# if process.is_inprocess:
# stopProcess(process)
# else:
# if process.is_stopped:
# startProcess(process)
# # startTask(task)
# #redirect to the view, don't put logic if it's already implemented
# return redirect(reverse('r-task-list',kwargs={'process_id': process_id}))
@login_required
def TaskStop(request, task_id, process_id):
task = get_object_or_404(Task, pk=task_id)
if request.method == 'POST':
# start and stop
# log.critical('startTask has to be fixed')
forceFinish(task)
# redirect to the view, don't put logic if it's already implemented
return redirect(reverse('r-task-list', kwargs={'process_id': process_id}))
else:
return render_to_response('requester/confirm.html', {'task': task}, context_instance=RequestContext(request))
@login_required
def TaskStartStop(request, task_id, process_id):
log.warn("don't use me, i'm here just for testing")
# start and stop
task = get_object_or_404(Task, pk=task_id)
# log.critical('startTask has to be fixed')
startTask(task)
# redirect to the view, don't put logic if it's already implemented
return redirect(reverse('r-task-list', kwargs={'process_id': process_id}))
@login_required
def TaskFinish(request, task_id, process_id):
task = get_object_or_404(Task, pk=task_id, user=request.user)
if task.is_inprocess:
task.finish()
# triggerTasks(task.process)
return redirect(reverse('r-task-list', kwargs={'process_id': process_id}))
class TaskInstanceList(ListView):
paginate_by = 10
template_name = 'requester/taskinstance_list.html'
def get_queryset(self):
task = get_object_or_404(Task, pk=self.kwargs['task_id'], owner=self.request.user)
tl = task.taskinstance_set.all()
checkIfProcessFinished(task.process)
return tl
def get_context_data(self, **kwargs):
contex_data = ListView.get_context_data(self, **kwargs)
task = get_object_or_404(Task, pk=self.kwargs['task_id'], owner=self.request.user)
contex_data['task'] = task
# if task.process.title.startswith("[V]"):
# id_process = task.process.title.lstrip("[V] Validation for ")
# process = get_object_or_404(Process, pk=self.kwargs['process_id'], owner=self.request.user)
#
# contex_data['process'] = task
# else:
process = get_object_or_404(Process, pk=self.kwargs['process_id'], owner=self.request.user)
contex_data['process'] = process
return contex_data
# task_list = Task.objects.filter(owner=self.request.user,process=process).order_by('date_deadline')
# FIXME
# task_list = sorted(task_list, key=lambda a: a.int_status)
# for task in task_list:
# checkIfFinished(task)
# return task_list
# def TaskInstanceList(request, process_id, task_id):
# #first check if user has the ownership
# task = get_object_or_404(Task, pk=task_id, owner=request.user)
# taskinstance_list = task.taskinstance_set.all()
# process = task.process
# return render_to_response('requester/taskinstance_list.html', {'process':process, 'taskinstance_list':taskinstance_list}, context_instance=RequestContext(request))
@login_required
def uploadProcess(request):
''' deploy the process and starts it '''
user = request.user
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
username = settings.ACTIVITI_USERNAME
password = settings.ACTIVITI_PASSWORD
# edit the id of the process, so it's almos unique.
# file_uploaded = request.FILES['file']
main_file = ""
obj_uploaded = request.FILES['file']
# data = request.FILES['file'] # or self.files['image'] in your form
path = default_storage.save(str(uuid4()) + '.zip', ContentFile(obj_uploaded.read()))
tmp_file = os.path.join(settings.MEDIA_ROOT, path)
log.debug("file %s", tmp_file)
if zipfile.is_zipfile(tmp_file):
zf = zipfile.ZipFile(tmp_file)
for member in zf.namelist():
log.debug("deploying %s", member)
bpmn_file = zf.read(member)
# for version 5.16.3<
files = {'file': (member, bpmn_file)}
#for version 5.16.4
# files={member:bpmn_file}
url = settings.ACTIVITI_URL + "/repository/deployments"
response = requests.post(url, files=files, auth=HTTPBasicAuth(username, password))
log.debug("deploy process response %s", response.status_code)
if response.status_code == 500:
log.debug("it is a 500")
raise Http404
log.debug(response.text)
# User.objects.get(username="crowdcomputer")
# log.debug("user %s",cc.username)
# TODO: useless right now.
app = Application.objects.get(name="bpmn")
cc = app.user
log.debug("app %s %s", app.name, cc)
# if c:
# app.token = str(uuid4()).replace('-', '')
# app.save()
# root = etree.fromstring(bpmn_file)
# processes = root.findall('{http://www.omg.org/spec/BPMN/20100524/MODEL}process')
if member.startswith("sid-main"):
main_file = member[0:member.index('.')]
log.debug("Main %s", main_file)
# title = processes[0].attrib['name']
title = request.FILES['file']
log.debug("title");
process = Process(title=title, description="process created with bpmn", owner=user,
application=app)
process.save()
log.debug("done")
log.debug("delete file ")
default_storage.delete(tmp_file)
log.debug("something to start -> %s", main_file)
data = {}
data['processDefinitionKey'] = str(main_file)
# data['processId'] = str(process.pk)
# data['app_token'] = app.token
# token, created = Token.objects.get_or_create(user=request.user)
# data['user_token'] = token.key
variables = []
variables.append(createObject('processId', str(process.pk)))
variables.append(createObject('app_token', app.token))
token, created = Token.objects.get_or_create(user=request.user)
variables.append(createObject('user_token', token.key))
data['variables'] = variables
dumps = json.dumps(data)
log.debug("dumps data %s", data)
startProcess(process, main_file, data)
return HttpResponseRedirect(reverse_lazy('r-task-list', args=[process.pk]))
else:
# check if user exists
form = None
if not user.groups.filter(name='bpmn').exists():
messages.error(request,
"You don't have the rights to use this feature. Please write to stefano@crowdcomputer.org if you need it.")
else:
form = UploadFileForm()
return render_to_response('requester/creation.html', {'form': form}, context_instance=RequestContext(request))
# root = etree.fromstring(read_file)
# processes = root.findall('{http://www.omg.org/spec/BPMN/20100524/MODEL}process')
# # change the id to be unique, if we create user then this is not needed.
# id_process = "sid-" + str(uuid4())
# log.debug("process id %s", processes[0].attrib['id'])
# processes[0].attrib['id'] = id_process
# process_name = processes[0].attrib['id']
# # process[0].attrib['name'] = id_process
# log.debug("process id %s", processes[0].attrib['id'])
# process = processes[0]
#
# # add receive tasks to all the processes
# tasks = root.xpath(".//omg:serviceTask[starts-with(@activiti:extensionId,'org.crowdcomputer.ui.task')]",namespaces={"omg":"http://www.omg.org/spec/BPMN/20100524/MODEL","activiti":"http://activiti.org/bpmn"})
# # sequence_flows_all = root.findall('.//{http://www.omg.org/spec/BPMN/20100524/MODEL}sequenceFlow')
# # random number to not overwrite existing one. hope there are no more than 100000 flows
# tot = 10000
# log.debug("tasks %s " % tasks)
# for task in tasks:
# # add a receive task for every crowdtask
# log.debug("task attrib id %s",task.attrib['id'])
# process.append(receiveTask(task.attrib['id']))
#
# # modify the sequence
# sequence_flow_task = root.findall('.//{http://www.omg.org/spec/BPMN/20100524/MODEL}sequenceFlow[@sourceRef="' + task.attrib['id'] + '"]')
# for sequence in sequence_flow_task:
# process.append(fixSF(sequence, task.attrib['id'] + "-receive", tot))
# tot = tot + 1
#
#
# bpmn_file = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + etree.tostring(root)
# log.debug("bpmn \n"+bpmn_file+"\n")
# log.debug("file_upload prima read %s",read_file)
# files = {'bpmn-file': bpmn_file}
# log.debug("url to post " + url)
# fixer_response = requests.post('http://localhost:8080/crocoactivitidiagram/',data=files)
# log.debug("response " + fixer_response.text)
# files = {'file': (str(id_process+".bpmn"), fixer_response.text)}
# start process
@login_required
def exportcsv(request, process_id, task_id):
response = HttpResponse(content_type='text/csv')
task = get_object_or_404(Task, pk=task_id)
process = get_object_or_404(Process, pk=process_id, owner=request.user)
response['Content-Disposition'] = 'attachment; filename="' + task.title + '.csv"'
writer = csv.writer(response)
allinstances = task.taskinstance_set.all()
if len(allinstances) > 0:
firstinstance = None
i = 0
while (firstinstance is None or firstinstance.executor is None):
firstinstance = allinstances[i]
log.debug("%s %s", firstinstance, i)
i = i + 1;
if i > len(allinstances):
return response
firstrow = ['user']
if firstinstance.input_data:
log.debug("fi input %s", firstinstance.input_data.value)
for obj in firstinstance.input_data.value:
for key in obj.keys():
firstrow.append("input-" + key)
if firstinstance.output_data:
log.debug("fi output %s", firstinstance.output_data.value)
for key in firstinstance.output_data.value.keys():
firstrow.append("output-" + key)
if firstinstance.parameters:
log.debug("fi pars %s", firstinstance.parameters)
for key in firstinstance.parameters.keys():
firstrow.append("parameters-" + key)
writer.writerow(firstrow)
for instance in allinstances:
row = []
if instance.executor:
if 'validation' in instance.parameters and instance.parameters['validation']:
row.append(instance.executor.username)
if instance.input_data:
for obj in instance.input_data.value:
log.debug("all in %s", obj)
for value in obj.values():
log.debug("input %s", value)
row.append("" + str(value))
if instance.output_data:
for value in instance.output_data.value.values():
log.debug("output %s", value)
row.append("" + str(value))
if instance.parameters:
for value in instance.parameters.values():
log.debug("pars %s", value)
row.append("" + str(value))
writer.writerow(row)
return response
def TaskValidate(request, task_id):
log.debug("task_id %s - %s - %s" %(task_id,request.POST,request.GET))
task = get_object_or_404(Task, pk=task_id, owner=request.user)
if request.POST:
form = ValidationForm(request.POST)
if form.is_valid():
# TODO: unify with the api, now the code is copied
value = form.cleaned_data['validation']
for task_instance in task.taskinstance_set.all():
if 'validation' not in task_instance.parameters:
task_instance.quality = value
pars = task_instance.parameters
if pars is None:
pars = {}
pars['validation'] = value
task_instance.save()
# if ("process_tactics_id" in task_instance.parameters):
# signal(task_instance.parameters['process_tactics_id'], task_instance.task.id, task_instance.id)
messages.info(request, 'Validation made')
return redirect(reverse('r-taskinstances',args={task_instance.task.process.id,task_instance.task.id,}))
else:
return render_to_response('requester/form.html', {'form': form}, context_instance=RequestContext(request))
else:
log.debug("GET task_id %s",task_id)
form = ValidationForm()
return render_to_response('requester/form.html', {'form': form}, context_instance=RequestContext(request))
def TaskInstanceValidate(request, task_instance_id):
task_instance = get_object_or_404(TaskInstance, pk=task_instance_id, task__owner=request.user)
if request.POST:
form = ValidationForm(request.POST)
if form.is_valid():
if 'validation' not in task_instance.parameters:
# TODO: unify with the api, now the code is copied
value = form.cleaned_data['validation']
task_instance.quality = value
pars = task_instance.parameters
if pars is None:
pars = {}
pars['validation'] = value
task_instance.save()
# if ("process_tactics_id" in task_instance.parameters):
# signal(task_instance.parameters['process_tactics_id'], task_instance.task.id, task_instance.id)
messages.info(request, 'Validation made')
else:
messages.warning(request, 'Validation was already set')
return redirect(reverse('r-taskinstances',args={task_instance.task.process.id,task_instance.task.id,}))
else:
return render_to_response('requester/form.html', {'form': form}, context_instance=RequestContext(request))
else:
form = ValidationForm()
return render_to_response('requester/form.html', {'form': form}, context_instance=RequestContext(request))
| |
# Copyright 2012 NEC Corporation
#
# 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.conf import settings
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon_lib import exceptions
from horizon_lib import forms
from horizon_lib import messages
from openstack_horizon import api
LOG = logging.getLogger(__name__)
PROVIDER_TYPES = [('local', _('Local')), ('flat', _('Flat')),
('vlan', _('VLAN')), ('gre', _('GRE')),
('vxlan', _('VXLAN'))]
SEGMENTATION_ID_RANGE = {'vlan': [1, 4094], 'gre': [0, (2 ** 32) - 1],
'vxlan': [0, (2 ** 24) - 1]}
class CreateNetwork(forms.SelfHandlingForm):
name = forms.CharField(max_length=255,
label=_("Name"),
required=False)
tenant_id = forms.ChoiceField(label=_("Project"))
if api.neutron.is_port_profiles_supported():
widget = None
else:
widget = forms.HiddenInput()
net_profile_id = forms.ChoiceField(label=_("Network Profile"),
required=False,
widget=widget)
network_type = forms.ChoiceField(
label=_("Provider Network Type"),
help_text=_("The physical mechanism by which the virtual "
"network is implemented."),
widget=forms.Select(attrs={
'class': 'switchable',
'data-slug': 'network_type'
}))
physical_network = forms.CharField(
max_length=255,
label=_("Physical Network"),
help_text=_("The name of the physical network over which the "
"virtual network is implemented."),
initial='default',
widget=forms.TextInput(attrs={
'class': 'switched',
'data-switch-on': 'network_type',
'data-network_type-flat': _('Physical Network'),
'data-network_type-vlan': _('Physical Network')
}))
segmentation_id = forms.IntegerField(
label=_("Segmentation ID"),
widget=forms.TextInput(attrs={
'class': 'switched',
'data-switch-on': 'network_type',
'data-network_type-vlan': _('Segmentation ID'),
'data-network_type-gre': _('Segmentation ID'),
'data-network_type-vxlan': _('Segmentation ID')
}))
# TODO(amotoki): make UP/DOWN translatable
admin_state = forms.ChoiceField(choices=[(True, 'UP'), (False, 'DOWN')],
label=_("Admin State"))
shared = forms.BooleanField(label=_("Shared"),
initial=False, required=False)
external = forms.BooleanField(label=_("External Network"),
initial=False, required=False)
@classmethod
def _instantiate(cls, request, *args, **kwargs):
return cls(request, *args, **kwargs)
def __init__(self, request, *args, **kwargs):
super(CreateNetwork, self).__init__(request, *args, **kwargs)
tenant_choices = [('', _("Select a project"))]
tenants, has_more = api.keystone.tenant_list(request)
for tenant in tenants:
if tenant.enabled:
tenant_choices.append((tenant.id, tenant.name))
self.fields['tenant_id'].choices = tenant_choices
if api.neutron.is_port_profiles_supported():
self.fields['net_profile_id'].choices = (
self.get_network_profile_choices(request))
if api.neutron.is_extension_supported(request, 'provider'):
neutron_settings = getattr(settings,
'OPENSTACK_NEUTRON_NETWORK', {})
seg_id_range = neutron_settings.get('segmentation_id_range', {})
self.seg_id_range = {
'vlan': seg_id_range.get('vlan',
SEGMENTATION_ID_RANGE.get('vlan')),
'gre': seg_id_range.get('gre',
SEGMENTATION_ID_RANGE.get('gre')),
'vxlan': seg_id_range.get('vxlan',
SEGMENTATION_ID_RANGE.get('vxlan'))
}
seg_id_help = (
_("For VLAN networks, the VLAN VID on the physical "
"network that realizes the virtual network. Valid VLAN VIDs "
"are %(vlan_min)s through %(vlan_max)s. For GRE or VXLAN "
"networks, the tunnel ID. Valid tunnel IDs for GRE networks "
"are %(gre_min)s through %(gre_max)s. For VXLAN networks, "
"%(vxlan_min)s through %(vxlan_max)s.")
% {'vlan_min': self.seg_id_range['vlan'][0],
'vlan_max': self.seg_id_range['vlan'][1],
'gre_min': self.seg_id_range['gre'][0],
'gre_max': self.seg_id_range['gre'][1],
'vxlan_min': self.seg_id_range['vxlan'][0],
'vxlan_max': self.seg_id_range['vxlan'][1]})
self.fields['segmentation_id'].help_text = seg_id_help
supported_provider_types = neutron_settings.get(
'supported_provider_types', ['*'])
if supported_provider_types == ['*']:
network_type_choices = PROVIDER_TYPES
else:
network_type_choices = [
net_type for net_type in PROVIDER_TYPES
if net_type[0] in supported_provider_types]
if len(network_type_choices) == 0:
self._hide_provider_network_type()
else:
self.fields['network_type'].choices = network_type_choices
else:
self._hide_provider_network_type()
def get_network_profile_choices(self, request):
profile_choices = [('', _("Select a profile"))]
for profile in self._get_profiles(request, 'network'):
profile_choices.append((profile.id, profile.name))
return profile_choices
def _get_profiles(self, request, type_p):
profiles = []
try:
profiles = api.neutron.profile_list(request, type_p)
except Exception:
msg = _('Network Profiles could not be retrieved.')
exceptions.handle(request, msg)
return profiles
def _hide_provider_network_type(self):
self.fields['network_type'].widget = forms.HiddenInput()
self.fields['physical_network'].widget = forms.HiddenInput()
self.fields['segmentation_id'].widget = forms.HiddenInput()
self.fields['network_type'].required = False
self.fields['physical_network'].required = False
self.fields['segmentation_id'].required = False
def handle(self, request, data):
try:
params = {'name': data['name'],
'tenant_id': data['tenant_id'],
'admin_state_up': (data['admin_state'] == 'True'),
'shared': data['shared'],
'router:external': data['external']}
if api.neutron.is_port_profiles_supported():
params['net_profile_id'] = data['net_profile_id']
if api.neutron.is_extension_supported(request, 'provider'):
network_type = data['network_type']
params['provider:network_type'] = network_type
if network_type in ['flat', 'vlan']:
params['provider:physical_network'] = (
data['physical_network'])
if network_type in ['vlan', 'gre', 'vxlan']:
params['provider:segmentation_id'] = (
data['segmentation_id'])
network = api.neutron.network_create(request, **params)
msg = _('Network %s was successfully created.') % data['name']
LOG.debug(msg)
messages.success(request, msg)
return network
except Exception:
redirect = reverse('horizon:admin:networks:index')
msg = _('Failed to create network %s') % data['name']
exceptions.handle(request, msg, redirect=redirect)
def clean(self):
cleaned_data = super(CreateNetwork, self).clean()
self._clean_physical_network(cleaned_data)
self._clean_segmentation_id(cleaned_data)
return cleaned_data
def _clean_physical_network(self, data):
network_type = data.get('network_type')
if 'physical_network' in self._errors and (
network_type in ['local', 'gre']):
# In this case the physical network is not required, so we can
# ignore any errors.
del self._errors['physical_network']
def _clean_segmentation_id(self, data):
network_type = data.get('network_type')
if 'segmentation_id' in self._errors:
if network_type in ['local', 'flat']:
# In this case the segmentation ID is not required, so we can
# ignore any errors.
del self._errors['segmentation_id']
elif network_type in ['vlan', 'gre', 'vxlan']:
seg_id = data.get('segmentation_id')
seg_id_range = {'min': self.seg_id_range[network_type][0],
'max': self.seg_id_range[network_type][1]}
if seg_id < seg_id_range['min'] or seg_id > seg_id_range['max']:
if network_type == 'vlan':
msg = _('For VLAN networks, valid VLAN IDs are %(min)s '
'through %(max)s.') % seg_id_range
elif network_type == 'gre':
msg = _('For GRE networks, valid tunnel IDs are %(min)s '
'through %(max)s.') % seg_id_range
elif network_type == 'vxlan':
msg = _('For VXLAN networks, valid tunnel IDs are %(min)s '
'through %(max)s.') % seg_id_range
self._errors['segmentation_id'] = self.error_class([msg])
class UpdateNetwork(forms.SelfHandlingForm):
name = forms.CharField(label=_("Name"), required=False)
tenant_id = forms.CharField(widget=forms.HiddenInput)
# TODO(amotoki): make UP/DOWN translatable
admin_state = forms.ChoiceField(choices=[(True, 'UP'), (False, 'DOWN')],
label=_("Admin State"))
shared = forms.BooleanField(label=_("Shared"), required=False)
external = forms.BooleanField(label=_("External Network"), required=False)
failure_url = 'horizon:admin:networks:index'
def handle(self, request, data):
try:
params = {'name': data['name'],
'admin_state_up': (data['admin_state'] == 'True'),
'shared': data['shared'],
'router:external': data['external']}
network = api.neutron.network_update(request,
self.initial['network_id'],
**params)
msg = _('Network %s was successfully updated.') % data['name']
LOG.debug(msg)
messages.success(request, msg)
return network
except Exception:
msg = _('Failed to update network %s') % data['name']
LOG.info(msg)
redirect = reverse(self.failure_url)
exceptions.handle(request, msg, redirect=redirect)
| |
# -*- coding: utf-8 -*-
"""A plugin to enable quick triage of Windows Services."""
import yaml
from plaso.analysis import interface
from plaso.analysis import manager
from plaso.lib import event
from plaso.winnt import human_readable_service_enums
class WindowsService(yaml.YAMLObject):
"""Class to represent a Windows Service."""
# This is used for comparison operations and defines attributes that should
# not be used during evaluation of whether two services are the same.
COMPARE_EXCLUDE = frozenset([u'sources'])
KEY_PATH_SEPARATOR = u'\\'
# YAML attributes
yaml_tag = u'!WindowsService'
yaml_loader = yaml.SafeLoader
yaml_dumper = yaml.SafeDumper
def __init__(self, name, service_type, image_path, start_type, object_name,
source, service_dll=None):
"""Initializes a new Windows service object.
Args:
name: The name of the service
service_type: The value of the Type value of the service key.
image_path: The value of the ImagePath value of the service key.
start_type: The value of the Start value of the service key.
object_name: The value of the ObjectName value of the service key.
source: A tuple of (pathspec, Registry key) describing where the
service was found
service_dll: Optional string value of the ServiceDll value in the
service's Parameters subkey. The default is None.
Raises:
TypeError: If a tuple with two elements is not passed as the 'source'
argument.
"""
self.name = name
self.service_type = service_type
self.image_path = image_path
self.start_type = start_type
self.service_dll = service_dll
self.object_name = object_name
if isinstance(source, tuple):
if len(source) != 2:
raise TypeError(u'Source arguments must be tuple of length 2.')
# A service may be found in multiple Control Sets or Registry hives,
# hence the list.
self.sources = [source]
else:
raise TypeError(u'Source argument must be a tuple.')
self.anomalies = []
@classmethod
def FromEvent(cls, service_event):
"""Creates a Service object from an plaso event.
Args:
service_event: The event object (instance of EventObject) to create a new
Service object from.
"""
_, _, name = service_event.keyname.rpartition(
WindowsService.KEY_PATH_SEPARATOR)
service_type = service_event.regvalue.get(u'Type')
image_path = service_event.regvalue.get(u'ImagePath')
start_type = service_event.regvalue.get(u'Start')
service_dll = service_event.regvalue.get(u'ServiceDll', u'')
object_name = service_event.regvalue.get(u'ObjectName', u'')
if service_event.pathspec:
source = (service_event.pathspec.location, service_event.keyname)
else:
source = (u'Unknown', u'Unknown')
return cls(
name=name, service_type=service_type, image_path=image_path,
start_type=start_type, object_name=object_name,
source=source, service_dll=service_dll)
def HumanReadableType(self):
"""Return a human readable string describing the type value."""
if isinstance(self.service_type, basestring):
return self.service_type
return human_readable_service_enums.SERVICE_ENUMS[u'Type'].get(
self.service_type, u'{0:d}'.format(self.service_type))
def HumanReadableStartType(self):
"""Return a human readable string describing the start_type value."""
if isinstance(self.start_type, basestring):
return self.start_type
return human_readable_service_enums.SERVICE_ENUMS[u'Start'].get(
self.start_type, u'{0:d}'.format(self.start_type))
def __eq__(self, other_service):
"""Custom equality method so that we match near-duplicates.
Compares two service objects together and evaluates if they are
the same or close enough to be considered to represent the same service.
For two service objects to be considered the same they need to
have the the same set of attributes and same values for all their
attributes, other than those enumerated as reserved in the
COMPARE_EXCLUDE constant.
Args:
other_service: The service (instance of WindowsService) we are testing
for equality.
Returns:
A boolean value to indicate whether the services are equal.
"""
if not isinstance(other_service, WindowsService):
return False
attributes = set(self.__dict__.keys())
other_attributes = set(self.__dict__.keys())
if attributes != other_attributes:
return False
# We compare the values for all attributes, other than those specifically
# enumerated as not relevant for equality comparisons.
for attribute in attributes.difference(self.COMPARE_EXCLUDE):
if getattr(self, attribute, None) != getattr(
other_service, attribute, None):
return False
return True
class WindowsServiceCollection(object):
"""Class to hold and de-duplicate Windows Services."""
def __init__(self):
"""Initialize a collection that holds Windows Service."""
self._services = []
def AddService(self, new_service):
"""Add a new service to the list of ones we know about.
Args:
new_service: The service (instance of WindowsService) to add.
"""
for service in self._services:
if new_service == service:
# If this service is the same as one we already know about, we
# just want to add where it came from.
service.sources.append(new_service.sources[0])
return
# We only add a new object to our list if we don't have
# an identical one already.
self._services.append(new_service)
@property
def services(self):
"""Get the services in this collection."""
return self._services
class WindowsServicesPlugin(interface.AnalysisPlugin):
"""Provides a single list of for Windows services found in the Registry."""
NAME = u'windows_services'
# Indicate that we can run this plugin during regular extraction.
ENABLE_IN_EXTRACTION = True
def __init__(self, incoming_queue):
"""Initializes the Windows Services plugin
Args:
incoming_queue: A queue to read events from.
"""
super(WindowsServicesPlugin, self).__init__(incoming_queue)
self._output_format = u'text'
self._service_collection = WindowsServiceCollection()
def ExamineEvent(self, analysis_mediator, event_object, **kwargs):
"""Analyzes an event_object and creates Windows Services as required.
At present, this method only handles events extracted from the Registry.
Args:
analysis_mediator: The analysis mediator object (instance of
AnalysisMediator).
event_object: The event object (instance of EventObject) to examine.
"""
# TODO: Handle event log entries here also (ie, event id 4697).
if getattr(event_object, u'data_type', None) != u'windows:registry:service':
return
else:
# Create and store the service.
service = WindowsService.FromEvent(event_object)
self._service_collection.AddService(service)
def SetOutputFormat(self, output_format):
"""Sets the output format of the generated report.
Args:
output_format: The format the the plugin should used to produce its
output, as a string.
"""
self._output_format = output_format
def _FormatServiceText(self, service):
"""Produces a human readable multi-line string representing the service.
Args:
service: The service (instance of WindowsService) to format.
"""
string_segments = [
service.name,
u'\tImage Path = {0:s}'.format(service.image_path),
u'\tService Type = {0:s}'.format(service.HumanReadableType()),
u'\tStart Type = {0:s}'.format(service.HumanReadableStartType()),
u'\tService Dll = {0:s}'.format(service.service_dll),
u'\tObject Name = {0:s}'.format(service.object_name),
u'\tSources:']
for source in service.sources:
string_segments.append(u'\t\t{0:s}:{1:s}'.format(source[0], source[1]))
return u'\n'.join(string_segments)
def CompileReport(self, analysis_mediator):
"""Compiles a report of the analysis.
Args:
analysis_mediator: The analysis mediator object (instance of
AnalysisMediator).
Returns:
The analysis report (instance of AnalysisReport).
"""
report = event.AnalysisReport(self.NAME)
if self._output_format == u'yaml':
lines_of_text = []
lines_of_text.append(
yaml.safe_dump_all(self._service_collection.services))
else:
lines_of_text = [u'Listing Windows Services']
for service in self._service_collection.services:
lines_of_text.append(self._FormatServiceText(service))
# Separate services with a blank line.
lines_of_text.append(u'')
report.SetText(lines_of_text)
return report
manager.AnalysisPluginManager.RegisterPlugin(WindowsServicesPlugin)
| |
import re
import ipaddr
import properties
from security import ACE, AtomicACE, LowlevelACE
from enums import RuleInteractionType, RuleOperation, ServiceProtocol, GraphAttribute, SecurityElement, RuleEffect
from exception import ParserException
def Singleton(cls):
instances = {}
def GetInstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return GetInstance
class Util:
@staticmethod
def HasDefaultSubnetZero(ipaddress_list):
for ip in ipaddress_list:
if ip == ipaddr.IPv4Network("0.0.0.0/0"):
return True
@staticmethod
def GetNodeById(id, graph):
for node in graph.nodes_iter():
zoneId = graph.node[node].get(GraphAttribute.Label)
if zoneId == id: return node
return None
@staticmethod
def ConvertStringToIpaddress(ip_string):
p = re.search('host',ip_string)
if p:
# host <ip> format
return ipaddr.IPv4Network("%s/%s" % (ip_string.split(' ')[1],"255.255.255.255"))
else:
# <subnet> <mask> format
# TODO: ASA needs this
#return ipaddr.IPv4Network("%s/%s" %(ip_string.split(' ')[0], ip_string.split(' ')[1]))
# TODO: Routers need this instead
wc_mask_value = int(ipaddr.IPv4Address(ip_string.split(' ')[1]))
subnet_mask_value = int(ipaddr.IPv4Address("255.255.255.255")) - wc_mask_value
return ipaddr.IPv4Network("%s/%s"%(ip_string.split(' ')[0],str(ipaddr.IPv4Address(subnet_mask_value))))
@staticmethod
def GetMergePendingZones(zone_ip_list):
zones_to_merge = []
for zone1 in zone_ip_list:
ip_list1 = zone_ip_list[zone1]
for zone2 in zone_ip_list:
if(zone1 != zone2):
ip_list2 = zone_ip_list[zone2]
if Util.SubnetOverlapsExist(ip_list1, ip_list2):
if not zones_to_merge.__contains__(zone1):
zones_to_merge.append(zone1)
if not zones_to_merge.__contains__(zone2):
zones_to_merge.append(zone2)
break
'''
# Cleanup
final=[]
for zone_tuple1 in zones_to_merge:
zone1=zone_tuple1[0]
zone2=zone_tuple1[1]
for zone_tuple2 in zones_to_merge:
if(zone_tuple1 != zone_tuple2):
zone3=zone_tuple2[0]
zone4=zone_tuple2[1]
if zone1==zone3 or zone1==zone4 or zone2==zone3 or zone2==zone4:
final.append((zone1,zone2,zone3,zone4))'''
return zones_to_merge
@staticmethod
def SubnetOverlapsExist(ip_list1, ip_list2):
for subnet1 in ip_list1:
for subnet2 in ip_list2:
if subnet1.overlaps(subnet2): return True
return False
@staticmethod
def GetHostZone(host_ip, all_zones):
fw_zone=None
#Find the firewall zone
for zone in all_zones:
if zone.zone_id =='fwz':
fw_zone =zone
break
for zone in all_zones:
if zone.ContainsSubnetOrIpaddress(host_ip): return zone.zone_id
elif fw_zone!=None:
excluded=None
#check whether zone+fw_zone includes the host_ip
for ipaddress in fw_zone.ipaddress_list:
try:
excluded = ipaddr.IPv4Network(host_ip).address_exclude(ipaddress)
break
except ValueError, e:
# not contained
pass
if zone.ContainsSubnetOrIpaddress(excluded): return zone.zone_id
return ""
@staticmethod
def GetHostZoneIds(host_ip, all_zones):
fw_zones=[]
zone_ids=[]
#Find the firewall zone
for zone in all_zones:
if zone.zone_id.__contains__('fwz'):
fw_zones.append(zone)
for zone in all_zones:
if zone.ContainsSubnetOrIpaddress(host_ip):
zone_ids.append(zone.zone_id)
return zone_ids
elif len(fw_zones) !=0:
excluded=None
for fw_zone in fw_zones:
#check whether zone+fw_zone includes the host_ip
for ipaddress in fw_zone.ipaddress_list:
try:
excluded = ipaddr.IPv4Network(host_ip).address_exclude(ipaddress)
break
except ValueError, e:
# not contained
pass
if zone.ContainsSubnetOrIpaddress(excluded):
zone_ids.append(fw_zone.zone_id)
zone_ids.append(zone.zone_id)
return zone_ids
return ""
@staticmethod
def GetServiceName(protocol, service_port):
tcp_service_lookup = dict({'5190': 'aol', '179': 'bgp','19': 'chargen','1494': 'citrix-ica',
'514': 'cmd','2748': 'ctiqbe', '13': 'daytime','53': 'domain', '7': 'echo','512': 'exec',
'79': 'finger','21': 'ftp', '20': 'ftp-data','70': 'gopher', '443': 'https','1720': 'h323',
'101': 'hostname','113': 'ident', '143': 'imap4','194': 'irc', '750': 'kerberos-iv','543': 'klogin',
'544': 'kshell','389': 'ldap', '636': 'ldaps','515': 'lpd', '513': 'login','1352': 'lotusnotes',
'139': 'netbios-ssn','119': 'nntp', '20': 'ftp-data','70': 'gopher', '443': 'https','1720': 'h323',
'5631': 'pcanywhere-data','496': 'pim-auto-rp', '109': 'pop2','110': 'pop3', '443': 'https','1720': 'h323', '139': 'netbios-ssn',
'1723': 'pptp','25': 'smtp', '1521': 'sqlnet','22': 'ssh', '111': 'sun_rpc','23': 'telnet', '137':'netbios-ns', '138':'netbios-dgm',
'69': 'tftp','540': 'uucp', '43': 'whois','80': 'www','49':'tacacs', '517':'talk', '445':'smb', '88':'kerberos', '135':'dce_rpc' })
udp_service_lookup = dict({'512':'biff','68':'bootpc','67':'bootps','195':'dnsix','7':'echo','500':'isakmp', '750':'kerberos-iv','434':'mobile-ip','42':'nameserver',
'137':'netbios-ns', '138':'netbios-dgm','123':'ntp','5632':'pcanywhere-status','1645':'radius','1646':'radius-acct','520':'rip','5510':'secureid-udp',
'161':'snmp','162':'snmptrap','111':'sun_rpc ', '514':'syslog','49':'tacacs','517':'talk ', '37':'time','513':'who','177':'xdmcp ',
'88':'kerberos', '135':'dce_rpc', '53':'domain', '389': 'ldap', '636': 'ldaps','139': 'netbios-ssn'})
if str(service_port).isdigit():
port_number = int(service_port)
if port_number < 1024:
if protocol =='tcp' and tcp_service_lookup.has_key(str(port_number)):
return tcp_service_lookup[str(port_number)]
elif protocol=='udp' and udp_service_lookup.has_key(str(port_number)):
return udp_service_lookup[str(port_number)]
else:
return service_port
else:
# Cannot translate dynamic ports
return service_port
else:
# Must be service name already
return service_port
@staticmethod
def IsZoneFreePath(path, zoneTopology):
if not path:
raise ValueError("path", properties.resources['value_null'])
if not zoneTopology:
raise ValueError("zoneTopology", properties.resources['value_null'])
for node in path:
if (zoneTopology.node[node].get(GraphAttribute.Type) == SecurityElement.Zone): return False
return True
@staticmethod
def ConvertToFirewallPath(nodePath, zoneTopology):
if not nodePath:
raise ValueError("nodePath", properties.resources['value_null'])
if not zoneTopology:
raise ValueError("zoneTopology", properties.resources['value_null'])
convertedPath = []
for node in nodePath:
convertedPath.append(zoneTopology.node[node].get(GraphAttribute.Label))
return convertedPath
@staticmethod
def GetIpList(criteria, zones):
# Evaluate criteria and extract ip address list
ip_list = []
if criteria!=None:
if criteria != 'any':
ipaddresses = Util.ConvertStringToIpaddress(criteria)
if isinstance(ipaddresses, list):
for ip in ipaddresses:
if not ip_list.__contains__(ip):
ip_list.append(ip)
elif not ip_list.__contains__(ipaddresses):
ip_list.append(ipaddresses)
else:
for zone in zones:
for ip in zone.ipaddress_list:
if not ip_list.__contains__(ip):
ip_list.append(ip)
return ip_list
@staticmethod
def ConvertToSubrulesList(ace, source_ip_list, dest_ip_list):
if not ace:
raise ValueError("ace", properties.resources['value_null'])
if not source_ip_list:
raise ValueError("source_ip_list", properties.resources['value_null'])
if not dest_ip_list:
raise ValueError("dest_ip_list", properties.resources['value_null'])
subrules = []
# Consider the cross-product of source and dest criteria to generate possible rule combinations
for source_ip in source_ip_list:
for dest_ip in dest_ip_list:
#TODO: use subrules with numeric fields for improved performance
#subrule_test = LowlevelACE(ace.Action, [Util.GetProtocol(ace.Protocol)], [source_ip], [Util.GetPorts(ace.source_port_filter)],[dest_ip],[Util.GetPorts(ace.dest_port_filter)], ace.icmp_type, ace.rule_core )
subrule = AtomicACE(ace.Action, [Util.GetProtocol(ace.Protocol)], source_ip, Util.GetPorts(ace.source_port_filter), dest_ip, Util.GetPorts(ace.dest_port_filter), ace.icmp_type, ace.rule_core)
if not subrules.__contains__(subrule): subrules.append(subrule)
return subrules
@staticmethod
def GetProtocol(protocol_desc):
if not protocol_desc:
raise ParserException("protocol_desc", properties.resources['value_null'])
if protocol_desc == ServiceProtocol.reverse_mapping[ServiceProtocol.tcp]:
return ServiceProtocol.tcp
elif protocol_desc == ServiceProtocol.reverse_mapping[ServiceProtocol.udp]:
return ServiceProtocol.udp
elif protocol_desc == ServiceProtocol.reverse_mapping[ServiceProtocol.icmp]:
return ServiceProtocol.icmp
elif protocol_desc == ServiceProtocol.reverse_mapping[ServiceProtocol.ip]:
return ServiceProtocol.ip
elif protocol_desc == ServiceProtocol.reverse_mapping[ServiceProtocol.eigrp]:
return ServiceProtocol.eigrp
else:
# Unhandled protocol type
raise ParserException('protocol_desc', properties.resources['arguments_invalid'])
@staticmethod
def GetPorts(port_filter_criteria):
if not port_filter_criteria: return None
ports = []
items = port_filter_criteria.split(' ')
# TODO: handle port ranges
ports.append(items[1])
return ports
@staticmethod
def GetCiscoACE(access_control_entry):
port_operators = ['eq', 'gt', 'lt', 'neq', 'range']
icmp_types=['unreachable', 'echo', 'echo-reply', 'source-quench']
# Extract rule action (permit/deny)
action_permit = re.search('permit',access_control_entry)
action_deny = re.search('deny',access_control_entry)
action_inactive=re.search('inactive',access_control_entry)
p = re.search(' \(',access_control_entry)
# work data
index =0
end = 0
rule_core_start=0
rule_core_end=0
ip_tuples =[]
rule_core=None
source = None
dest = None
source_port_filter = None
dest_port_filter=None
rule_effect = None
icmp_type=None
if action_inactive:
# Entry is disabled..ignore
pass
elif action_permit or action_deny:
if action_permit:
rule_core_start=action_permit.start()
end = action_permit.end()
rule_effect = RuleEffect.Permit
else:
end = action_deny.end()
rule_core_start=action_deny.start()
rule_effect = RuleEffect.Deny
if p: rule_core_end = p.start()
# TODO: check if ASA still works with this (added for routers)
else: rule_core_end = len(access_control_entry)
rule_core=access_control_entry[rule_core_start:rule_core_end]
rule_match_criteria = access_control_entry[end:].lstrip().split(' ')
protocol = rule_match_criteria[index]
# Cisco ACLs support tcp, udp, icmp and ip based ACEs
if protocol == 'tcp' or protocol == 'udp' or protocol=='icmp' or protocol=='ip' or protocol=='eigrp':
index +=1
# Extract source
temp = rule_match_criteria[index]
if temp == 'any':
source = 'any'
else:
# Must be source source_wc format
index +=1
source = "%s %s" % (temp, rule_match_criteria[index])
index +=1
if protocol == 'tcp' or protocol == 'udp':
# Extract source ports
source_port_operator = rule_match_criteria[index]
if source_port_operator in port_operators:
index +=1
source_port_filter = "%s %s"% (source_port_operator, rule_match_criteria[index])
index +=1
temp = rule_match_criteria[index]
# Extract dest
if temp == 'any':
dest = 'any'
else:
# Must be dest dest_wc format
index +=1
dest = "%s %s" % (temp, rule_match_criteria[index])
index +=1
# Extract dest ports
if protocol == 'tcp' or protocol == 'udp':
if index < len(rule_match_criteria):
dest_port_operator = rule_match_criteria[index]
if dest_port_operator in port_operators:
index +=1
dest_port_filter = "%s %s"%(dest_port_operator, rule_match_criteria[index])
elif protocol=="icmp":
if index < len(rule_match_criteria):
icmp_type= rule_match_criteria[index]
if not icmp_type in icmp_types:
icmp_type=None
# Replace www with http (Cisco allows www)
if source_port_filter!= None and source_port_filter.__contains__('www'):
source_port_filter = source_port_filter.replace('www','http')
if dest_port_filter!= None and dest_port_filter.__contains__('www'):
dest_port_filter = dest_port_filter.replace('www','http')
return ACE(rule_effect, protocol, source,source_port_filter, dest, dest_port_filter, icmp_type, rule_core)
return None
@staticmethod
def RemoveProtocolsFromRange(protocols, range):
return [i for i in range if i not in protocols]
@staticmethod
def GetNetRule(rule1, rule2, operation, final_action):
if not rule1:
raise ParserException("rule1", properties.resources['value_null'])
if not rule2:
raise ParserException("rule2", properties.resources['value_null'])
if not operation:
raise ParserException("operation", properties.resources['value_null'])
#..calculate cross_product of rules
rule1_combinations = []
for rule1_source_host in Util.GetHostIpaddresses(rule1.source_ip):
for rule1_dest_host in Util.GetHostIpaddresses(rule1.dest_ip):
rule1_combinations.append((rule1_source_host,rule1_dest_host))
rule2_combinations = []
# rule2 can be a single rule or a list of rules
rule2_protocols=None
if isinstance(rule2, list):
for rule2_item in rule2:
rule2_protocols=rule2_item.Protocols
for rule2_source_host in Util.GetHostIpaddresses(rule2_item.source_ip):
for rule2_dest_host in Util.GetHostIpaddresses(rule2_item.dest_ip):
rule2_combinations.append((rule2_source_host,rule2_dest_host))
else:
rule2_protocols=rule2.Protocols
for rule2_source_host in Util.GetHostIpaddresses(rule2.source_ip):
for rule2_dest_host in Util.GetHostIpaddresses(rule2.dest_ip):
rule2_combinations.append((rule2_source_host,rule2_dest_host))
if operation == RuleOperation.Exclude:
result=[]
if rule1.Protocols==rule2_protocols:
# take rule1-rule2
#..i.e. cross_product(rule1.source_ip, rule1.dest_ip) - cross_product(rule2.source_ip, rule2.dest_ip)
# i.e. exclude rule2_combinations from rule1_combinations
for combination_to_remove in rule2_combinations:
if rule1_combinations.__contains__(combination_to_remove):
rule1_combinations.remove(combination_to_remove)
# Create rules for remaining combinations
for combination in rule1_combinations:
atomic_ace = AtomicACE(final_action, rule1.Protocols, combination[0], rule1.SourcePortFilter, combination[1], rule1.DestPortFilter, rule1.icmp_type, rule1.entry)
result.append(atomic_ace)
elif (rule1.Protocols.__contains__(ServiceProtocol.ip) or rule2_protocols.__contains__(ServiceProtocol.ip)):
# TODO: take (ip - other_protocol): need finite list - resolve
# for the time being return rule1 in whole
# expand ip into its protocol composition
overlap_rule=None
non_overlap_rule=None
if rule1.Protocols.__contains__(ServiceProtocol.ip):
overlap_rule = AtomicACE(rule1.Action, rule2_protocols, rule1.source_ip, rule1.SourcePortFilter, rule1.dest_ip, rule1.DestPortFilter, rule1.icmp_type, rule1.entry )
non_overlap_protocols= Util.RemoveProtocolsFromRange(rule2_protocols,range(1,255))
non_overlap_rule = AtomicACE(rule1.Action, non_overlap_protocols, rule1.source_ip, rule1.SourcePortFilter, rule1.dest_ip, rule1.DestPortFilter, rule1.icmp_type, rule1.entry )
net_overlap = Util.GetNetRule(overlap_rule, rule2, operation, rule1.Action)
if net_overlap!=None:
if isinstance(net_overlap, list):
[result.append(overlap) for overlap in net_overlap]
else:
result.append(net_overlap)
if non_overlap_rule!=None:
result.append(non_overlap_rule)
elif rule2_protocols.__contains__(ServiceProtocol.ip):
overlap_rule = AtomicACE(rule2.Action, rule1.Protocols, rule2.source_ip, rule2.SourcePortFilter, rule2.dest_ip, rule2.DestPortFilter, rule2.icmp_type, rule2.entry )
non_overlap_protocols= Util.RemoveProtocolsFromRange(rule1.Protocols,range(1,255))
non_overlap_rule = AtomicACE(rule2.Action, non_overlap_protocols, rule2.source_ip, rule2.SourcePortFilter, rule2.dest_ip, rule2.DestPortFilter, rule2.icmp_type, rule2.entry )
net_overlap = Util.GetNetRule(overlap_rule, rule1, operation, rule2.Action)
if net_overlap!=None:
if isinstance(net_overlap, list):
[result.append(overlap) for overlap in net_overlap]
else:
result.append(net_overlap)
if non_overlap_rule!=None:
result.append(non_overlap_rule)
return result
elif operation == RuleOperation.Intersect:
# include only the common tuples in rule2_combinations and rule1_combinations
common_combinations=[]
for combination in rule2_combinations:
if rule1_combinations.__contains__(combination):
common_combinations.append(combination)
# Get resultant protocol
final_protocols= rule1.Protocols
if rule1.Protocols != rule2.Protocols and (rule1.Protocols.__contains__(ServiceProtocol.ip) or rule2.Protocols.__contains__(ServiceProtocol.ip)):
# Pick child protocol that is NOT based on ip
if not rule2.Protocols.__contains__(ServiceProtocol.ip): final_protocols=rule2.Protocols
# Create rules for common combinations
result=[]
for combination in common_combinations:
atomic_ace = AtomicACE(final_action, final_protocols, combination[0], rule1.SourcePortFilter, combination[1], rule1.DestPortFilter, rule1.icmp_type, rule1.entry)
result.append(atomic_ace)
return result
else:
# Unhandled operation type
raise ParserException('operation', properties.resources['arguments_invalid'])
@staticmethod
def GetHostIpaddresses(ipv4_network):
hosts=[]
if isinstance(ipv4_network, ipaddr.IPv4Address):
return [ipv4_network]
elif ipv4_network.prefixlen == 32:
# ip is host address
return [ipv4_network.network]
else:
# TODO: need to do this differently..when we do address splits, the subnets created are not real subnets, infact they can be hosts
hosts.append(ipv4_network.network)
for host in ipv4_network.iterhosts(): hosts.append(host)
return hosts
@staticmethod
def GetFirewallHostname(file_contents):
for line in file_contents:
p = re.search('hostname', line)
if p:
return line.split(' ')[1]
return None
@staticmethod
def IsIpaddressListMatch(iplist_1, iplist_2):
for ip1 in iplist_1:
possible_match = False
for ip2 in iplist_2:
if ip2.__contains__(ip1):
possible_match = True
break
if not possible_match: return False
return True
| |
#!/usr/bin/env python
"""
A newick/nexus file/string parser based on the ete3.parser.newick. Takes as
input a string or file that contains one or multiple lines that contain
newick strings. Lines that do not contain newick strings are ignored, unless
the #NEXUS is in the header in which case the 'translate' and 'trees' blocks
are parsed.
"""
import os
import re
import requests
from .TreeNode import TreeNode
from .utils import NW_FORMAT
# Regular expressions used for reading newick format
FLOAT_RE = r"\s*[+-]?\d+\.?\d*(?:[eE][-+]\d+)?\s*"
NAME_RE = r"[^():,;]+?"
NHX_RE = r"\[&&NHX:[^\]]*\]"
MB_BRLEN_RE = r"\[&B (\w+) [0-9.e-]+\]"
class NewickError(Exception):
"""Exception class designed for NewickIO errors."""
def __init__(self, value):
Exception.__init__(self, value)
class NexusError(Exception):
"""Exception class designed for NewickIO errors."""
def __init__(self, value):
Exception.__init__(self, value)
class FastTreeParser():
"""
A less flexible but faster newick parser for performance sensitive apps.
Only supports newick string input in format 0.
"""
def __init__(self, newick, tree_format):
self.data = newick
extractor = FastNewick2TreeNode(self.data, tree_format)
self.treenode = extractor.newick_from_string()
class TreeParser(object):
def __init__(self, intree, tree_format=0, multitree=False, debug=False):
"""
Reads input as a string or file, figures out format and parses it.
Formats 0-10 are newick formats supported by ete3.
Format 11 is nexus format from mrbayes.
Returns either a Toytree or MultiTree object, depending if input has
one or more trees.
"""
# the input file/stream and the loaded data
self.intree = intree
self.data = None
self.debug = debug
# the tree_format and parsed tree string from data
self.fmt = tree_format
self.multitree = multitree
self.newick = ""
# returned result: 1 tree for Toytree multiple trees for MultiTrees
self.treenodes = []
# newick translation dictionary
self.tdict = {}
# compiled re matchers for this tree format type
self.matcher = MATCHER[self.fmt]
# parse intree
if not self.debug:
self._run()
def _run(self):
# get newick from data and test newick structure
if self.intree:
# read data input by lines to .data
self.get_data_from_intree()
# check for NEXUS wrappings and update .data for newick strings
self.parse_nexus()
# raise warnings if tree_format doesn't seem right for data
self.warn_about_format()
# parse newick strings to treenodes list
self.get_treenodes()
# apply names from tdict
self.apply_name_translation()
# no input data
else:
self.treenodes = [TreeNode()]
def warn_about_format(self):
# warning about formats
if "[&&NHX" not in self.data[0]:
if ("[&" in self.data[0]) & (self.fmt != 10):
print("Warning: data looks like tree_format=10 (mrbayes-like)")
def get_data_from_intree(self):
"""
Load *data* from a file or string and return as a list of strings.
The data contents could be one newick string; a multiline NEXUS format
for one tree; multiple newick strings on multiple lines; or multiple
newick strings in a multiline NEXUS format. In any case, we will read
in the data as a list on lines.
"""
# load string: filename or data stream
if isinstance(self.intree, (str, bytes)):
# strip it
self.intree = self.intree.strip()
# is a URL: make a list by splitting a string
if any([i in self.intree for i in ("http://", "https://")]):
response = requests.get(self.intree)
response.raise_for_status()
self.data = response.text.strip().split("\n")
# is a file: read by lines to a list
elif os.path.exists(self.intree):
with open(self.intree, 'rU') as indata:
self.data = indata.readlines()
# is a string: make into a list by splitting
else:
self.data = self.intree.split("\n")
# load iterable: iterable of newick strings
elif isinstance(self.intree, (list, set, tuple)):
self.data = list(self.intree)
def parse_nexus(self):
"get newick data from NEXUS"
if self.data[0].strip().upper() == "#NEXUS":
nex = NexusParser(self.data)
self.data = nex.newicks
self.tdict = nex.tdict
def get_treenodes(self):
"test format of intree nex/nwk, extra features"
if not self.multitree:
# get TreeNodes from Newick
extractor = Newick2TreeNode(self.data[0].strip(), fmt=self.fmt)
# extract one tree
self.treenodes.append(extractor.newick_from_string())
else:
for tre in self.data:
# get TreeNodes from Newick
extractor = Newick2TreeNode(tre.strip(), fmt=self.fmt)
# extract one tree
self.treenodes.append(extractor.newick_from_string())
def apply_name_translation(self):
if self.tdict:
for tree in self.treenodes:
for node in tree.traverse():
if node.name in self.tdict:
node.name = self.tdict[node.name]
class Newick2TreeNode:
"Parse newick str to a TreeNode object"
def __init__(self, data, fmt=0):
self.data = data
self.root = TreeNode()
self.current_node = self.root
self.current_parent = None
self.fmt = fmt
self.cleanup_data()
def cleanup_data(self):
# check parentheses
if self.data.count('(') != self.data.count(')'):
raise NewickError('Parentheses do not match. Broken tree data.')
# remove white spaces and separators
self.data = re.sub(r"[\n\r\t ]+", "", self.data)
# mrbayes format terrible formatting hacks--------
if self.fmt == 10:
# convert bracket markers to NHX format
self.data = self.data.replace("[&", "[&&NHX:")
# replace commas inside feature strings with dashes
ns = ""
for chunk in self.data.split("{"):
if "}" in chunk:
pre, post = chunk.split("}", 1)
pre = pre.replace(",", "-")
ns += "{" + pre + "}" + post
else:
ns += chunk
self.data = ns
# replace parentheses inside brackets with curly braces
ns = ""
for chunk in self.data.split("["):
if "]" in chunk:
pre, post = chunk.split("]", 1)
pre = pre.replace("(", "{")
pre = pre.replace(")", "}")
pre = pre.replace(",", ":")
pre = pre.replace('"', "")
pre = pre.replace("'", "")
ns += "[" + pre + "]" + post
else:
ns += chunk
self.data = ns
def newick_from_string(self):
"Reads a newick string in the New Hampshire format."
# split on parentheses to traverse hierarchical tree structure
for chunk in self.data.split("(")[1:]:
# add child to make this node a parent.
self.current_parent = (
self.root if self.current_parent is None else
self.current_parent.add_child()
)
# get all parenth endings from this parenth start
subchunks = [ch.strip() for ch in chunk.split(",")]
if subchunks[-1] != '' and not subchunks[-1].endswith(';'):
raise NewickError(
'Broken newick structure at: {}'.format(chunk))
# Every closing parenthesis will close a node and go up one level.
for idx, leaf in enumerate(subchunks):
if leaf.strip() == '' and idx == len(subchunks) - 1:
continue
closing_nodes = leaf.split(")")
# parse features and apply to the node object
self.apply_node_data(closing_nodes[0], "leaf")
# next contain closing nodes and data about the internal nodes.
if len(closing_nodes) > 1:
for closing_internal in closing_nodes[1:]:
closing_internal = closing_internal.rstrip(";")
# read internal node data and go up one level
self.apply_node_data(closing_internal, "internal")
self.current_parent = self.current_parent.up
return self.root
def apply_node_data(self, subnw, node_type):
if node_type in ("leaf", "single"):
self.current_node = self.current_parent.add_child()
else:
self.current_node = self.current_parent
# if no feature data
subnw = subnw.strip()
if not subnw:
return
# load matcher junk
c1, c2, cv1, cv2, match = MATCHER[self.fmt].type[node_type]
# if beast or mb then combine brackets
if self.fmt == 10:
if "]:" not in subnw:
node, edge = subnw.split("]", 1)
subnw = node + "]:0.0" + edge
node, edge = subnw.split("]:")
npre, npost = node.split("[")
# mrbayes mode: (a[&a:1,b:2]:0.1[&c:10])
try:
epre, epost = edge.split("[")
subnw = "{}:{}[&&NHX:{}".format(
npre, epre, ":".join([npost[6:], epost[6:]]))
# BEAST mode: (a[&a:1,b:2,c:10]:0.1)
except ValueError:
subnw = "{}:{}[&&NHX:{}]".format(npre, edge, npost[6:])
# look for node features
data = re.match(match, subnw)
# if there are node features then add them to this node
if data:
data = data.groups()
# data should not be empty
if all([i is None for i in data]):
raise NewickError(
"Unexpected newick format {}".format(subnw))
# node has a name
if (data[0] is not None) and (data[0] != ''):
self.current_node.add_feature(c1, cv1(data[0]))
if (data[1] is not None) and (data[1] != ''):
self.current_node.add_feature(c2, cv2(data[1][1:]))
if (data[2] is not None) and data[2].startswith("[&&NHX"):
fdict = parse_nhx(data[2])
for fname, fvalue in fdict.items():
self.current_node.add_feature(fname, fvalue)
else:
raise NewickError("Unexpected newick format {}".format(subnw))
class NexusParser:
"""
Parse nexus file/str formatted data to extract tree data and features.
Expects '#NEXUS', 'begin trees', 'tree', and 'end;'.
"""
def __init__(self, data, debug=False):
self.data = data
self.newicks = []
self.tdict = {}
self.matcher = re.compile(MB_BRLEN_RE)
if not debug:
self.extract_tree_block()
def extract_tree_block(self):
"iterate through data file to extract trees"
# data SHOULD be a list of strings at this point
lines = iter(self.data)
while 1:
try:
line = next(lines).strip()
except StopIteration:
break
# oh mrbayes, you seriously allow spaces within newick format!?
# find "[&B TK02Brlens 8.123e-3]" and change to [&Brlen=8.123e-3]
# this is a tmp hack fix, to be replaced with a regex
line = line.replace(" TK02Brlens ", "=")
# enter trees block
if line.lower() == "begin trees;":
while 1:
# iter through trees block
nextline = next(lines).strip()
# remove horrible brlen string with spaces from mb
nextline = self.matcher.sub("", nextline)
# split into parts on spaces
sub = nextline.split()
# skip if a blank line
if not sub:
continue
# look for translation
elif sub[0].lower() == "translate":
while not sub[-1].endswith(";"):
sub = next(lines).strip().split()
self.tdict[sub[0]] = sub[-1].strip(",").strip(";")
# parse tree blocks
elif sub[0].lower().startswith("tree"):
self.newicks.append(sub[-1])
# end of trees block
elif sub[0].lower() == "end;":
break
# re matchers should all be compiled on toytree init
class Matchers:
def __init__(self, formatcode):
self.type = {}
for node_type in ["leaf", "single", "internal"]:
# (node_type == "leaf") or (node_type == "single"):
if node_type != "internal":
container1 = NW_FORMAT[formatcode][0][0]
container2 = NW_FORMAT[formatcode][1][0]
converterFn1 = NW_FORMAT[formatcode][0][1]
converterFn2 = NW_FORMAT[formatcode][1][1]
flexible1 = NW_FORMAT[formatcode][0][2]
flexible2 = NW_FORMAT[formatcode][1][2]
else:
container1 = NW_FORMAT[formatcode][2][0]
container2 = NW_FORMAT[formatcode][3][0]
converterFn1 = NW_FORMAT[formatcode][2][1]
converterFn2 = NW_FORMAT[formatcode][3][1]
flexible1 = NW_FORMAT[formatcode][2][2]
flexible2 = NW_FORMAT[formatcode][3][2]
if converterFn1 == str:
first_match = "({})".format(NAME_RE)
elif converterFn1 == float:
first_match = "({})".format(FLOAT_RE)
elif converterFn1 is None:
first_match = '()'
if converterFn2 == str:
second_match = "(:{})".format(NAME_RE)
elif converterFn2 == float:
second_match = "(:{})".format(FLOAT_RE)
elif converterFn2 is None:
second_match = '()'
if flexible1 and (node_type != 'leaf'):
first_match += "?"
if flexible2:
second_match += "?"
m0 = r"^\s*{first_match}"
m1 = r"\s*{second_match}"
m2 = r"\s*({NHX_RE})"
m3 = r"?\s*$"
matcher_str = (m0 + m1 + m2 + m3).format(**{
"first_match": first_match,
"second_match": second_match,
"NHX_RE": NHX_RE,
})
# matcher_str = r'^\s*{}\s*{}\s*({})?\s*$'.format(
# FIRST_MATCH, SECOND_MATCH, NHX_RE)
compiled_matcher = re.compile(matcher_str)
# fill matcher for this node
self.type[node_type] = [
container1,
container2,
converterFn1,
converterFn2,
compiled_matcher
]
def parse_messy_nexus(nexus):
"""
Approaches:
1: Parse the format to match NHX and then parse like normal NHX.
2. New parser to store all features and values as strings.
"""
def parse_nhx(NHX_string):
"""
NHX format: [&&NHX:prop1=value1:prop2=value2]
MB format: ((a[&Z=1,Y=2], b[&Z=1,Y=2]):1.0[&L=1,W=0], ...
"""
# store features
ndict = {}
# parse NHX or MB features
if "[&&NHX:" in NHX_string:
NHX_string = NHX_string.replace("[&&NHX:", "")
NHX_string = NHX_string.replace("]", "")
for field in NHX_string.split(":"):
try:
pname, pvalue = field.split("=")
ndict[pname] = pvalue
except ValueError as e:
raise NewickError('Invalid NHX format %s' % field)
return ndict
# GLOBAL RE COMPILED MATCHERS
MATCHER = {}
for formatcode in range(11):
MATCHER[formatcode] = Matchers(formatcode)
class FastNewick2TreeNode:
"Parse newick str to a TreeNode object"
def __init__(self, data, tree_format):
self.data = data
self.root = TreeNode()
self.current_node = self.root
self.current_parent = None
self.fmt = tree_format
self.data = re.sub(r"[\n\r\t ]+", "", self.data)
def newick_from_string(self):
"Reads a newick string in the New Hampshire format."
# split on parentheses to traverse hierarchical tree structure
for chunk in self.data.split("(")[1:]:
# add child to make this node a parent.
self.current_parent = (
self.root if self.current_parent is None else
self.current_parent.add_child()
)
# get all parenth endings from this parenth start
subchunks = [ch.strip() for ch in chunk.split(",")]
if subchunks[-1] != '' and not subchunks[-1].endswith(';'):
raise NewickError(
'Broken newick structure at: {}'.format(chunk))
# Every closing parenthesis will close a node and go up one level.
for idx, leaf in enumerate(subchunks):
if leaf.strip() == '' and idx == len(subchunks) - 1:
continue
closing_nodes = leaf.split(")")
# parse features and apply to the node object
self.apply_node_data(closing_nodes[0], "leaf")
# next contain closing nodes and data about the internal nodes.
if len(closing_nodes) > 1:
for closing_internal in closing_nodes[1:]:
closing_internal = closing_internal.rstrip(";")
# read internal node data and go up one level
self.apply_node_data(closing_internal, "internal")
self.current_parent = self.current_parent.up
return self.root
def apply_node_data(self, subnw, node_type):
if node_type in ("leaf", "single"):
self.current_node = self.current_parent.add_child()
else:
self.current_node = self.current_parent
# if no feature data
subnw = subnw.strip()
if not subnw:
return
# load matcher junk
c1, c2, cv1, cv2, match = MATCHER[self.fmt].type[node_type]
# look for node features
data = re.match(match, subnw)
# if there are node features then add them to this node
if data:
data = data.groups()
# node has a name
if (data[0] is not None) and (data[0] != ''):
self.current_node.add_feature(c1, cv1(data[0]))
if (data[1] is not None) and (data[1] != ''):
self.current_node.add_feature(c2, cv2(data[1][1:]))
else:
raise NewickError("Unexpected newick format {}".format(subnw))
| |
import collections
import glob
import hashlib
import json
import logging
import os
import re
import shutil
import stat
import StringIO
import tempfile
import zipfile
from cStringIO import StringIO as cStringIO
from datetime import datetime
from itertools import groupby
from xml.dom import minidom
from zipfile import BadZipfile, ZipFile
from django import forms
from django.conf import settings
from django.core.cache import cache
from django.core.files.storage import default_storage as storage
import rdflib
from tower import ugettext as _
import amo
from amo.utils import rm_local_tmp_dir
from applications.models import AppVersion
from versions.compare import version_int as vint
log = logging.getLogger('z.files.utils')
class ParseError(forms.ValidationError):
pass
VERSION_RE = re.compile('^[-+*.\w]{,32}$')
SIGNED_RE = re.compile('^META\-INF/(\w+)\.(rsa|sf)$')
# The default update URL.
default = (
'https://versioncheck.addons.mozilla.org/update/VersionCheck.php?'
'reqVersion=%REQ_VERSION%&id=%ITEM_ID%&version=%ITEM_VERSION%&'
'maxAppVersion=%ITEM_MAXAPPVERSION%&status=%ITEM_STATUS%&appID=%APP_ID%&'
'appVersion=%APP_VERSION%&appOS=%APP_OS%&appABI=%APP_ABI%&'
'locale=%APP_LOCALE%¤tAppVersion=%CURRENT_APP_VERSION%&'
'updateType=%UPDATE_TYPE%'
)
def get_filepath(fileorpath):
"""Get the actual file path of fileorpath if it's a FileUpload object."""
if hasattr(fileorpath, 'path'): # FileUpload
return fileorpath.path
return fileorpath
def get_file(fileorpath):
"""Get a file-like object, whether given a FileUpload object or a path."""
if hasattr(fileorpath, 'path'): # FileUpload
return storage.open(fileorpath.path)
if hasattr(fileorpath, 'name'):
return fileorpath
return storage.open(fileorpath)
def make_xpi(files):
f = cStringIO()
z = ZipFile(f, 'w')
for path, data in files.items():
z.writestr(path, data)
z.close()
f.seek(0)
return f
def is_beta(version):
"""Return True if the version is believed to be a beta version."""
return bool(amo.VERSION_BETA.search(version))
class Extractor(object):
"""Extract adon info from an install.rdf or package.json"""
App = collections.namedtuple('App', 'appdata id min max')
@classmethod
def parse(cls, path):
install_rdf = os.path.join(path, 'install.rdf')
package_json = os.path.join(path, 'package.json')
if os.path.exists(install_rdf):
return RDFExtractor(path).data
elif os.path.exists(package_json):
return PackageJSONExtractor(package_json).parse()
else:
raise forms.ValidationError("No install.rdf or package.json found")
class PackageJSONExtractor(object):
def __init__(self, path):
self.path = path
self.data = json.load(open(self.path))
def get(self, key, default=None):
return self.data.get(key, default)
def apps(self):
def find_appversion(app, version_req):
"""
Convert an app and a package.json style version requirement to an
`AppVersion`. This simply extracts the version number without the
><= requirement so it will not be accurate for version requirements
that are not >=, <= or = to a version.
>>> find_appversion(amo.APPS['firefox'], '>=33.0a1')
<AppVersion: 33.0a1>
"""
version = re.sub('>?=?<?', '', version_req)
try:
return AppVersion.objects.get(
application=app.id, version=version)
except AppVersion.DoesNotExist:
return None
for engine, version in self.get('engines', {}).items():
name = 'android' if engine == 'fennec' else engine
app = amo.APPS.get(name)
if app and app.guid in amo.APP_GUIDS:
appversion = find_appversion(app, version)
if appversion:
yield Extractor.App(
appdata=app, id=app.id, min=appversion, max=appversion)
def parse(self):
return {
'guid': self.get('id') or self.get('name'),
'type': amo.ADDON_EXTENSION,
'name': self.get('title') or self.get('name'),
'version': self.get('version'),
'homepage': self.get('homepage'),
'summary': self.get('description'),
'no_restart': True,
'apps': list(self.apps()),
}
class RDFExtractor(object):
"""Extract add-on info from an install.rdf."""
TYPES = {'2': amo.ADDON_EXTENSION, '4': amo.ADDON_THEME,
'8': amo.ADDON_LPAPP, '64': amo.ADDON_DICT}
manifest = u'urn:mozilla:install-manifest'
def __init__(self, path):
self.path = path
install_rdf_path = os.path.join(path, 'install.rdf')
self.rdf = rdflib.Graph().parse(open(install_rdf_path))
self.package_type = None
self.find_root()
self.data = {
'guid': self.find('id'),
'type': self.find_type(),
'name': self.find('name'),
'version': self.find('version'),
'homepage': self.find('homepageURL'),
'summary': self.find('description'),
'no_restart':
self.find('bootstrap') == 'true' or self.find('type') == '64',
'strict_compatibility': self.find('strictCompatibility') == 'true',
'apps': self.apps(),
'is_multi_package': self.package_type == '32',
}
def find_type(self):
# If the extension declares a type that we know about, use
# that.
# https://developer.mozilla.org/en-US/Add-ons/Install_Manifests#type
self.package_type = self.find('type')
if self.package_type and self.package_type in self.TYPES:
return self.TYPES[self.package_type]
# Look for Complete Themes.
if self.path.endswith('.jar') or self.find('internalName'):
return amo.ADDON_THEME
# Look for dictionaries.
dic = os.path.join(self.path, 'dictionaries')
if os.path.exists(dic) and glob.glob('%s/*.dic' % dic):
return amo.ADDON_DICT
# Consult <em:type>.
return self.TYPES.get(self.package_type, amo.ADDON_EXTENSION)
def uri(self, name):
namespace = 'http://www.mozilla.org/2004/em-rdf'
return rdflib.term.URIRef('%s#%s' % (namespace, name))
def find_root(self):
# If the install-manifest root is well-defined, it'll show up when we
# search for triples with it. If not, we have to find the context that
# defines the manifest and use that as our root.
# http://www.w3.org/TR/rdf-concepts/#section-triples
manifest = rdflib.term.URIRef(self.manifest)
if list(self.rdf.triples((manifest, None, None))):
self.root = manifest
else:
self.root = self.rdf.subjects(None, self.manifest).next()
def find(self, name, ctx=None):
"""Like $() for install.rdf, where name is the selector."""
if ctx is None:
ctx = self.root
# predicate it maps to <em:{name}>.
match = list(self.rdf.objects(ctx, predicate=self.uri(name)))
# These come back as rdflib.Literal, which subclasses unicode.
if match:
return unicode(match[0])
def apps(self):
rv = []
for ctx in self.rdf.objects(None, self.uri('targetApplication')):
app = amo.APP_GUIDS.get(self.find('id', ctx))
if not app:
continue
if app.guid not in amo.APP_GUIDS:
continue
try:
qs = AppVersion.objects.filter(application=app.id)
min = qs.get(version=self.find('minVersion', ctx))
max = qs.get(version=self.find('maxVersion', ctx))
except AppVersion.DoesNotExist:
continue
rv.append(Extractor.App(appdata=app, id=app.id, min=min, max=max))
return rv
def extract_search(content):
rv = {}
dom = minidom.parse(content)
def text(x):
return dom.getElementsByTagName(x)[0].childNodes[0].wholeText
rv['name'] = text('ShortName')
rv['description'] = text('Description')
return rv
def parse_search(fileorpath, addon=None):
try:
f = get_file(fileorpath)
data = extract_search(f)
except forms.ValidationError:
raise
except Exception:
log.error('OpenSearch parse error', exc_info=True)
raise forms.ValidationError(_('Could not parse uploaded file.'))
return {'guid': None,
'type': amo.ADDON_SEARCH,
'name': data['name'],
'summary': data['description'],
'version': datetime.now().strftime('%Y%m%d')}
class SafeUnzip(object):
def __init__(self, source, mode='r'):
self.source = source
self.info = None
self.mode = mode
def is_valid(self, fatal=True):
"""
Runs some overall archive checks.
fatal: if the archive is not valid and fatal is True, it will raise
an error, otherwise it will return False.
"""
try:
zip = zipfile.ZipFile(self.source, self.mode)
except (BadZipfile, IOError):
if fatal:
log.info('Error extracting', exc_info=True)
raise
return False
_info = zip.infolist()
for info in _info:
if '..' in info.filename or info.filename.startswith('/'):
log.error('Extraction error, invalid file name (%s) in '
'archive: %s' % (info.filename, self.source))
# L10n: {0} is the name of the invalid file.
raise forms.ValidationError(
_('Invalid file name in archive: {0}').format(
info.filename))
if info.file_size > settings.FILE_UNZIP_SIZE_LIMIT:
log.error('Extraction error, file too big (%s) for file (%s): '
'%s' % (self.source, info.filename, info.file_size))
# L10n: {0} is the name of the invalid file.
raise forms.ValidationError(
_('File exceeding size limit in archive: {0}').format(
info.filename))
self.info = _info
self.zip = zip
return True
def is_signed(self):
"""Tells us if an addon is signed."""
finds = []
for info in self.info:
match = SIGNED_RE.match(info.filename)
if match:
name, ext = match.groups()
# If it's rsa or sf, just look for the opposite.
if (name, {'rsa': 'sf', 'sf': 'rsa'}[ext]) in finds:
return True
finds.append((name, ext))
def extract_from_manifest(self, manifest):
"""
Extracts a file given a manifest such as:
jar:chrome/de.jar!/locale/de/browser/
or
locale/de/browser
"""
type, path = manifest.split(':')
jar = self
if type == 'jar':
parts = path.split('!')
for part in parts[:-1]:
jar = self.__class__(StringIO.StringIO(jar.zip.read(part)))
jar.is_valid(fatal=True)
path = parts[-1]
return jar.extract_path(path[1:] if path.startswith('/') else path)
def extract_path(self, path):
"""Given a path, extracts the content at path."""
return self.zip.read(path)
def extract_info_to_dest(self, info, dest):
"""Extracts the given info to a directory and checks the file size."""
self.zip.extract(info, dest)
dest = os.path.join(dest, info.filename)
if not os.path.isdir(dest):
# Directories consistently report their size incorrectly.
size = os.stat(dest)[stat.ST_SIZE]
if size != info.file_size:
log.error('Extraction error, uncompressed size: %s, %s not %s'
% (self.source, size, info.file_size))
raise forms.ValidationError(_('Invalid archive.'))
def extract_to_dest(self, dest):
"""Extracts the zip file to a directory."""
for info in self.info:
self.extract_info_to_dest(info, dest)
def close(self):
self.zip.close()
def extract_zip(source, remove=False, fatal=True):
"""Extracts the zip file. If remove is given, removes the source file."""
tempdir = tempfile.mkdtemp()
zip = SafeUnzip(source)
try:
if zip.is_valid(fatal):
zip.extract_to_dest(tempdir)
except:
rm_local_tmp_dir(tempdir)
raise
if remove:
os.remove(source)
return tempdir
def copy_over(source, dest):
"""
Copies from the source to the destination, removing the destination
if it exists and is a directory.
"""
if os.path.exists(dest) and os.path.isdir(dest):
shutil.rmtree(dest)
shutil.copytree(source, dest)
# mkdtemp will set the directory permissions to 700
# for the webserver to read them, we need 755
os.chmod(dest, stat.S_IRWXU | stat.S_IRGRP |
stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
shutil.rmtree(source)
def extract_xpi(xpi, path, expand=False):
"""
If expand is given, will look inside the expanded file
and find anything in the whitelist and try and expand it as well.
It will do up to 10 iterations, after that you are on your own.
It will replace the expanded file with a directory and the expanded
contents. If you have 'foo.jar', that contains 'some-image.jpg', then
it will create a folder, foo.jar, with an image inside.
"""
expand_whitelist = ['.jar', '.xpi']
tempdir = extract_zip(xpi)
if expand:
for x in xrange(0, 10):
flag = False
for root, dirs, files in os.walk(tempdir):
for name in files:
if os.path.splitext(name)[1] in expand_whitelist:
src = os.path.join(root, name)
if not os.path.isdir(src):
dest = extract_zip(src, remove=True, fatal=False)
if dest:
copy_over(dest, src)
flag = True
if not flag:
break
copy_over(tempdir, path)
def parse_xpi(xpi, addon=None, check=True):
"""Extract and parse an XPI."""
# Extract to /tmp
path = tempfile.mkdtemp()
try:
xpi = get_file(xpi)
extract_xpi(xpi, path)
xpi_info = Extractor.parse(path)
except forms.ValidationError:
raise
except IOError as e:
if len(e.args) < 2:
errno, strerror = None, e[0]
else:
errno, strerror = e
log.error('I/O error({0}): {1}'.format(errno, strerror))
raise forms.ValidationError(_('Could not parse install.rdf.'))
except Exception:
log.error('XPI parse error', exc_info=True)
raise forms.ValidationError(_('Could not parse install.rdf.'))
finally:
rm_local_tmp_dir(path)
if check:
return check_xpi_info(xpi_info, addon)
else:
return xpi_info
def check_xpi_info(xpi_info, addon=None):
from addons.models import Addon, BlacklistedGuid
if not xpi_info['guid']:
raise forms.ValidationError(_("Could not find a UUID."))
if addon and addon.guid != xpi_info['guid']:
raise forms.ValidationError(_("UUID doesn't match add-on."))
if (not addon
and Addon.with_unlisted.filter(guid=xpi_info['guid']).exists()
or BlacklistedGuid.objects.filter(guid=xpi_info['guid']).exists()):
raise forms.ValidationError(_('Duplicate UUID found.'))
if len(xpi_info['version']) > 32:
raise forms.ValidationError(
_('Version numbers should have fewer than 32 characters.'))
if not VERSION_RE.match(xpi_info['version']):
raise forms.ValidationError(
_('Version numbers should only contain letters, numbers, '
'and these punctuation characters: +*.-_.'))
return xpi_info
def parse_addon(pkg, addon=None, check=True):
"""
pkg is a filepath or a django.core.files.UploadedFile
or files.models.FileUpload.
"""
name = getattr(pkg, 'name', pkg)
if name.endswith('.xml'):
parsed = parse_search(pkg, addon)
else:
parsed = parse_xpi(pkg, addon, check)
if addon and addon.type != parsed['type']:
raise forms.ValidationError(_("<em:type> doesn't match add-on"))
return parsed
def _get_hash(filename, block_size=2 ** 20, hash=hashlib.md5):
"""Returns an MD5 hash for a filename."""
f = open(filename, 'rb')
hash_ = hash()
while True:
data = f.read(block_size)
if not data:
break
hash_.update(data)
return hash_.hexdigest()
def get_md5(filename, **kw):
return _get_hash(filename, **kw)
def get_sha256(filename, **kw):
return _get_hash(filename, hash=hashlib.sha256, **kw)
def find_jetpacks(minver, maxver):
"""
Find all jetpack files that aren't disabled.
Files that should be upgraded will have needs_upgrade=True.
"""
from .models import File
statuses = amo.VALID_STATUSES
files = (File.objects.filter(jetpack_version__isnull=False,
version__addon__auto_repackage=True,
version__addon__status__in=statuses,
version__addon__disabled_by_user=False)
.exclude(status=amo.STATUS_DISABLED).no_cache()
.select_related('version'))
files = sorted(files, key=lambda f: (f.version.addon_id, f.version.id))
# Figure out which files need to be upgraded.
for file_ in files:
file_.needs_upgrade = False
# If any files for this add-on are reviewed, take the last reviewed file
# plus all newer files. Otherwise, only upgrade the latest file.
for _group, fs in groupby(files, key=lambda f: f.version.addon_id):
fs = list(fs)
if any(f.status in amo.REVIEWED_STATUSES for f in fs):
for file_ in reversed(fs):
file_.needs_upgrade = True
if file_.status in amo.REVIEWED_STATUSES:
break
else:
fs[-1].needs_upgrade = True
# Make sure only old files are marked.
for file_ in [f for f in files if f.needs_upgrade]:
if not (vint(minver) <= vint(file_.jetpack_version) < vint(maxver)):
file_.needs_upgrade = False
return files
class JetpackUpgrader(object):
"""A little manager for jetpack upgrade data in memcache."""
prefix = 'admin:jetpack:upgrade:'
def __init__(self):
self.version_key = self.prefix + 'version'
self.file_key = self.prefix + 'files'
self.jetpack_key = self.prefix + 'jetpack'
def jetpack_versions(self, min_=None, max_=None):
if None not in (min_, max_):
d = {'min': min_, 'max': max_}
return cache.set(self.jetpack_key, d)
d = cache.get(self.jetpack_key, {})
return d.get('min'), d.get('max')
def version(self, val=None):
if val is not None:
return cache.add(self.version_key, val)
return cache.get(self.version_key)
def files(self, val=None):
if val is not None:
current = cache.get(self.file_key, {})
current.update(val)
return cache.set(self.file_key, val)
return cache.get(self.file_key, {})
def file(self, file_id, val=None):
file_id = int(file_id)
if val is not None:
current = cache.get(self.file_key, {})
current[file_id] = val
cache.set(self.file_key, current)
return val
return cache.get(self.file_key, {}).get(file_id, {})
def cancel(self):
cache.delete(self.version_key)
newfiles = dict([(k, v) for (k, v) in self.files().items()
if v.get('owner') != 'bulk'])
cache.set(self.file_key, newfiles)
def finish(self, file_id):
file_id = int(file_id)
newfiles = dict([(k, v) for (k, v) in self.files().items()
if k != file_id])
cache.set(self.file_key, newfiles)
if not newfiles:
cache.delete(self.version_key)
| |
#!/usr/bin/python
# web service, so return only JSON (no HTML)
from flask import Flask, jsonify, request, url_for, make_response, render_template, send_file
import sqlite3
import interface_db as d
import os.path
import urlparse
import argparse
import textwrap
import functools # need to wrap own decorators to comply with flask views
import zipfile
from io import BytesIO
try:
from flask.ext.cors import CORS # The typical way to import flask-cors
except ImportError:
# Path hack allows examples to be run without installation.
import os
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.insert(0, parentdir)
from flask_cors import CORS
app = Flask(__name__)
app.debug=False
if not app.debug:
print("adding logger")
import logging
from logging import FileHandler
from logging import Formatter
data_dir = os.path.expanduser('~/benchtracker_data/')
if not os.path.isdir(data_dir):
os.makedirs(data_dir)
file_handler = FileHandler(os.path.join(data_dir, 'log.txt'))
file_handler.setFormatter(Formatter(
'%(asctime)s %(levelname)s: %(message)s '
'[in %(pathname)s:%(lineno)d'
))
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_handler)
cors = CORS(app)
port = 5000
database = None
root_directory = None
def parse_args(ns=None):
"""parse arguments from command line and return as namespace object"""
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent("""\
serve a central database with benchmark information
Generated database:
Database should be created by populate_db.py, with each task
organized as a table. A task is a collection of related benchmarks
that are commonly run together."""),
usage="%(prog)s [OPTIONS]")
parser.add_argument("-d", "--database",
default="results.db",
help="name of database to store results in; default: %(default)s")
parser.add_argument("-r", "--root_directory",
default="~/benchtracker_data/",
help="name of the directory to store databases in; default: %(default)s")
parser.add_argument("-p", "--port",
default=5000,
type=int,
help="port number to listen on; default: %(default)s")
params = parser.parse_args(namespace=ns)
global database, port, root_directory
root_directory = os.path.expanduser(params.root_directory)
database = os.path.expanduser(params.database)
port = params.port
return params
def catch_operation_errors(func):
@functools.wraps(func)
def task_checker(*args, **kwargs):
try:
return func(*args, **kwargs)
except IOError as e:
return jsonify({'status': 'File does not exist! ({})'.format(e)})
except IndexError:
return jsonify({'status': 'Index out of bounds! (likely table index)'})
except sqlite3.OperationalError as e:
return jsonify({'status': 'Malformed request! ({})'.format(e)})
return task_checker
# each URI should be a noun since it is a resource (vs a verb for most library functions)
@app.route('/')
@app.route('/tasks', methods=['GET'])
@catch_operation_errors
def get_tasks():
database = parse_db()
return jsonify({'tasks':d.list_tasks(database), 'database':database})
@app.route('/db', methods=['GET'])
def get_database():
return jsonify({'database':database})
@app.route('/param', methods=['GET'])
@catch_operation_errors
def get_param_desc():
database = parse_db()
tasks = parse_tasks()
param = request.args.get('p')
mode = request.args.get('m', 'range') # by default give ranges, overriden if param is text
try:
(param_type, param_val) = d.describe_param(param, mode, tasks, real_db(database))
except ValueError as e:
return jsonify({'status': 'Parameter value error: {}'.format(e)})
return jsonify({'status': 'OK',
'database':database,
'tasks':tasks,
'param': param,
'type': param_type,
'val': param_val})
@app.route('/params/', methods=['GET'])
@catch_operation_errors
def get_shared_params():
database = parse_db()
tasks = parse_tasks()
params = d.describe_tasks(tasks, real_db(database))
return jsonify({'status': 'OK', 'database':database, 'tasks':tasks, 'params': params})
@app.route('/data', methods=['GET'])
@catch_operation_errors
def get_filtered_data():
(exception, payload) = parse_data()
if exception:
return payload
else:
(databaes, tasks, params, data) = payload
return jsonify({'status': 'OK',
'database':database,
'tasks':tasks,
'params':params,
'data':data})
@app.route('/csv', methods=['GET'])
@catch_operation_errors
def get_csv_data():
"""Return a zipped archive of csv files for selected tasks"""
(exception, payload) = parse_data()
if exception:
return payload
else:
(database, tasks, params, data) = payload
memory_file = BytesIO()
with zipfile.ZipFile(memory_file, 'a', zipfile.ZIP_DEFLATED) as zf:
t = 0
for csvf in d.export_data_csv(params, data):
# characters the filesystem might complain about (/|) are replaced
zf.writestr("benchmark_results/" + tasks[t].replace('/','.').replace('|','__'), csvf.getvalue())
t += 1
# prepare to send over network
memory_file.seek(0)
return send_file(memory_file, attachment_filename="benchmark_results.zip", as_attachment=True)
@app.route('/view')
@catch_operation_errors
def get_view():
database = parse_db()
print(real_db(database))
tasks = {task_name: task_context for (task_name, task_context) in [t.split('|',1) for t in d.list_tasks(real_db(database))]}
queried_tasks = parse_tasks()
x = y = filters = ""
# only pass other argument values if valid tasks selected
if queried_tasks:
x = request.args.get('x')
y = request.args.get('y')
(temp, filters) = parse_filters(verbose=True)
return render_template('viewer.html',
database=database,
tasks=tasks,
queried_tasks=queried_tasks,
queried_x = x,
queried_y = y,
filters = filters)
@app.errorhandler(404)
def not_found(error):
resp = jsonify({'error': 'Not found'})
resp.status_code = 404
return resp
# library call knows path to database, web viewer doesn't for security reasons
def real_db(relative_db):
return os.path.join(root_directory, relative_db)
# should always be run before all other querying since it determines where to look from
def parse_db():
db = request.args.get('db')
if db:
return db
# default to the global database
return database
def parse_tasks():
tasks = request.args.getlist('t')
if tasks and tasks[0].isdigit():
all_tasks = d.list_tasks(database)
tasks = [all_tasks[int(t)] for t in tasks]
return tasks
def parse_filters(verbose=False):
"""
Parse filter from current request query string and return the filtered parameters and filters in a list
verbose mode returns filters without splitting out the type
"""
filter_param = None
filter_method = None
filters = []
filter_args = []
filter_params = []
for arg in urlparse.parse_qsl(request.query_string):
if arg[0][0] != 'f':
continue
# new filter parameter
if arg[0] == 'fp':
# previous filter ready to be built
if filter_param and filter_method and filter_args:
filters.append(d.Task_filter(filter_param, filter_method, filter_args))
filter_args = [] # clear arguments; important!
print("{}: {}".format(filters[-1], filters[-1].args))
filter_params.append(filter_param)
# split out the optional type following parameter name
if verbose:
filter_param = arg[1]
else:
filter_param = arg[1].split()[0]
if arg[0] == 'fm':
filter_method = arg[1]
if arg[0] == 'fa':
filter_args.append(arg[1])
# last filter to be added
if (not filters or filter_param != filters[-1].param) and filter_args:
filters.append(d.Task_filter(filter_param, filter_method, filter_args))
print("{}: {}".format(filters[-1], filters[-1].args))
filter_params.append(filter_param)
return filter_params,filters
def parse_data():
"""
Parses request for data and returns a 2-tuple payload.
First item is True for an exception occurance, with the 2nd item being the json response for error.
Else false for no exception occruance, with second item being a 3-tuple.
"""
database = parse_db()
# split to get name only in case type is also given
x_param = request.args.get('x')
y_param = request.args.get('y')
if not x_param:
return (True, jsonify({'status': 'Missing x parameter!'}))
if not y_param:
return (True, jsonify({'status': 'Missing y parameter!'}))
x_param = x_param.split()[0]
y_param = y_param.split()[0]
try:
(filtered_params, filters) = parse_filters()
except IndexError:
return (True, jsonify({'status': 'Incomplete filter arguments!'}))
except ValueError:
return (True, jsonify({'status': 'Unsupported filter method!'}))
tasks = parse_tasks()
(params, data) = d.retrieve_data(x_param, y_param, filters, tasks, real_db(database))
return (False, (database, tasks, params, data))
if __name__ == '__main__':
parse_args()
app.run(host='0.0.0.0', port=port)
| |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Unit tests for ComputeManager()."""
import contextlib
import time
from eventlet import event as eventlet_event
import mock
import mox
from oslo.config import cfg
from nova.compute import power_state
from nova.compute import task_states
from nova.compute import utils as compute_utils
from nova.compute import vm_states
from nova.conductor import rpcapi as conductor_rpcapi
from nova import context
from nova import db
from nova import exception
from nova.network import model as network_model
from nova.objects import base as obj_base
from nova.objects import block_device as block_device_obj
from nova.objects import external_event as external_event_obj
from nova.objects import instance as instance_obj
from nova.objects import migration as migration_obj
from nova.openstack.common import importutils
from nova.openstack.common import uuidutils
from nova import test
from nova.tests.compute import fake_resource_tracker
from nova.tests import fake_block_device
from nova.tests import fake_instance
from nova.tests.objects import test_instance_info_cache
CONF = cfg.CONF
CONF.import_opt('compute_manager', 'nova.service')
class ComputeManagerUnitTestCase(test.NoDBTestCase):
def setUp(self):
super(ComputeManagerUnitTestCase, self).setUp()
self.compute = importutils.import_object(CONF.compute_manager)
self.context = context.RequestContext('fake', 'fake')
def test_allocate_network_succeeds_after_retries(self):
self.flags(network_allocate_retries=8)
nwapi = self.compute.network_api
self.mox.StubOutWithMock(nwapi, 'allocate_for_instance')
self.mox.StubOutWithMock(self.compute, '_instance_update')
self.mox.StubOutWithMock(time, 'sleep')
instance = fake_instance.fake_db_instance(system_metadata={})
is_vpn = 'fake-is-vpn'
req_networks = 'fake-req-networks'
macs = 'fake-macs'
sec_groups = 'fake-sec-groups'
final_result = 'meow'
dhcp_options = None
expected_sleep_times = [1, 2, 4, 8, 16, 30, 30, 30]
for sleep_time in expected_sleep_times:
nwapi.allocate_for_instance(
self.context, instance, vpn=is_vpn,
requested_networks=req_networks, macs=macs,
security_groups=sec_groups,
dhcp_options=dhcp_options).AndRaise(
test.TestingException())
time.sleep(sleep_time)
nwapi.allocate_for_instance(
self.context, instance, vpn=is_vpn,
requested_networks=req_networks, macs=macs,
security_groups=sec_groups,
dhcp_options=dhcp_options).AndReturn(final_result)
self.compute._instance_update(self.context, instance['uuid'],
system_metadata={'network_allocated': 'True'})
self.mox.ReplayAll()
res = self.compute._allocate_network_async(self.context, instance,
req_networks,
macs,
sec_groups,
is_vpn,
dhcp_options)
self.assertEqual(final_result, res)
def test_allocate_network_fails(self):
self.flags(network_allocate_retries=0)
nwapi = self.compute.network_api
self.mox.StubOutWithMock(nwapi, 'allocate_for_instance')
instance = {}
is_vpn = 'fake-is-vpn'
req_networks = 'fake-req-networks'
macs = 'fake-macs'
sec_groups = 'fake-sec-groups'
dhcp_options = None
nwapi.allocate_for_instance(
self.context, instance, vpn=is_vpn,
requested_networks=req_networks, macs=macs,
security_groups=sec_groups,
dhcp_options=dhcp_options).AndRaise(test.TestingException())
self.mox.ReplayAll()
self.assertRaises(test.TestingException,
self.compute._allocate_network_async,
self.context, instance, req_networks, macs,
sec_groups, is_vpn, dhcp_options)
def test_allocate_network_neg_conf_value_treated_as_zero(self):
self.flags(network_allocate_retries=-1)
nwapi = self.compute.network_api
self.mox.StubOutWithMock(nwapi, 'allocate_for_instance')
instance = {}
is_vpn = 'fake-is-vpn'
req_networks = 'fake-req-networks'
macs = 'fake-macs'
sec_groups = 'fake-sec-groups'
dhcp_options = None
# Only attempted once.
nwapi.allocate_for_instance(
self.context, instance, vpn=is_vpn,
requested_networks=req_networks, macs=macs,
security_groups=sec_groups,
dhcp_options=dhcp_options).AndRaise(test.TestingException())
self.mox.ReplayAll()
self.assertRaises(test.TestingException,
self.compute._allocate_network_async,
self.context, instance, req_networks, macs,
sec_groups, is_vpn, dhcp_options)
def test_init_host(self):
our_host = self.compute.host
fake_context = 'fake-context'
inst = fake_instance.fake_db_instance(
vm_state=vm_states.ACTIVE,
info_cache=dict(test_instance_info_cache.fake_info_cache,
network_info=None),
security_groups=None)
startup_instances = [inst, inst, inst]
def _do_mock_calls(defer_iptables_apply):
self.compute.driver.init_host(host=our_host)
context.get_admin_context().AndReturn(fake_context)
db.instance_get_all_by_host(
fake_context, our_host, columns_to_join=['info_cache'],
use_slave=False
).AndReturn(startup_instances)
if defer_iptables_apply:
self.compute.driver.filter_defer_apply_on()
self.compute._destroy_evacuated_instances(fake_context)
self.compute._init_instance(fake_context,
mox.IsA(instance_obj.Instance))
self.compute._init_instance(fake_context,
mox.IsA(instance_obj.Instance))
self.compute._init_instance(fake_context,
mox.IsA(instance_obj.Instance))
if defer_iptables_apply:
self.compute.driver.filter_defer_apply_off()
self.mox.StubOutWithMock(self.compute.driver, 'init_host')
self.mox.StubOutWithMock(self.compute.driver,
'filter_defer_apply_on')
self.mox.StubOutWithMock(self.compute.driver,
'filter_defer_apply_off')
self.mox.StubOutWithMock(db, 'instance_get_all_by_host')
self.mox.StubOutWithMock(context, 'get_admin_context')
self.mox.StubOutWithMock(self.compute,
'_destroy_evacuated_instances')
self.mox.StubOutWithMock(self.compute,
'_init_instance')
# Test with defer_iptables_apply
self.flags(defer_iptables_apply=True)
_do_mock_calls(True)
self.mox.ReplayAll()
self.compute.init_host()
self.mox.VerifyAll()
# Test without defer_iptables_apply
self.mox.ResetAll()
self.flags(defer_iptables_apply=False)
_do_mock_calls(False)
self.mox.ReplayAll()
self.compute.init_host()
# tearDown() uses context.get_admin_context(), so we have
# to do the verification here and unstub it.
self.mox.VerifyAll()
self.mox.UnsetStubs()
@mock.patch('nova.objects.instance.InstanceList')
def test_cleanup_host(self, mock_instance_list):
# just testing whether the cleanup_host method
# when fired will invoke the underlying driver's
# equivalent method.
mock_instance_list.get_by_host.return_value = []
with mock.patch.object(self.compute, 'driver') as mock_driver:
self.compute.init_host()
mock_driver.init_host.assert_called_once()
self.compute.cleanup_host()
mock_driver.cleanup_host.assert_called_once()
def test_init_host_with_deleted_migration(self):
our_host = self.compute.host
not_our_host = 'not-' + our_host
fake_context = 'fake-context'
deleted_instance = instance_obj.Instance(host=not_our_host,
uuid='fake-uuid',
task_state=None)
self.mox.StubOutWithMock(self.compute.driver, 'init_host')
self.mox.StubOutWithMock(self.compute.driver, 'destroy')
self.mox.StubOutWithMock(db, 'instance_get_all_by_host')
self.mox.StubOutWithMock(context, 'get_admin_context')
self.mox.StubOutWithMock(self.compute, 'init_virt_events')
self.mox.StubOutWithMock(self.compute, '_get_instances_on_driver')
self.mox.StubOutWithMock(self.compute, '_init_instance')
self.mox.StubOutWithMock(self.compute, '_get_instance_nw_info')
self.compute.driver.init_host(host=our_host)
context.get_admin_context().AndReturn(fake_context)
db.instance_get_all_by_host(fake_context, our_host,
columns_to_join=['info_cache'],
use_slave=False
).AndReturn([])
self.compute.init_virt_events()
# simulate failed instance
self.compute._get_instances_on_driver(
fake_context, {'deleted': False}).AndReturn([deleted_instance])
self.compute._get_instance_nw_info(fake_context, deleted_instance
).AndRaise(exception.InstanceNotFound(
instance_id=deleted_instance['uuid']))
# ensure driver.destroy is called so that driver may
# clean up any dangling files
self.compute.driver.destroy(fake_context, deleted_instance,
mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg())
self.mox.ReplayAll()
self.compute.init_host()
# tearDown() uses context.get_admin_context(), so we have
# to do the verification here and unstub it.
self.mox.VerifyAll()
self.mox.UnsetStubs()
def test_init_instance_failed_resume_sets_error(self):
instance = fake_instance.fake_instance_obj(
self.context,
uuid='fake-uuid',
info_cache=None,
power_state=power_state.RUNNING,
vm_state=vm_states.ACTIVE,
task_state=None,
expected_attrs=['info_cache'])
self.flags(resume_guests_state_on_host_boot=True)
self.mox.StubOutWithMock(self.compute, '_get_power_state')
self.mox.StubOutWithMock(self.compute.driver, 'plug_vifs')
self.mox.StubOutWithMock(self.compute.driver,
'resume_state_on_host_boot')
self.mox.StubOutWithMock(self.compute,
'_get_instance_block_device_info')
self.mox.StubOutWithMock(self.compute,
'_set_instance_error_state')
self.compute._get_power_state(mox.IgnoreArg(),
instance).AndReturn(power_state.SHUTDOWN)
self.compute._get_power_state(mox.IgnoreArg(),
instance).AndReturn(power_state.SHUTDOWN)
self.compute._get_power_state(mox.IgnoreArg(),
instance).AndReturn(power_state.SHUTDOWN)
self.compute.driver.plug_vifs(instance, mox.IgnoreArg())
self.compute._get_instance_block_device_info(mox.IgnoreArg(),
instance).AndReturn('fake-bdm')
self.compute.driver.resume_state_on_host_boot(mox.IgnoreArg(),
instance, mox.IgnoreArg(),
'fake-bdm').AndRaise(test.TestingException)
self.compute._set_instance_error_state(mox.IgnoreArg(),
instance['uuid'])
self.mox.ReplayAll()
self.compute._init_instance('fake-context', instance)
def test_init_instance_stuck_in_deleting(self):
instance = fake_instance.fake_instance_obj(
self.context,
uuid='fake-uuid',
power_state=power_state.RUNNING,
vm_state=vm_states.ACTIVE,
task_state=task_states.DELETING)
self.mox.StubOutWithMock(block_device_obj.BlockDeviceMappingList,
'get_by_instance_uuid')
self.mox.StubOutWithMock(self.compute, '_delete_instance')
self.mox.StubOutWithMock(instance, 'obj_load_attr')
bdms = []
instance.obj_load_attr('metadata')
instance.obj_load_attr('system_metadata')
block_device_obj.BlockDeviceMappingList.get_by_instance_uuid(
self.context, instance.uuid).AndReturn(bdms)
self.compute._delete_instance(self.context, instance, bdms)
self.mox.ReplayAll()
self.compute._init_instance(self.context, instance)
def _test_init_instance_reverts_crashed_migrations(self,
old_vm_state=None):
power_on = True if (not old_vm_state or
old_vm_state == vm_states.ACTIVE) else False
sys_meta = {
'old_vm_state': old_vm_state
}
instance = fake_instance.fake_instance_obj(
self.context,
uuid='foo',
vm_state=vm_states.ERROR,
task_state=task_states.RESIZE_MIGRATING,
power_state=power_state.SHUTDOWN,
system_metadata=sys_meta,
expected_attrs=['system_metadata'])
self.mox.StubOutWithMock(compute_utils, 'get_nw_info_for_instance')
self.mox.StubOutWithMock(self.compute.driver, 'plug_vifs')
self.mox.StubOutWithMock(self.compute.driver,
'finish_revert_migration')
self.mox.StubOutWithMock(self.compute,
'_get_instance_block_device_info')
self.mox.StubOutWithMock(self.compute.driver, 'get_info')
self.mox.StubOutWithMock(instance, 'save')
self.mox.StubOutWithMock(self.compute, '_retry_reboot')
self.compute._retry_reboot(self.context, instance).AndReturn(
(False, None))
compute_utils.get_nw_info_for_instance(instance).AndReturn(
network_model.NetworkInfo())
self.compute.driver.plug_vifs(instance, [])
self.compute._get_instance_block_device_info(
self.context, instance).AndReturn([])
self.compute.driver.finish_revert_migration(self.context, instance,
[], [], power_on)
instance.save()
self.compute.driver.get_info(instance).AndReturn(
{'state': power_state.SHUTDOWN})
self.compute.driver.get_info(instance).AndReturn(
{'state': power_state.SHUTDOWN})
self.mox.ReplayAll()
self.compute._init_instance(self.context, instance)
self.assertIsNone(instance.task_state)
def test_init_instance_reverts_crashed_migration_from_active(self):
self._test_init_instance_reverts_crashed_migrations(
old_vm_state=vm_states.ACTIVE)
def test_init_instance_reverts_crashed_migration_from_stopped(self):
self._test_init_instance_reverts_crashed_migrations(
old_vm_state=vm_states.STOPPED)
def test_init_instance_reverts_crashed_migration_no_old_state(self):
self._test_init_instance_reverts_crashed_migrations(old_vm_state=None)
def test_init_instance_sets_building_error(self):
instance = fake_instance.fake_instance_obj(
self.context,
uuid='foo',
vm_state=vm_states.BUILDING,
task_state=None)
with mock.patch.object(instance, 'save') as save:
self.compute._init_instance(self.context, instance)
save.assert_called_once_with()
self.assertIsNone(instance.task_state)
self.assertEqual(vm_states.ERROR, instance.vm_state)
def _test_init_instance_sets_building_tasks_error(self, instance):
with mock.patch.object(instance, 'save') as save:
self.compute._init_instance(self.context, instance)
save.assert_called_once_with()
self.assertIsNone(instance.task_state)
self.assertEqual(vm_states.ERROR, instance.vm_state)
def test_init_instance_sets_building_tasks_error_scheduling(self):
instance = fake_instance.fake_instance_obj(
self.context,
uuid='foo',
vm_state=None,
task_state=task_states.SCHEDULING)
self._test_init_instance_sets_building_tasks_error(instance)
def test_init_instance_sets_building_tasks_error_block_device(self):
instance = instance_obj.Instance(self.context)
instance.uuid = 'foo'
instance.vm_state = None
instance.task_state = task_states.BLOCK_DEVICE_MAPPING
self._test_init_instance_sets_building_tasks_error(instance)
def test_init_instance_sets_building_tasks_error_networking(self):
instance = instance_obj.Instance(self.context)
instance.uuid = 'foo'
instance.vm_state = None
instance.task_state = task_states.NETWORKING
self._test_init_instance_sets_building_tasks_error(instance)
def test_init_instance_sets_building_tasks_error_spawning(self):
instance = instance_obj.Instance(self.context)
instance.uuid = 'foo'
instance.vm_state = None
instance.task_state = task_states.SPAWNING
self._test_init_instance_sets_building_tasks_error(instance)
def _test_init_instance_cleans_image_states(self, instance):
with mock.patch.object(instance, 'save') as save:
self.compute._get_power_state = mock.Mock()
instance.info_cache = None
instance.power_state = power_state.RUNNING
self.compute._init_instance(self.context, instance)
save.assert_called_once_with()
self.assertIsNone(instance.task_state)
def test_init_instance_cleans_image_state_pending_upload(self):
instance = instance_obj.Instance(self.context)
instance.uuid = 'foo'
instance.vm_state = vm_states.ACTIVE
instance.task_state = task_states.IMAGE_PENDING_UPLOAD
self._test_init_instance_cleans_image_states(instance)
def test_init_instance_cleans_image_state_uploading(self):
instance = instance_obj.Instance(self.context)
instance.uuid = 'foo'
instance.vm_state = vm_states.ACTIVE
instance.task_state = task_states.IMAGE_UPLOADING
self._test_init_instance_cleans_image_states(instance)
def test_init_instance_cleans_image_state_snapshot(self):
instance = instance_obj.Instance(self.context)
instance.uuid = 'foo'
instance.vm_state = vm_states.ACTIVE
instance.task_state = task_states.IMAGE_SNAPSHOT
self._test_init_instance_cleans_image_states(instance)
def test_init_instance_cleans_image_state_snapshot_pending(self):
instance = instance_obj.Instance(self.context)
instance.uuid = 'foo'
instance.vm_state = vm_states.ACTIVE
instance.task_state = task_states.IMAGE_SNAPSHOT_PENDING
self._test_init_instance_cleans_image_states(instance)
def test_init_instance_errors_when_not_migrating(self):
instance = instance_obj.Instance(self.context)
instance.uuid = 'foo'
instance.vm_state = vm_states.ERROR
instance.task_state = task_states.IMAGE_UPLOADING
self.mox.StubOutWithMock(compute_utils, 'get_nw_info_for_instance')
self.mox.ReplayAll()
self.compute._init_instance(self.context, instance)
self.mox.VerifyAll()
def test_init_instance_deletes_error_deleting_instance(self):
instance = fake_instance.fake_instance_obj(
self.context,
uuid='fake',
vm_state=vm_states.ERROR,
task_state=task_states.DELETING)
self.mox.StubOutWithMock(block_device_obj.BlockDeviceMappingList,
'get_by_instance_uuid')
self.mox.StubOutWithMock(self.compute, '_delete_instance')
self.mox.StubOutWithMock(instance, 'obj_load_attr')
bdms = []
instance.obj_load_attr('metadata')
instance.obj_load_attr('system_metadata')
block_device_obj.BlockDeviceMappingList.get_by_instance_uuid(
self.context, instance.uuid).AndReturn(bdms)
self.compute._delete_instance(self.context, instance, bdms)
self.mox.ReplayAll()
self.compute._init_instance(self.context, instance)
self.mox.VerifyAll()
def _test_init_instance_retries_reboot(self, instance, reboot_type,
return_power_state):
with contextlib.nested(
mock.patch.object(self.compute, '_get_power_state',
return_value=return_power_state),
mock.patch.object(self.compute.compute_rpcapi, 'reboot_instance'),
mock.patch.object(compute_utils, 'get_nw_info_for_instance')
) as (
_get_power_state,
reboot_instance,
get_nw_info_for_instance
):
self.compute._init_instance(self.context, instance)
call = mock.call(self.context, instance, block_device_info=None,
reboot_type=reboot_type)
reboot_instance.assert_has_calls([call])
def test_init_instance_retries_reboot_pending(self):
instance = instance_obj.Instance(self.context)
instance.uuid = 'foo'
instance.task_state = task_states.REBOOT_PENDING
for state in vm_states.ALLOW_SOFT_REBOOT:
instance.vm_state = state
self._test_init_instance_retries_reboot(instance, 'SOFT',
power_state.RUNNING)
def test_init_instance_retries_reboot_pending_hard(self):
instance = instance_obj.Instance(self.context)
instance.uuid = 'foo'
instance.task_state = task_states.REBOOT_PENDING_HARD
for state in vm_states.ALLOW_HARD_REBOOT:
# NOTE(dave-mcnally) while a reboot of a vm in error state is
# possible we don't attempt to recover an error during init
if state == vm_states.ERROR:
continue
instance.vm_state = state
self._test_init_instance_retries_reboot(instance, 'HARD',
power_state.RUNNING)
def test_init_instance_retries_reboot_started(self):
instance = instance_obj.Instance(self.context)
instance.uuid = 'foo'
instance.vm_state = vm_states.ACTIVE
instance.task_state = task_states.REBOOT_STARTED
self._test_init_instance_retries_reboot(instance, 'HARD',
power_state.NOSTATE)
def test_init_instance_retries_reboot_started_hard(self):
instance = instance_obj.Instance(self.context)
instance.uuid = 'foo'
instance.vm_state = vm_states.ACTIVE
instance.task_state = task_states.REBOOT_STARTED_HARD
self._test_init_instance_retries_reboot(instance, 'HARD',
power_state.NOSTATE)
def _test_init_instance_cleans_reboot_state(self, instance):
with contextlib.nested(
mock.patch.object(self.compute, '_get_power_state',
return_value=power_state.RUNNING),
mock.patch.object(instance, 'save', autospec=True),
mock.patch.object(compute_utils, 'get_nw_info_for_instance')
) as (
_get_power_state,
instance_save,
get_nw_info_for_instance
):
self.compute._init_instance(self.context, instance)
instance_save.assert_called_once_with()
self.assertIsNone(instance.task_state)
self.assertEqual(vm_states.ACTIVE, instance.vm_state)
def test_init_instance_cleans_image_state_reboot_started(self):
instance = instance_obj.Instance(self.context)
instance.uuid = 'foo'
instance.vm_state = vm_states.ACTIVE
instance.task_state = task_states.REBOOT_STARTED
instance.power_state = power_state.RUNNING
self._test_init_instance_cleans_reboot_state(instance)
def test_init_instance_cleans_image_state_reboot_started_hard(self):
instance = instance_obj.Instance(self.context)
instance.uuid = 'foo'
instance.vm_state = vm_states.ACTIVE
instance.task_state = task_states.REBOOT_STARTED_HARD
instance.power_state = power_state.RUNNING
self._test_init_instance_cleans_reboot_state(instance)
def test_get_instances_on_driver(self):
fake_context = context.get_admin_context()
driver_instances = []
for x in xrange(10):
driver_instances.append(fake_instance.fake_db_instance())
self.mox.StubOutWithMock(self.compute.driver,
'list_instance_uuids')
self.mox.StubOutWithMock(db, 'instance_get_all_by_filters')
self.compute.driver.list_instance_uuids().AndReturn(
[inst['uuid'] for inst in driver_instances])
db.instance_get_all_by_filters(
fake_context,
{'uuid': [inst['uuid'] for
inst in driver_instances]},
'created_at', 'desc', columns_to_join=None,
limit=None, marker=None,
use_slave=True).AndReturn(
driver_instances)
self.mox.ReplayAll()
result = self.compute._get_instances_on_driver(fake_context)
self.assertEqual([x['uuid'] for x in driver_instances],
[x['uuid'] for x in result])
def test_get_instances_on_driver_fallback(self):
# Test getting instances when driver doesn't support
# 'list_instance_uuids'
self.compute.host = 'host'
filters = {'host': self.compute.host}
fake_context = context.get_admin_context()
self.flags(instance_name_template='inst-%i')
all_instances = []
driver_instances = []
for x in xrange(10):
instance = fake_instance.fake_db_instance(name='inst-%i' % x,
id=x)
if x % 2:
driver_instances.append(instance)
all_instances.append(instance)
self.mox.StubOutWithMock(self.compute.driver,
'list_instance_uuids')
self.mox.StubOutWithMock(self.compute.driver,
'list_instances')
self.mox.StubOutWithMock(db, 'instance_get_all_by_filters')
self.compute.driver.list_instance_uuids().AndRaise(
NotImplementedError())
self.compute.driver.list_instances().AndReturn(
[inst['name'] for inst in driver_instances])
db.instance_get_all_by_filters(
fake_context, filters,
'created_at', 'desc', columns_to_join=None,
limit=None, marker=None,
use_slave=True).AndReturn(all_instances)
self.mox.ReplayAll()
result = self.compute._get_instances_on_driver(fake_context, filters)
self.assertEqual([x['uuid'] for x in driver_instances],
[x['uuid'] for x in result])
def test_instance_usage_audit(self):
instances = [{'uuid': 'foo'}]
self.flags(instance_usage_audit=True)
self.stubs.Set(compute_utils, 'has_audit_been_run',
lambda *a, **k: False)
self.stubs.Set(self.compute.conductor_api,
'instance_get_active_by_window_joined',
lambda *a, **k: instances)
self.stubs.Set(compute_utils, 'start_instance_usage_audit',
lambda *a, **k: None)
self.stubs.Set(compute_utils, 'finish_instance_usage_audit',
lambda *a, **k: None)
self.mox.StubOutWithMock(self.compute.conductor_api,
'notify_usage_exists')
self.compute.conductor_api.notify_usage_exists(
self.context, instances[0], ignore_missing_network_data=False)
self.mox.ReplayAll()
self.compute._instance_usage_audit(self.context)
def _get_sync_instance(self, power_state, vm_state, task_state=None):
instance = instance_obj.Instance()
instance.uuid = 'fake-uuid'
instance.power_state = power_state
instance.vm_state = vm_state
instance.host = self.compute.host
instance.task_state = task_state
self.mox.StubOutWithMock(instance, 'refresh')
self.mox.StubOutWithMock(instance, 'save')
return instance
def test_sync_instance_power_state_match(self):
instance = self._get_sync_instance(power_state.RUNNING,
vm_states.ACTIVE)
instance.refresh(use_slave=False)
self.mox.ReplayAll()
self.compute._sync_instance_power_state(self.context, instance,
power_state.RUNNING)
def test_sync_instance_power_state_running_stopped(self):
instance = self._get_sync_instance(power_state.RUNNING,
vm_states.ACTIVE)
instance.refresh(use_slave=False)
instance.save()
self.mox.ReplayAll()
self.compute._sync_instance_power_state(self.context, instance,
power_state.SHUTDOWN)
self.assertEqual(instance.power_state, power_state.SHUTDOWN)
def _test_sync_to_stop(self, power_state, vm_state, driver_power_state,
stop=True, force=False):
instance = self._get_sync_instance(power_state, vm_state)
instance.refresh(use_slave=False)
instance.save()
self.mox.StubOutWithMock(self.compute.compute_api, 'stop')
self.mox.StubOutWithMock(self.compute.compute_api, 'force_stop')
if stop:
if force:
self.compute.compute_api.force_stop(self.context, instance)
else:
self.compute.compute_api.stop(self.context, instance)
self.mox.ReplayAll()
self.compute._sync_instance_power_state(self.context, instance,
driver_power_state)
self.mox.VerifyAll()
self.mox.UnsetStubs()
def test_sync_instance_power_state_to_stop(self):
for ps in (power_state.SHUTDOWN, power_state.CRASHED,
power_state.SUSPENDED):
self._test_sync_to_stop(power_state.RUNNING, vm_states.ACTIVE, ps)
for ps in (power_state.SHUTDOWN, power_state.CRASHED):
self._test_sync_to_stop(power_state.PAUSED, vm_states.PAUSED, ps,
force=True)
self._test_sync_to_stop(power_state.SHUTDOWN, vm_states.STOPPED,
power_state.RUNNING, force=True)
def test_sync_instance_power_state_to_no_stop(self):
for ps in (power_state.PAUSED, power_state.NOSTATE):
self._test_sync_to_stop(power_state.RUNNING, vm_states.ACTIVE, ps,
stop=False)
for vs in (vm_states.SOFT_DELETED, vm_states.DELETED):
for ps in (power_state.NOSTATE, power_state.SHUTDOWN):
self._test_sync_to_stop(power_state.RUNNING, vs, ps,
stop=False)
def test_run_pending_deletes(self):
self.flags(instance_delete_interval=10)
class FakeInstance(object):
def __init__(self, uuid, name, smd):
self.uuid = uuid
self.name = name
self.system_metadata = smd
self.cleaned = False
def __getitem__(self, name):
return getattr(self, name)
def save(self, context):
pass
class FakeInstanceList(object):
def get_by_filters(self, *args, **kwargs):
return []
a = FakeInstance('123', 'apple', {'clean_attempts': '100'})
b = FakeInstance('456', 'orange', {'clean_attempts': '3'})
c = FakeInstance('789', 'banana', {})
self.mox.StubOutWithMock(instance_obj.InstanceList,
'get_by_filters')
instance_obj.InstanceList.get_by_filters(
{'read_deleted': 'yes'},
{'deleted': True, 'soft_deleted': False, 'host': 'fake-mini',
'cleaned': False},
expected_attrs=['info_cache', 'security_groups',
'system_metadata']).AndReturn([a, b, c])
self.mox.StubOutWithMock(self.compute.driver, 'delete_instance_files')
self.compute.driver.delete_instance_files(
mox.IgnoreArg()).AndReturn(True)
self.compute.driver.delete_instance_files(
mox.IgnoreArg()).AndReturn(False)
self.mox.ReplayAll()
self.compute._run_pending_deletes({})
self.assertFalse(a.cleaned)
self.assertEqual('100', a.system_metadata['clean_attempts'])
self.assertTrue(b.cleaned)
self.assertEqual('4', b.system_metadata['clean_attempts'])
self.assertFalse(c.cleaned)
self.assertEqual('1', c.system_metadata['clean_attempts'])
def test_swap_volume_volume_api_usage(self):
# This test ensures that volume_id arguments are passed to volume_api
# and that volume states are OK
volumes = {}
old_volume_id = uuidutils.generate_uuid()
volumes[old_volume_id] = {'id': old_volume_id,
'display_name': 'old_volume',
'status': 'detaching'}
new_volume_id = uuidutils.generate_uuid()
volumes[new_volume_id] = {'id': new_volume_id,
'display_name': 'new_volume',
'status': 'available'}
def fake_vol_api_begin_detaching(context, volume_id):
self.assertTrue(uuidutils.is_uuid_like(volume_id))
volumes[volume_id]['status'] = 'detaching'
def fake_vol_api_roll_detaching(context, volume_id):
self.assertTrue(uuidutils.is_uuid_like(volume_id))
if volumes[volume_id]['status'] == 'detaching':
volumes[volume_id]['status'] = 'in-use'
fake_bdm = fake_block_device.FakeDbBlockDeviceDict(
{'device_name': '/dev/vdb', 'source_type': 'volume',
'destination_type': 'volume', 'instance_uuid': 'fake',
'connection_info': '{"foo": "bar"}'})
def fake_vol_api_func(context, volume, *args):
self.assertTrue(uuidutils.is_uuid_like(volume))
return {}
def fake_vol_get(context, volume_id):
self.assertTrue(uuidutils.is_uuid_like(volume_id))
return volumes[volume_id]
def fake_vol_attach(context, volume_id, instance_uuid, connector):
self.assertTrue(uuidutils.is_uuid_like(volume_id))
self.assertIn(volumes[volume_id]['status'],
['available', 'attaching'])
volumes[volume_id]['status'] = 'in-use'
def fake_vol_api_reserve(context, volume_id):
self.assertTrue(uuidutils.is_uuid_like(volume_id))
self.assertEqual(volumes[volume_id]['status'], 'available')
volumes[volume_id]['status'] = 'attaching'
def fake_vol_unreserve(context, volume_id):
self.assertTrue(uuidutils.is_uuid_like(volume_id))
if volumes[volume_id]['status'] == 'attaching':
volumes[volume_id]['status'] = 'available'
def fake_vol_detach(context, volume_id):
self.assertTrue(uuidutils.is_uuid_like(volume_id))
volumes[volume_id]['status'] = 'available'
def fake_vol_migrate_volume_completion(context, old_volume_id,
new_volume_id, error=False):
self.assertTrue(uuidutils.is_uuid_like(old_volume_id))
self.assertTrue(uuidutils.is_uuid_like(old_volume_id))
return {'save_volume_id': new_volume_id}
def fake_func_exc(*args, **kwargs):
raise AttributeError # Random exception
self.stubs.Set(self.compute.volume_api, 'begin_detaching',
fake_vol_api_begin_detaching)
self.stubs.Set(self.compute.volume_api, 'roll_detaching',
fake_vol_api_roll_detaching)
self.stubs.Set(self.compute.volume_api, 'get', fake_vol_get)
self.stubs.Set(self.compute.volume_api, 'initialize_connection',
fake_vol_api_func)
self.stubs.Set(self.compute.volume_api, 'attach', fake_vol_attach)
self.stubs.Set(self.compute.volume_api, 'reserve_volume',
fake_vol_api_reserve)
self.stubs.Set(self.compute.volume_api, 'unreserve_volume',
fake_vol_unreserve)
self.stubs.Set(self.compute.volume_api, 'terminate_connection',
fake_vol_api_func)
self.stubs.Set(self.compute.volume_api, 'detach', fake_vol_detach)
self.stubs.Set(db, 'block_device_mapping_get_by_volume_id',
lambda x, y, z: fake_bdm)
self.stubs.Set(self.compute.driver, 'get_volume_connector',
lambda x: {})
self.stubs.Set(self.compute.driver, 'swap_volume',
lambda w, x, y, z: None)
self.stubs.Set(self.compute.volume_api, 'migrate_volume_completion',
fake_vol_migrate_volume_completion)
self.stubs.Set(db, 'block_device_mapping_update',
lambda *a, **k: fake_bdm)
self.stubs.Set(self.compute.conductor_api,
'instance_fault_create',
lambda x, y: None)
# Good path
self.compute.swap_volume(self.context, old_volume_id, new_volume_id,
fake_instance.fake_instance_obj(
self.context, **{'uuid': 'fake'}))
self.assertEqual(volumes[old_volume_id]['status'], 'available')
self.assertEqual(volumes[new_volume_id]['status'], 'in-use')
# Error paths
volumes[old_volume_id]['status'] = 'detaching'
volumes[new_volume_id]['status'] = 'attaching'
self.stubs.Set(self.compute.driver, 'swap_volume', fake_func_exc)
self.assertRaises(AttributeError, self.compute.swap_volume,
self.context, old_volume_id, new_volume_id,
fake_instance.fake_instance_obj(
self.context, **{'uuid': 'fake'}))
self.assertEqual(volumes[old_volume_id]['status'], 'in-use')
self.assertEqual(volumes[new_volume_id]['status'], 'available')
volumes[old_volume_id]['status'] = 'detaching'
volumes[new_volume_id]['status'] = 'attaching'
self.stubs.Set(self.compute.volume_api, 'initialize_connection',
fake_func_exc)
self.assertRaises(AttributeError, self.compute.swap_volume,
self.context, old_volume_id, new_volume_id,
fake_instance.fake_instance_obj(
self.context, **{'uuid': 'fake'}))
self.assertEqual(volumes[old_volume_id]['status'], 'in-use')
self.assertEqual(volumes[new_volume_id]['status'], 'available')
def test_check_can_live_migrate_source(self):
is_volume_backed = 'volume_backed'
bdms = 'bdms'
dest_check_data = dict(foo='bar')
db_instance = fake_instance.fake_db_instance()
instance = instance_obj.Instance._from_db_object(
self.context, instance_obj.Instance(), db_instance)
expected_dest_check_data = dict(dest_check_data,
is_volume_backed=is_volume_backed)
self.mox.StubOutWithMock(self.compute.compute_api,
'is_volume_backed_instance')
self.mox.StubOutWithMock(self.compute.driver,
'check_can_live_migrate_source')
instance_p = obj_base.obj_to_primitive(instance)
self.compute.compute_api.is_volume_backed_instance(
self.context, instance).AndReturn(is_volume_backed)
self.compute.driver.check_can_live_migrate_source(
self.context, instance, expected_dest_check_data)
self.mox.ReplayAll()
self.compute.check_can_live_migrate_source(
self.context, instance=instance,
dest_check_data=dest_check_data)
def _test_check_can_live_migrate_destination(self, do_raise=False,
has_mig_data=False):
db_instance = fake_instance.fake_db_instance(host='fake-host')
instance = instance_obj.Instance._from_db_object(
self.context, instance_obj.Instance(), db_instance)
instance.host = 'fake-host'
block_migration = 'block_migration'
disk_over_commit = 'disk_over_commit'
src_info = 'src_info'
dest_info = 'dest_info'
dest_check_data = dict(foo='bar')
mig_data = dict(cow='moo')
expected_result = dict(mig_data)
if has_mig_data:
dest_check_data['migrate_data'] = dict(cat='meow')
expected_result.update(cat='meow')
self.mox.StubOutWithMock(self.compute, '_get_compute_info')
self.mox.StubOutWithMock(self.compute.driver,
'check_can_live_migrate_destination')
self.mox.StubOutWithMock(self.compute.compute_rpcapi,
'check_can_live_migrate_source')
self.mox.StubOutWithMock(self.compute.driver,
'check_can_live_migrate_destination_cleanup')
self.compute._get_compute_info(self.context,
'fake-host').AndReturn(src_info)
self.compute._get_compute_info(self.context,
CONF.host).AndReturn(dest_info)
self.compute.driver.check_can_live_migrate_destination(
self.context, instance, src_info, dest_info,
block_migration, disk_over_commit).AndReturn(dest_check_data)
mock_meth = self.compute.compute_rpcapi.check_can_live_migrate_source(
self.context, instance, dest_check_data)
if do_raise:
mock_meth.AndRaise(test.TestingException())
self.mox.StubOutWithMock(self.compute.conductor_api,
'instance_fault_create')
self.compute.conductor_api.instance_fault_create(self.context,
mox.IgnoreArg())
else:
mock_meth.AndReturn(mig_data)
self.compute.driver.check_can_live_migrate_destination_cleanup(
self.context, dest_check_data)
self.mox.ReplayAll()
result = self.compute.check_can_live_migrate_destination(
self.context, instance=instance,
block_migration=block_migration,
disk_over_commit=disk_over_commit)
self.assertEqual(expected_result, result)
def test_check_can_live_migrate_destination_success(self):
self._test_check_can_live_migrate_destination()
def test_check_can_live_migrate_destination_success_w_mig_data(self):
self._test_check_can_live_migrate_destination(has_mig_data=True)
def test_check_can_live_migrate_destination_fail(self):
self.assertRaises(
test.TestingException,
self._test_check_can_live_migrate_destination,
do_raise=True)
def test_prepare_for_instance_event(self):
inst_obj = instance_obj.Instance(uuid='foo')
result = self.compute.instance_events.prepare_for_instance_event(
inst_obj, 'test-event')
self.assertIn('foo', self.compute.instance_events._events)
self.assertIn('test-event',
self.compute.instance_events._events['foo'])
self.assertEqual(
result,
self.compute.instance_events._events['foo']['test-event'])
self.assertTrue(hasattr(result, 'send'))
def test_prepare_for_instance_event_again(self):
inst_obj = instance_obj.Instance(uuid='foo')
self.compute.instance_events.prepare_for_instance_event(
inst_obj, 'test-event')
# A second attempt will avoid creating a new list; make sure we
# get the current list
result = self.compute.instance_events.prepare_for_instance_event(
inst_obj, 'test-event')
self.assertIn('foo', self.compute.instance_events._events)
self.assertIn('test-event',
self.compute.instance_events._events['foo'])
self.assertEqual(
result,
self.compute.instance_events._events['foo']['test-event'])
self.assertTrue(hasattr(result, 'send'))
def test_process_instance_event(self):
event = eventlet_event.Event()
self.compute.instance_events._events = {
'foo': {
'test-event': event,
}
}
inst_obj = instance_obj.Instance(uuid='foo')
event_obj = external_event_obj.InstanceExternalEvent(name='test-event',
tag=None)
self.compute._process_instance_event(inst_obj, event_obj)
self.assertTrue(event.ready())
self.assertEqual(event_obj, event.wait())
self.assertEqual({}, self.compute.instance_events._events)
def test_external_instance_event(self):
instances = [
instance_obj.Instance(uuid='uuid1'),
instance_obj.Instance(uuid='uuid2')]
events = [
external_event_obj.InstanceExternalEvent(name='network-changed',
instance_uuid='uuid1'),
external_event_obj.InstanceExternalEvent(name='foo',
instance_uuid='uuid2')]
@mock.patch.object(self.compute.network_api, 'get_instance_nw_info')
@mock.patch.object(self.compute, '_process_instance_event')
def do_test(_process_instance_event, get_instance_nw_info):
self.compute.external_instance_event(self.context,
instances, events)
get_instance_nw_info.assert_called_once_with(self.context,
instances[0])
_process_instance_event.assert_called_once_with(instances[1],
events[1])
do_test()
def test_retry_reboot_pending_soft(self):
instance = instance_obj.Instance(self.context)
instance.uuid = 'foo'
instance.task_state = task_states.REBOOT_PENDING
instance.vm_state = vm_states.ACTIVE
with mock.patch.object(self.compute, '_get_power_state',
return_value=power_state.RUNNING):
allow_reboot, reboot_type = self.compute._retry_reboot(
context, instance)
self.assertTrue(allow_reboot)
self.assertEqual(reboot_type, 'SOFT')
def test_retry_reboot_pending_hard(self):
instance = instance_obj.Instance(self.context)
instance.uuid = 'foo'
instance.task_state = task_states.REBOOT_PENDING_HARD
instance.vm_state = vm_states.ACTIVE
with mock.patch.object(self.compute, '_get_power_state',
return_value=power_state.RUNNING):
allow_reboot, reboot_type = self.compute._retry_reboot(
context, instance)
self.assertTrue(allow_reboot)
self.assertEqual(reboot_type, 'HARD')
def test_retry_reboot_starting_soft_off(self):
instance = instance_obj.Instance(self.context)
instance.uuid = 'foo'
instance.task_state = task_states.REBOOT_STARTED
with mock.patch.object(self.compute, '_get_power_state',
return_value=power_state.NOSTATE):
allow_reboot, reboot_type = self.compute._retry_reboot(
context, instance)
self.assertTrue(allow_reboot)
self.assertEqual(reboot_type, 'HARD')
def test_retry_reboot_starting_hard_off(self):
instance = instance_obj.Instance(self.context)
instance.uuid = 'foo'
instance.task_state = task_states.REBOOT_STARTED_HARD
with mock.patch.object(self.compute, '_get_power_state',
return_value=power_state.NOSTATE):
allow_reboot, reboot_type = self.compute._retry_reboot(
context, instance)
self.assertTrue(allow_reboot)
self.assertEqual(reboot_type, 'HARD')
def test_retry_reboot_starting_hard_on(self):
instance = instance_obj.Instance(self.context)
instance.uuid = 'foo'
instance.task_state = task_states.REBOOT_STARTED_HARD
with mock.patch.object(self.compute, '_get_power_state',
return_value=power_state.RUNNING):
allow_reboot, reboot_type = self.compute._retry_reboot(
context, instance)
self.assertFalse(allow_reboot)
self.assertEqual(reboot_type, 'HARD')
def test_retry_reboot_no_reboot(self):
instance = instance_obj.Instance(self.context)
instance.uuid = 'foo'
instance.task_state = 'bar'
with mock.patch.object(self.compute, '_get_power_state',
return_value=power_state.RUNNING):
allow_reboot, reboot_type = self.compute._retry_reboot(
context, instance)
self.assertFalse(allow_reboot)
self.assertEqual(reboot_type, 'HARD')
def test_init_host_with_partial_migration(self):
our_host = self.compute.host
instance_1 = instance_obj.Instance(self.context)
instance_1.uuid = 'foo'
instance_1.task_state = task_states.MIGRATING
instance_1.host = 'not-' + our_host
instance_2 = instance_obj.Instance(self.context)
instance_2.uuid = 'bar'
instance_2.task_state = None
instance_2.host = 'not-' + our_host
with contextlib.nested(
mock.patch.object(self.compute, '_get_instances_on_driver',
return_value=[instance_1,
instance_2]),
mock.patch.object(self.compute, '_get_instance_nw_info',
return_value=None),
mock.patch.object(self.compute,
'_get_instance_block_device_info',
return_value={}),
mock.patch.object(self.compute, '_is_instance_storage_shared',
return_value=False),
mock.patch.object(self.compute.driver, 'destroy')
) as (_get_instances_on_driver, _get_instance_nw_info,
_get_instance_block_device_info,
_is_instance_storage_shared, destroy):
self.compute._destroy_evacuated_instances(self.context)
destroy.assert_called_once_with(self.context, instance_2, None,
{}, True)
class ComputeManagerBuildInstanceTestCase(test.NoDBTestCase):
def setUp(self):
super(ComputeManagerBuildInstanceTestCase, self).setUp()
self.compute = importutils.import_object(CONF.compute_manager)
self.context = context.RequestContext('fake', 'fake')
self.instance = fake_instance.fake_instance_obj(self.context,
vm_state=vm_states.ACTIVE,
expected_attrs=['metadata', 'system_metadata', 'info_cache'])
self.admin_pass = 'pass'
self.injected_files = []
self.image = {}
self.node = 'fake-node'
self.limits = {}
self.requested_networks = []
self.security_groups = []
self.block_device_mapping = []
def fake_network_info():
return network_model.NetworkInfo()
self.network_info = network_model.NetworkInfoAsyncWrapper(
fake_network_info)
self.block_device_info = self.compute._prep_block_device(context,
self.instance, self.block_device_mapping)
# override tracker with a version that doesn't need the database:
fake_rt = fake_resource_tracker.FakeResourceTracker(self.compute.host,
self.compute.driver, self.node)
self.compute._resource_tracker_dict[self.node] = fake_rt
def _do_build_instance_update(self, reschedule_update=False):
self.mox.StubOutWithMock(self.instance, 'save')
self.instance.save(
expected_task_state=(task_states.SCHEDULING, None)).AndReturn(
self.instance)
if reschedule_update:
self.instance.save().AndReturn(self.instance)
def _build_and_run_instance_update(self):
self.mox.StubOutWithMock(self.instance, 'save')
self._build_resources_instance_update(stub=False)
self.instance.save(expected_task_state=
task_states.BLOCK_DEVICE_MAPPING).AndReturn(self.instance)
def _build_resources_instance_update(self, stub=True):
if stub:
self.mox.StubOutWithMock(self.instance, 'save')
self.instance.save().AndReturn(self.instance)
def _notify_about_instance_usage(self, event, stub=True, **kwargs):
if stub:
self.mox.StubOutWithMock(self.compute,
'_notify_about_instance_usage')
self.compute._notify_about_instance_usage(self.context, self.instance,
event, **kwargs)
def test_build_and_run_instance_called_with_proper_args(self):
self.mox.StubOutWithMock(self.compute, '_build_and_run_instance')
self.mox.StubOutWithMock(self.compute.conductor_api,
'action_event_start')
self.mox.StubOutWithMock(self.compute.conductor_api,
'action_event_finish')
self._do_build_instance_update()
self.compute._build_and_run_instance(self.context, self.instance,
self.image, self.injected_files, self.admin_pass,
self.requested_networks, self.security_groups,
self.block_device_mapping, self.node, self.limits)
self.compute.conductor_api.action_event_start(self.context,
mox.IgnoreArg())
self.compute.conductor_api.action_event_finish(self.context,
mox.IgnoreArg())
self.mox.ReplayAll()
self.compute.build_and_run_instance(self.context, self.instance,
self.image, request_spec={}, filter_properties=[],
injected_files=self.injected_files,
admin_password=self.admin_pass,
requested_networks=self.requested_networks,
security_groups=self.security_groups,
block_device_mapping=self.block_device_mapping, node=self.node,
limits=self.limits)
def test_build_abort_exception(self):
self.mox.StubOutWithMock(self.compute, '_build_and_run_instance')
self.mox.StubOutWithMock(self.compute, '_cleanup_allocated_networks')
self.mox.StubOutWithMock(self.compute, '_set_instance_error_state')
self.mox.StubOutWithMock(self.compute.compute_task_api,
'build_instances')
self.mox.StubOutWithMock(self.compute.conductor_api,
'action_event_start')
self.mox.StubOutWithMock(self.compute.conductor_api,
'action_event_finish')
self._do_build_instance_update()
self.compute._build_and_run_instance(self.context, self.instance,
self.image, self.injected_files, self.admin_pass,
self.requested_networks, self.security_groups,
self.block_device_mapping, self.node, self.limits).AndRaise(
exception.BuildAbortException(reason='',
instance_uuid=self.instance['uuid']))
self.compute._cleanup_allocated_networks(self.context, self.instance,
self.requested_networks)
self.compute._set_instance_error_state(self.context,
self.instance['uuid'])
self.compute.conductor_api.action_event_start(self.context,
mox.IgnoreArg())
self.compute.conductor_api.action_event_finish(self.context,
mox.IgnoreArg())
self.mox.ReplayAll()
self.compute.build_and_run_instance(self.context, self.instance,
self.image, request_spec={}, filter_properties=[],
injected_files=self.injected_files,
admin_password=self.admin_pass,
requested_networks=self.requested_networks,
security_groups=self.security_groups,
block_device_mapping=self.block_device_mapping, node=self.node,
limits=self.limits)
def test_rescheduled_exception(self):
self.mox.StubOutWithMock(self.compute, '_build_and_run_instance')
self.mox.StubOutWithMock(self.compute, '_set_instance_error_state')
self.mox.StubOutWithMock(self.compute.compute_task_api,
'build_instances')
self.mox.StubOutWithMock(self.compute.conductor_api,
'action_event_start')
self.mox.StubOutWithMock(self.compute.conductor_api,
'action_event_finish')
self._do_build_instance_update(reschedule_update=True)
self.compute._build_and_run_instance(self.context, self.instance,
self.image, self.injected_files, self.admin_pass,
self.requested_networks, self.security_groups,
self.block_device_mapping, self.node, self.limits).AndRaise(
exception.RescheduledException(reason='',
instance_uuid=self.instance['uuid']))
self.compute.compute_task_api.build_instances(self.context,
[self.instance], self.image, [], self.admin_pass,
self.injected_files, self.requested_networks,
self.security_groups, self.block_device_mapping)
self.compute.conductor_api.action_event_start(self.context,
mox.IgnoreArg())
self.compute.conductor_api.action_event_finish(self.context,
mox.IgnoreArg())
self.mox.ReplayAll()
self.compute.build_and_run_instance(self.context, self.instance,
self.image, request_spec={}, filter_properties=[],
injected_files=self.injected_files,
admin_password=self.admin_pass,
requested_networks=self.requested_networks,
security_groups=self.security_groups,
block_device_mapping=self.block_device_mapping, node=self.node,
limits=self.limits)
def test_rescheduled_exception_do_not_deallocate_network(self):
self.mox.StubOutWithMock(self.compute, '_build_and_run_instance')
self.mox.StubOutWithMock(self.compute, '_cleanup_allocated_networks')
self.mox.StubOutWithMock(self.compute.compute_task_api,
'build_instances')
self.mox.StubOutWithMock(self.compute.conductor_api,
'action_event_start')
self.mox.StubOutWithMock(self.compute.conductor_api,
'action_event_finish')
self._do_build_instance_update(reschedule_update=True)
self.compute._build_and_run_instance(self.context, self.instance,
self.image, self.injected_files, self.admin_pass,
self.requested_networks, self.security_groups,
self.block_device_mapping, self.node, self.limits).AndRaise(
exception.RescheduledException(reason='',
instance_uuid=self.instance['uuid']))
self.compute.compute_task_api.build_instances(self.context,
[self.instance], self.image, [], self.admin_pass,
self.injected_files, self.requested_networks,
self.security_groups, self.block_device_mapping)
self.compute.conductor_api.action_event_start(self.context,
mox.IgnoreArg())
self.compute.conductor_api.action_event_finish(self.context,
mox.IgnoreArg())
self.mox.ReplayAll()
self.compute.build_and_run_instance(self.context, self.instance,
self.image, request_spec={}, filter_properties=[],
injected_files=self.injected_files,
admin_password=self.admin_pass,
requested_networks=self.requested_networks,
security_groups=self.security_groups,
block_device_mapping=self.block_device_mapping, node=self.node,
limits=self.limits)
def test_rescheduled_exception_deallocate_network_if_dhcp(self):
self.mox.StubOutWithMock(self.compute, '_build_and_run_instance')
self.mox.StubOutWithMock(self.compute.driver,
'dhcp_options_for_instance')
self.mox.StubOutWithMock(self.compute, '_cleanup_allocated_networks')
self.mox.StubOutWithMock(self.compute.compute_task_api,
'build_instances')
self.mox.StubOutWithMock(self.compute.conductor_api,
'action_event_start')
self.mox.StubOutWithMock(self.compute.conductor_api,
'action_event_finish')
self._do_build_instance_update(reschedule_update=True)
self.compute._build_and_run_instance(self.context, self.instance,
self.image, self.injected_files, self.admin_pass,
self.requested_networks, self.security_groups,
self.block_device_mapping, self.node, self.limits).AndRaise(
exception.RescheduledException(reason='',
instance_uuid=self.instance['uuid']))
self.compute.driver.dhcp_options_for_instance(self.instance).AndReturn(
{'fake': 'options'})
self.compute._cleanup_allocated_networks(self.context, self.instance,
self.requested_networks)
self.compute.compute_task_api.build_instances(self.context,
[self.instance], self.image, [], self.admin_pass,
self.injected_files, self.requested_networks,
self.security_groups, self.block_device_mapping)
self.compute.conductor_api.action_event_start(self.context,
mox.IgnoreArg())
self.compute.conductor_api.action_event_finish(self.context,
mox.IgnoreArg())
self.mox.ReplayAll()
self.compute.build_and_run_instance(self.context, self.instance,
self.image, request_spec={}, filter_properties=[],
injected_files=self.injected_files,
admin_password=self.admin_pass,
requested_networks=self.requested_networks,
security_groups=self.security_groups,
block_device_mapping=self.block_device_mapping, node=self.node,
limits=self.limits)
def _test_build_and_run_exceptions(self, exc, set_error=False):
self.mox.StubOutWithMock(self.compute, '_build_and_run_instance')
self.mox.StubOutWithMock(self.compute, '_cleanup_allocated_networks')
self.mox.StubOutWithMock(self.compute.compute_task_api,
'build_instances')
self.mox.StubOutWithMock(self.compute.conductor_api,
'action_event_start')
self.mox.StubOutWithMock(self.compute.conductor_api,
'action_event_finish')
self._do_build_instance_update()
self.compute._build_and_run_instance(self.context, self.instance,
self.image, self.injected_files, self.admin_pass,
self.requested_networks, self.security_groups,
self.block_device_mapping, self.node, self.limits).AndRaise(
exc)
self.compute._cleanup_allocated_networks(self.context, self.instance,
self.requested_networks)
if set_error:
self.mox.StubOutWithMock(self.compute, '_set_instance_error_state')
self.compute._set_instance_error_state(self.context,
self.instance['uuid'])
self.compute.conductor_api.action_event_start(self.context,
mox.IgnoreArg())
self.compute.conductor_api.action_event_finish(self.context,
mox.IgnoreArg())
self.mox.ReplayAll()
self.compute.build_and_run_instance(self.context, self.instance,
self.image, request_spec={}, filter_properties=[],
injected_files=self.injected_files,
admin_password=self.admin_pass,
requested_networks=self.requested_networks,
security_groups=self.security_groups,
block_device_mapping=self.block_device_mapping, node=self.node,
limits=self.limits)
self.mox.UnsetStubs()
def test_build_and_run_instance_exceptions(self):
exceptions = [
exception.InstanceNotFound(instance_id=''),
exception.UnexpectedDeletingTaskStateError(expected='',
actual='')]
error_exceptions = [
exception.BuildAbortException(instance_uuid='', reason=''),
test.TestingException()]
for exc in exceptions:
self._test_build_and_run_exceptions(exc)
for exc in error_exceptions:
self._test_build_and_run_exceptions(exc, set_error=True)
def test_instance_not_found(self):
exc = exception.InstanceNotFound(instance_id=1)
self.mox.StubOutWithMock(self.compute.driver, 'spawn')
self.mox.StubOutWithMock(conductor_rpcapi.ConductorAPI,
'instance_update')
self.mox.StubOutWithMock(self.compute, '_build_networks_for_instance')
self.compute._build_networks_for_instance(self.context, self.instance,
self.requested_networks, self.security_groups).AndReturn(
self.network_info)
self._notify_about_instance_usage('create.start',
extra_usage_info={'image_name': self.image.get('name')})
self._build_and_run_instance_update()
self.compute.driver.spawn(self.context, self.instance, self.image,
self.injected_files, self.admin_pass,
network_info=self.network_info,
block_device_info=self.block_device_info).AndRaise(exc)
self._notify_about_instance_usage('create.end',
fault=exc, stub=False)
conductor_rpcapi.ConductorAPI.instance_update(
self.context, self.instance['uuid'], mox.IgnoreArg(), 'conductor')
self.mox.ReplayAll()
self.assertRaises(exception.InstanceNotFound,
self.compute._build_and_run_instance, self.context,
self.instance, self.image, self.injected_files,
self.admin_pass, self.requested_networks, self.security_groups,
self.block_device_mapping, self.node,
self.limits)
def test_reschedule_on_exception(self):
self.mox.StubOutWithMock(self.compute.driver, 'spawn')
self.mox.StubOutWithMock(conductor_rpcapi.ConductorAPI,
'instance_update')
self.mox.StubOutWithMock(self.compute, '_build_networks_for_instance')
self.compute._build_networks_for_instance(self.context, self.instance,
self.requested_networks, self.security_groups).AndReturn(
self.network_info)
self._notify_about_instance_usage('create.start',
extra_usage_info={'image_name': self.image.get('name')})
self._build_and_run_instance_update()
exc = test.TestingException()
self.compute.driver.spawn(self.context, self.instance, self.image,
self.injected_files, self.admin_pass,
network_info=self.network_info,
block_device_info=self.block_device_info).AndRaise(exc)
conductor_rpcapi.ConductorAPI.instance_update(
self.context, self.instance['uuid'], mox.IgnoreArg(), 'conductor')
self._notify_about_instance_usage('create.error',
fault=exc, stub=False)
self.mox.ReplayAll()
self.assertRaises(exception.RescheduledException,
self.compute._build_and_run_instance, self.context,
self.instance, self.image, self.injected_files,
self.admin_pass, self.requested_networks, self.security_groups,
self.block_device_mapping, self.node,
self.limits)
def test_spawn_network_alloc_failure(self):
# Because network allocation is asynchronous, failures may not present
# themselves until the virt spawn method is called.
exc = exception.NoMoreNetworks()
with contextlib.nested(
mock.patch.object(self.compute.driver, 'spawn',
side_effect=exc),
mock.patch.object(conductor_rpcapi.ConductorAPI,
'instance_update'),
mock.patch.object(self.instance, 'save',
side_effect=[self.instance, self.instance]),
mock.patch.object(self.compute,
'_build_networks_for_instance',
return_value=self.network_info),
mock.patch.object(self.compute,
'_notify_about_instance_usage')
) as (spawn, instance_update, save,
_build_networks_for_instance, _notify_about_instance_usage):
self.assertRaises(exception.BuildAbortException,
self.compute._build_and_run_instance, self.context,
self.instance, self.image, self.injected_files,
self.admin_pass, self.requested_networks,
self.security_groups, self.block_device_mapping, self.node,
self.limits)
_build_networks_for_instance.assert_has_calls(
mock.call(self.context, self.instance,
self.requested_networks, self.security_groups))
_notify_about_instance_usage.assert_has_calls([
mock.call(self.context, self.instance, 'create.start',
extra_usage_info={'image_name': self.image.get('name')}),
mock.call(self.context, self.instance, 'create.error',
fault=exc)])
save.assert_has_calls([
mock.call(),
mock.call(
expected_task_state=task_states.BLOCK_DEVICE_MAPPING)])
spawn.assert_has_calls(mock.call(self.context, self.instance,
self.image, self.injected_files, self.admin_pass,
network_info=self.network_info,
block_device_info=self.block_device_info))
instance_update.assert_has_calls(mock.call(self.context,
self.instance['uuid'], mock.ANY, 'conductor'))
@mock.patch('nova.compute.manager.ComputeManager._get_power_state')
def test_spawn_waits_for_network_and_saves_info_cache(self, gps):
inst = mock.MagicMock()
network_info = mock.MagicMock()
with mock.patch.object(self.compute, 'driver'):
self.compute._spawn(self.context, inst, {}, network_info, None,
None, None)
network_info.wait.assert_called_once_with(do_raise=True)
self.assertEqual(network_info, inst.info_cache.network_info)
inst.save.assert_called_with(expected_task_state=task_states.SPAWNING)
def test_reschedule_on_resources_unavailable(self):
reason = 'resource unavailable'
exc = exception.ComputeResourcesUnavailable(reason=reason)
class FakeResourceTracker(object):
def instance_claim(self, context, instance, limits):
raise exc
self.mox.StubOutWithMock(self.compute, '_get_resource_tracker')
self.mox.StubOutWithMock(self.compute.compute_task_api,
'build_instances')
self.mox.StubOutWithMock(self.compute.conductor_api,
'action_event_start')
self.mox.StubOutWithMock(self.compute.conductor_api,
'action_event_finish')
self.compute._get_resource_tracker(self.node).AndReturn(
FakeResourceTracker())
self._do_build_instance_update(reschedule_update=True)
self._notify_about_instance_usage('create.start',
extra_usage_info={'image_name': self.image.get('name')})
self._notify_about_instance_usage('create.error',
fault=exc, stub=False)
self.compute.compute_task_api.build_instances(self.context,
[self.instance], self.image, [], self.admin_pass,
self.injected_files, self.requested_networks,
self.security_groups, self.block_device_mapping)
self.compute.conductor_api.action_event_start(self.context,
mox.IgnoreArg())
self.compute.conductor_api.action_event_finish(self.context,
mox.IgnoreArg())
self.mox.ReplayAll()
self.compute.build_and_run_instance(self.context, self.instance,
self.image, request_spec={}, filter_properties=[],
injected_files=self.injected_files,
admin_password=self.admin_pass,
requested_networks=self.requested_networks,
security_groups=self.security_groups,
block_device_mapping=self.block_device_mapping, node=self.node,
limits=self.limits)
def test_build_resources_buildabort_reraise(self):
exc = exception.BuildAbortException(
instance_uuid=self.instance['uuid'], reason='')
self.mox.StubOutWithMock(self.compute, '_build_resources')
self.mox.StubOutWithMock(conductor_rpcapi.ConductorAPI,
'instance_update')
conductor_rpcapi.ConductorAPI.instance_update(
self.context, self.instance['uuid'], mox.IgnoreArg(), 'conductor')
self._notify_about_instance_usage('create.start',
extra_usage_info={'image_name': self.image.get('name')})
self.compute._build_resources(self.context, self.instance,
self.requested_networks, self.security_groups, self.image,
self.block_device_mapping).AndRaise(exc)
self._notify_about_instance_usage('create.error',
fault=exc, stub=False)
self.mox.ReplayAll()
self.assertRaises(exception.BuildAbortException,
self.compute._build_and_run_instance, self.context,
self.instance, self.image, self.injected_files,
self.admin_pass, self.requested_networks,
self.security_groups, self.block_device_mapping, self.node,
self.limits)
def test_build_resources_reraises_on_failed_bdm_prep(self):
self.mox.StubOutWithMock(self.compute, '_prep_block_device')
self.mox.StubOutWithMock(self.compute, '_build_networks_for_instance')
self.compute._build_networks_for_instance(self.context, self.instance,
self.requested_networks, self.security_groups).AndReturn(
self.network_info)
self._build_resources_instance_update()
self.compute._prep_block_device(self.context, self.instance,
self.block_device_mapping).AndRaise(test.TestingException())
self.mox.ReplayAll()
try:
with self.compute._build_resources(self.context, self.instance,
self.requested_networks, self.security_groups,
self.image, self.block_device_mapping):
pass
except Exception as e:
self.assertIsInstance(e, exception.BuildAbortException)
def test_failed_bdm_prep_from_delete_raises_unexpected(self):
with contextlib.nested(
mock.patch.object(self.compute,
'_build_networks_for_instance',
return_value=self.network_info),
mock.patch.object(self.instance, 'save',
side_effect=exception.UnexpectedDeletingTaskStateError(
actual=task_states.DELETING, expected='None')),
) as (_build_networks_for_instance, save):
try:
with self.compute._build_resources(self.context, self.instance,
self.requested_networks, self.security_groups,
self.image, self.block_device_mapping):
pass
except Exception as e:
self.assertIsInstance(e,
exception.UnexpectedDeletingTaskStateError)
_build_networks_for_instance.assert_has_calls(
mock.call(self.context, self.instance,
self.requested_networks, self.security_groups))
save.assert_has_calls(mock.call())
def test_build_resources_aborts_on_failed_network_alloc(self):
self.mox.StubOutWithMock(self.compute, '_build_networks_for_instance')
self.compute._build_networks_for_instance(self.context, self.instance,
self.requested_networks, self.security_groups).AndRaise(
test.TestingException())
self.mox.ReplayAll()
try:
with self.compute._build_resources(self.context, self.instance,
self.requested_networks, self.security_groups, self.image,
self.block_device_mapping):
pass
except Exception as e:
self.assertIsInstance(e, exception.BuildAbortException)
def test_failed_network_alloc_from_delete_raises_unexpected(self):
with mock.patch.object(self.compute,
'_build_networks_for_instance') as _build_networks:
exc = exception.UnexpectedDeletingTaskStateError
_build_networks.side_effect = exc(actual=task_states.DELETING,
expected='None')
try:
with self.compute._build_resources(self.context, self.instance,
self.requested_networks, self.security_groups,
self.image, self.block_device_mapping):
pass
except Exception as e:
self.assertIsInstance(e, exc)
_build_networks.assert_has_calls(
mock.call(self.context, self.instance,
self.requested_networks, self.security_groups))
def test_build_resources_cleans_up_and_reraises_on_spawn_failure(self):
self.mox.StubOutWithMock(self.compute, '_cleanup_build_resources')
self.mox.StubOutWithMock(self.compute, '_build_networks_for_instance')
self.compute._build_networks_for_instance(self.context, self.instance,
self.requested_networks, self.security_groups).AndReturn(
self.network_info)
self._build_resources_instance_update()
self.compute._cleanup_build_resources(self.context, self.instance,
self.block_device_mapping)
self.mox.ReplayAll()
test_exception = test.TestingException()
def fake_spawn():
raise test_exception
try:
with self.compute._build_resources(self.context, self.instance,
self.requested_networks, self.security_groups,
self.image, self.block_device_mapping):
fake_spawn()
except Exception as e:
self.assertEqual(test_exception, e)
def test_build_resources_aborts_on_cleanup_failure(self):
self.mox.StubOutWithMock(self.compute, '_cleanup_build_resources')
self.mox.StubOutWithMock(self.compute, '_build_networks_for_instance')
self.compute._build_networks_for_instance(self.context, self.instance,
self.requested_networks, self.security_groups).AndReturn(
self.network_info)
self._build_resources_instance_update()
self.compute._cleanup_build_resources(self.context, self.instance,
self.block_device_mapping).AndRaise(test.TestingException())
self.mox.ReplayAll()
def fake_spawn():
raise test.TestingException()
try:
with self.compute._build_resources(self.context, self.instance,
self.requested_networks, self.security_groups,
self.image, self.block_device_mapping):
fake_spawn()
except Exception as e:
self.assertIsInstance(e, exception.BuildAbortException)
def test_cleanup_cleans_volumes(self):
self.mox.StubOutWithMock(self.compute, '_cleanup_volumes')
self.compute._cleanup_volumes(self.context, self.instance['uuid'],
self.block_device_mapping)
self.mox.ReplayAll()
self.compute._cleanup_build_resources(self.context, self.instance,
self.block_device_mapping)
def test_cleanup_reraises_volume_cleanup_failure(self):
self.mox.StubOutWithMock(self.compute, '_cleanup_volumes')
self.compute._cleanup_volumes(self.context, self.instance['uuid'],
self.block_device_mapping).AndRaise(test.TestingException())
self.mox.ReplayAll()
self.assertRaises(test.TestingException,
self.compute._cleanup_build_resources, self.context,
self.instance, self.block_device_mapping)
def test_build_networks_if_not_allocated(self):
instance = fake_instance.fake_instance_obj(self.context,
system_metadata={},
expected_attrs=['system_metadata'])
self.mox.StubOutWithMock(self.compute, '_get_instance_nw_info')
self.mox.StubOutWithMock(self.compute, '_allocate_network')
self.compute._allocate_network(self.context, instance,
self.requested_networks, None, self.security_groups, None)
self.mox.ReplayAll()
self.compute._build_networks_for_instance(self.context, instance,
self.requested_networks, self.security_groups)
def test_build_networks_if_allocated_false(self):
instance = fake_instance.fake_instance_obj(self.context,
system_metadata=dict(network_allocated='False'),
expected_attrs=['system_metadata'])
self.mox.StubOutWithMock(self.compute, '_get_instance_nw_info')
self.mox.StubOutWithMock(self.compute, '_allocate_network')
self.compute._allocate_network(self.context, instance,
self.requested_networks, None, self.security_groups, None)
self.mox.ReplayAll()
self.compute._build_networks_for_instance(self.context, instance,
self.requested_networks, self.security_groups)
def test_return_networks_if_found(self):
instance = fake_instance.fake_instance_obj(self.context,
system_metadata=dict(network_allocated='True'),
expected_attrs=['system_metadata'])
def fake_network_info():
return network_model.NetworkInfo([{'address': '123.123.123.123'}])
self.mox.StubOutWithMock(self.compute, '_get_instance_nw_info')
self.mox.StubOutWithMock(self.compute, '_allocate_network')
self.compute._get_instance_nw_info(self.context, instance).AndReturn(
network_model.NetworkInfoAsyncWrapper(fake_network_info))
self.mox.ReplayAll()
self.compute._build_networks_for_instance(self.context, instance,
self.requested_networks, self.security_groups)
def test_cleanup_allocated_networks_instance_not_found(self):
with contextlib.nested(
mock.patch.object(self.compute, '_deallocate_network'),
mock.patch.object(self.instance, 'save',
side_effect=exception.InstanceNotFound(instance_id=''))
) as (_deallocate_network, save):
# Testing that this doesn't raise an exeption
self.compute._cleanup_allocated_networks(self.context,
self.instance, self.requested_networks)
save.assert_called_once_with()
self.assertEqual('False',
self.instance.system_metadata['network_allocated'])
class ComputeManagerMigrationTestCase(test.NoDBTestCase):
def setUp(self):
super(ComputeManagerMigrationTestCase, self).setUp()
self.compute = importutils.import_object(CONF.compute_manager)
self.context = context.RequestContext('fake', 'fake')
self.image = {}
self.instance = fake_instance.fake_instance_obj(self.context,
vm_state=vm_states.ACTIVE,
expected_attrs=['metadata', 'system_metadata', 'info_cache'])
self.migration = migration_obj.Migration()
self.migration.status = 'migrating'
def test_finish_resize_failure(self):
elevated_context = self.context.elevated()
with contextlib.nested(
mock.patch.object(self.compute, '_finish_resize',
side_effect=exception.ResizeError(reason='')),
mock.patch.object(self.compute.conductor_api,
'action_event_start'),
mock.patch.object(self.compute.conductor_api,
'action_event_finish'),
mock.patch.object(self.compute.conductor_api,
'instance_fault_create'),
mock.patch.object(self.compute, '_instance_update'),
mock.patch.object(self.migration, 'save'),
mock.patch.object(self.context, 'elevated',
return_value=elevated_context)
) as (meth, event_start, event_finish, fault_create, instance_update,
migration_save, context_elevated):
self.assertRaises(
exception.ResizeError, self.compute.finish_resize,
context=self.context, disk_info=[], image=self.image,
instance=self.instance, reservations=[],
migration=self.migration
)
self.assertEqual("error", self.migration.status)
migration_save.assert_has_calls([mock.call(elevated_context)])
def test_resize_instance_failure(self):
elevated_context = self.context.elevated()
self.migration.dest_host = None
with contextlib.nested(
mock.patch.object(self.compute.driver,
'migrate_disk_and_power_off',
side_effect=exception.ResizeError(reason='')),
mock.patch.object(self.compute.conductor_api,
'action_event_start'),
mock.patch.object(self.compute.conductor_api,
'action_event_finish'),
mock.patch.object(self.compute.conductor_api,
'instance_fault_create'),
mock.patch.object(self.compute, '_instance_update'),
mock.patch.object(self.migration, 'save'),
mock.patch.object(self.context, 'elevated',
return_value=elevated_context),
mock.patch.object(self.compute, '_get_instance_nw_info',
return_value=None),
mock.patch.object(self.instance, 'save'),
mock.patch.object(self.compute, '_notify_about_instance_usage'),
mock.patch.object(self.compute,
'_get_instance_block_device_info',
return_value=None),
mock.patch.object(block_device_obj.BlockDeviceMappingList,
'get_by_instance_uuid',
return_value=None)
) as (meth, event_start, event_finish, fault_create, instance_update,
migration_save, context_elevated, nw_info, save_inst, notify,
vol_block_info, bdm):
self.assertRaises(
exception.ResizeError, self.compute.resize_instance,
context=self.context, instance=self.instance, image=self.image,
reservations=[], migration=self.migration, instance_type='type'
)
self.assertEqual("error", self.migration.status)
migration_save.assert_has_calls([mock.call(elevated_context)])
| |
# Copyright (c) 2010 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.
"""Generic presubmit checks that can be reused by other presubmit checks."""
### Description checks
def CheckChangeHasTestField(input_api, output_api):
"""Requires that the changelist have a TEST= field."""
if input_api.change.TEST:
return []
else:
return [output_api.PresubmitNotifyResult(
'Changelist should have a TEST= field. TEST=none is allowed.')]
def CheckChangeHasBugField(input_api, output_api):
"""Requires that the changelist have a BUG= field."""
if input_api.change.BUG:
return []
else:
return [output_api.PresubmitNotifyResult(
'Changelist should have a BUG= field. BUG=none is allowed.')]
def CheckChangeHasTestedField(input_api, output_api):
"""Requires that the changelist have a TESTED= field."""
if input_api.change.TESTED:
return []
else:
return [output_api.PresubmitError('Changelist must have a TESTED= field.')]
def CheckChangeHasQaField(input_api, output_api):
"""Requires that the changelist have a QA= field."""
if input_api.change.QA:
return []
else:
return [output_api.PresubmitError('Changelist must have a QA= field.')]
def CheckDoNotSubmitInDescription(input_api, output_api):
"""Checks that the user didn't add 'DO NOT ' + 'SUBMIT' to the CL description.
"""
keyword = 'DO NOT ' + 'SUBMIT'
if keyword in input_api.change.DescriptionText():
return [output_api.PresubmitError(
keyword + ' is present in the changelist description.')]
else:
return []
def CheckChangeHasDescription(input_api, output_api):
"""Checks the CL description is not empty."""
text = input_api.change.DescriptionText()
if text.strip() == '':
if input_api.is_committing:
return [output_api.PresubmitError('Add a description.')]
else:
return [output_api.PresubmitNotifyResult('Add a description.')]
return []
### Content checks
def CheckDoNotSubmitInFiles(input_api, output_api):
"""Checks that the user didn't add 'DO NOT ' + 'SUBMIT' to any files."""
keyword = 'DO NOT ' + 'SUBMIT'
# We want to check every text files, not just source files.
for f, line_num, line in input_api.RightHandSideLines(lambda x: x):
if keyword in line:
text = 'Found ' + keyword + ' in %s, line %s' % (f.LocalPath(), line_num)
return [output_api.PresubmitError(text)]
return []
def CheckChangeLintsClean(input_api, output_api, source_file_filter=None):
"""Checks that all '.cc' and '.h' files pass cpplint.py."""
_RE_IS_TEST = input_api.re.compile(r'.*tests?.(cc|h)$')
result = []
# Initialize cpplint.
import cpplint
cpplint._cpplint_state.ResetErrorCounts()
# Justifications for each filter:
#
# - build/include : Too many; fix in the future.
# - build/include_order : Not happening; #ifdefed includes.
# - build/namespace : I'm surprised by how often we violate this rule.
# - readability/casting : Mistakes a whole bunch of function pointer.
# - runtime/int : Can be fixed long term; volume of errors too high
# - runtime/virtual : Broken now, but can be fixed in the future?
# - whitespace/braces : We have a lot of explicit scoping in chrome code.
cpplint._SetFilters('-build/include,-build/include_order,-build/namespace,'
'-readability/casting,-runtime/int,-runtime/virtual,'
'-whitespace/braces')
# We currently are more strict with normal code than unit tests; 4 and 5 are
# the verbosity level that would normally be passed to cpplint.py through
# --verbose=#. Hopefully, in the future, we can be more verbose.
files = [f.AbsoluteLocalPath() for f in
input_api.AffectedSourceFiles(source_file_filter)]
for file_name in files:
if _RE_IS_TEST.match(file_name):
level = 5
else:
level = 4
cpplint.ProcessFile(file_name, level)
if cpplint._cpplint_state.error_count > 0:
if input_api.is_committing:
res_type = output_api.PresubmitError
else:
res_type = output_api.PresubmitPromptWarning
result = [res_type('Changelist failed cpplint.py check.')]
return result
def CheckChangeHasNoCR(input_api, output_api, source_file_filter=None):
"""Checks no '\r' (CR) character is in any source files."""
cr_files = []
for f in input_api.AffectedSourceFiles(source_file_filter):
if '\r' in input_api.ReadFile(f, 'rb'):
cr_files.append(f.LocalPath())
if cr_files:
return [output_api.PresubmitPromptWarning(
'Found a CR character in these files:', items=cr_files)]
return []
def CheckSvnModifiedDirectories(input_api, output_api, source_file_filter=None):
"""Checks for files in svn modified directories.
They will get submitted on accident because svn commits recursively by
default, and that's very dangerous.
"""
if input_api.change.scm != 'svn':
return []
errors = []
current_cl_files = input_api.change.GetModifiedFiles()
all_modified_files = input_api.change.GetAllModifiedFiles()
# Filter out files in the current CL.
modified_files = [f for f in all_modified_files if f not in current_cl_files]
modified_abspaths = [input_api.os_path.abspath(f) for f in modified_files]
for f in input_api.AffectedFiles(source_file_filter):
if f.Action() == 'M' and f.IsDirectory():
curpath = f.AbsoluteLocalPath()
bad_files = []
# Check if any of the modified files in other CLs are under curpath.
for i in xrange(len(modified_files)):
abspath = modified_abspaths[i]
if input_api.os_path.commonprefix([curpath, abspath]) == curpath:
bad_files.append(modified_files[i])
if bad_files:
if input_api.is_committing:
error_type = output_api.PresubmitPromptWarning
else:
error_type = output_api.PresubmitNotifyResult
errors.append(error_type(
'Potential accidental commits in changelist %s:' % f.LocalPath(),
items=bad_files))
return errors
def CheckChangeHasOnlyOneEol(input_api, output_api, source_file_filter=None):
"""Checks the files ends with one and only one \n (LF)."""
eof_files = []
for f in input_api.AffectedSourceFiles(source_file_filter):
contents = input_api.ReadFile(f, 'rb')
# Check that the file ends in one and only one newline character.
if len(contents) > 1 and (contents[-1:] != '\n' or contents[-2:-1] == '\n'):
eof_files.append(f.LocalPath())
if eof_files:
return [output_api.PresubmitPromptWarning(
'These files should end in one (and only one) newline character:',
items=eof_files)]
return []
def CheckChangeHasNoCrAndHasOnlyOneEol(input_api, output_api,
source_file_filter=None):
"""Runs both CheckChangeHasNoCR and CheckChangeHasOnlyOneEOL in one pass.
It is faster because it is reading the file only once.
"""
cr_files = []
eof_files = []
for f in input_api.AffectedSourceFiles(source_file_filter):
contents = input_api.ReadFile(f, 'rb')
if '\r' in contents:
cr_files.append(f.LocalPath())
# Check that the file ends in one and only one newline character.
if len(contents) > 1 and (contents[-1:] != '\n' or contents[-2:-1] == '\n'):
eof_files.append(f.LocalPath())
outputs = []
if cr_files:
outputs.append(output_api.PresubmitPromptWarning(
'Found a CR character in these files:', items=cr_files))
if eof_files:
outputs.append(output_api.PresubmitPromptWarning(
'These files should end in one (and only one) newline character:',
items=eof_files))
return outputs
def CheckChangeHasNoTabs(input_api, output_api, source_file_filter=None):
"""Checks that there are no tab characters in any of the text files to be
submitted.
"""
# In addition to the filter, make sure that makefiles are blacklisted.
if not source_file_filter:
# It's the default filter.
source_file_filter = input_api.FilterSourceFile
def filter_more(affected_file):
return (not input_api.os_path.basename(affected_file.LocalPath()) in
('Makefile', 'makefile') and
source_file_filter(affected_file))
tabs = []
for f, line_num, line in input_api.RightHandSideLines(filter_more):
if '\t' in line:
tabs.append('%s, line %s' % (f.LocalPath(), line_num))
if tabs:
return [output_api.PresubmitPromptWarning('Found a tab character in:',
long_text='\n'.join(tabs))]
return []
def CheckChangeHasNoStrayWhitespace(input_api, output_api,
source_file_filter=None):
"""Checks that there is no stray whitespace at source lines end."""
errors = []
for f, line_num, line in input_api.RightHandSideLines(source_file_filter):
if line.rstrip() != line:
errors.append('%s, line %s' % (f.LocalPath(), line_num))
if errors:
return [output_api.PresubmitPromptWarning(
'Found line ending with white spaces in:',
long_text='\n'.join(errors))]
return []
def CheckLongLines(input_api, output_api, maxlen=80, source_file_filter=None):
"""Checks that there aren't any lines longer than maxlen characters in any of
the text files to be submitted.
"""
bad = []
for f, line_num, line in input_api.RightHandSideLines(source_file_filter):
# Allow lines with http://, https:// and #define/#pragma/#include/#if/#endif
# to exceed the maxlen rule.
if (len(line) > maxlen and
not 'http://' in line and
not 'https://' in line and
not line.startswith('#define') and
not line.startswith('#include') and
not line.startswith('#pragma') and
not line.startswith('#if') and
not line.startswith('#endif')):
bad.append(
'%s, line %s, %s chars' %
(f.LocalPath(), line_num, len(line)))
if len(bad) == 5: # Just show the first 5 errors.
break
if bad:
msg = 'Found lines longer than %s characters (first 5 shown).' % maxlen
return [output_api.PresubmitPromptWarning(msg, items=bad)]
else:
return []
def CheckLicense(input_api, output_api, license, source_file_filter=None):
"""Verifies the license header.
"""
license_re = input_api.re.compile(license, input_api.re.MULTILINE)
bad_files = []
for f in input_api.AffectedSourceFiles(source_file_filter):
contents = input_api.ReadFile(f, 'rb')
if not license_re.search(contents):
bad_files.append(f.LocalPath())
if bad_files:
if input_api.is_committing:
res_type = output_api.PresubmitPromptWarning
else:
res_type = output_api.PresubmitNotifyResult
return [res_type(
'Found a bad license header in these files:', items=bad_files)]
return []
def CheckChangeSvnEolStyle(input_api, output_api, source_file_filter=None):
"""Checks that the source files have svn:eol-style=LF."""
return CheckSvnProperty(input_api, output_api,
'svn:eol-style', 'LF',
input_api.AffectedSourceFiles(source_file_filter))
def CheckSvnForCommonMimeTypes(input_api, output_api):
"""Checks that common binary file types have the correct svn:mime-type."""
output = []
files = input_api.AffectedFiles(include_deletes=False)
def IsExts(x, exts):
path = x.LocalPath()
for extension in exts:
if path.endswith(extension):
return True
return False
def FilterFiles(extension):
return filter(lambda x: IsExts(x, extension), files)
def RunCheck(mime_type, files):
output.extend(CheckSvnProperty(input_api, output_api, 'svn:mime-type',
mime_type, files))
RunCheck('application/pdf', FilterFiles(['.pdf']))
RunCheck('image/bmp', FilterFiles(['.bmp']))
RunCheck('image/gif', FilterFiles(['.gif']))
RunCheck('image/png', FilterFiles(['.png']))
RunCheck('image/jpeg', FilterFiles(['.jpg', '.jpeg', '.jpe']))
RunCheck('image/vnd.microsoft.icon', FilterFiles(['.ico']))
return output
def CheckSvnProperty(input_api, output_api, prop, expected, affected_files):
"""Checks that affected_files files have prop=expected."""
if input_api.change.scm != 'svn':
return []
bad = filter(lambda f: f.Property(prop) != expected, affected_files)
if bad:
if input_api.is_committing:
res_type = output_api.PresubmitError
else:
res_type = output_api.PresubmitNotifyResult
message = 'Run the command: svn pset %s %s \\' % (prop, expected)
return [res_type(message, items=bad)]
return []
### Other checks
def CheckDoNotSubmit(input_api, output_api):
return (
CheckDoNotSubmitInDescription(input_api, output_api) +
CheckDoNotSubmitInFiles(input_api, output_api)
)
def CheckTreeIsOpen(input_api, output_api,
url=None, closed=None, json_url=None):
"""Check whether to allow commit without prompt.
Supports two styles:
1. Checks that an url's content doesn't match a regexp that would mean that
the tree is closed. (old)
2. Check the json_url to decide whether to allow commit without prompt.
Args:
input_api: input related apis.
output_api: output related apis.
url: url to use for regex based tree status.
closed: regex to match for closed status.
json_url: url to download json style status.
"""
if not input_api.is_committing:
return []
try:
if json_url:
connection = input_api.urllib2.urlopen(json_url)
status = input_api.json.loads(connection.read())
connection.close()
if not status['can_commit_freely']:
short_text = 'Tree state is: ' + status['general_state']
long_text = status['message'] + '\n' + json_url
return [output_api.PresubmitError(short_text, long_text=long_text)]
else:
# TODO(bradnelson): drop this once all users are gone.
connection = input_api.urllib2.urlopen(url)
status = connection.read()
connection.close()
if input_api.re.match(closed, status):
long_text = status + '\n' + url
return [output_api.PresubmitError('The tree is closed.',
long_text=long_text)]
except IOError:
pass
return []
def RunPythonUnitTests(input_api, output_api, unit_tests):
"""Run the unit tests out of process, capture the output and use the result
code to determine success.
"""
# We don't want to hinder users from uploading incomplete patches.
if input_api.is_committing:
message_type = output_api.PresubmitError
else:
message_type = output_api.PresubmitNotifyResult
outputs = []
for unit_test in unit_tests:
# Run the unit tests out of process. This is because some unit tests
# stub out base libraries and don't clean up their mess. It's too easy to
# get subtle bugs.
cwd = None
env = None
unit_test_name = unit_test
# 'python -m test.unit_test' doesn't work. We need to change to the right
# directory instead.
if '.' in unit_test:
# Tests imported in submodules (subdirectories) assume that the current
# directory is in the PYTHONPATH. Manually fix that.
unit_test = unit_test.replace('.', '/')
cwd = input_api.os_path.dirname(unit_test)
unit_test = input_api.os_path.basename(unit_test)
env = input_api.environ.copy()
# At least on Windows, it seems '.' must explicitly be in PYTHONPATH
backpath = [
'.', input_api.os_path.pathsep.join(['..'] * (cwd.count('/') + 1))
]
if env.get('PYTHONPATH'):
backpath.append(env.get('PYTHONPATH'))
env['PYTHONPATH'] = input_api.os_path.pathsep.join((backpath))
subproc = input_api.subprocess.Popen(
[
input_api.python_executable,
'-m',
'%s' % unit_test
],
cwd=cwd,
env=env,
stdin=input_api.subprocess.PIPE,
stdout=input_api.subprocess.PIPE,
stderr=input_api.subprocess.PIPE)
stdoutdata, stderrdata = subproc.communicate()
# Discard the output if returncode == 0
if subproc.returncode:
outputs.append('Test \'%s\' failed with code %d\n%s\n%s\n' % (
unit_test_name, subproc.returncode, stdoutdata, stderrdata))
if outputs:
return [message_type('%d unit tests failed.' % len(outputs),
long_text='\n'.join(outputs))]
return []
def CheckRietveldTryJobExecution(input_api, output_api, host_url, platforms,
owner):
if not input_api.is_committing:
return []
if not input_api.change.issue or not input_api.change.patchset:
return []
url = '%s/%d/get_build_results/%d' % (
host_url, input_api.change.issue, input_api.change.patchset)
try:
connection = input_api.urllib2.urlopen(url)
# platform|status|url
values = [item.split('|', 2) for item in connection.read().splitlines()]
connection.close()
except input_api.urllib2.HTTPError, e:
if e.code == 404:
# Fallback to no try job.
return [output_api.PresubmitPromptWarning(
'You should try the patch first.')]
else:
# Another HTTP error happened, warn the user.
return [output_api.PresubmitPromptWarning(
'Got %s while looking for try job status.' % str(e))]
if not values:
# It returned an empty list. Probably a private review.
return []
# Reformat as an dict of platform: [status, url]
values = dict([[v[0], [v[1], v[2]]] for v in values if len(v) == 3])
if not values:
# It returned useless data.
return [output_api.PresubmitNotifyResult('Failed to parse try job results')]
for platform in platforms:
values.setdefault(platform, ['not started', ''])
message = None
non_success = [k.upper() for k,v in values.iteritems() if v[0] != 'success']
if 'failure' in [v[0] for v in values.itervalues()]:
message = 'Try job failures on %s!\n' % ', '.join(non_success)
elif non_success:
message = ('Unfinished (or not even started) try jobs on '
'%s.\n') % ', '.join(non_success)
if message:
message += (
'Is try server wrong or broken? Please notify %s. '
'Thanks.\n' % owner)
return [output_api.PresubmitPromptWarning(message=message)]
return []
def CheckBuildbotPendingBuilds(input_api, output_api, url, max_pendings,
ignored):
if not input_api.json:
return [output_api.PresubmitPromptWarning(
'Please install simplejson or upgrade to python 2.6+')]
try:
connection = input_api.urllib2.urlopen(url)
raw_data = connection.read()
connection.close()
except IOError:
return [output_api.PresubmitNotifyResult('%s is not accessible' % url)]
try:
data = input_api.json.loads(raw_data)
except ValueError:
return [output_api.PresubmitNotifyResult('Received malformed json while '
'looking up buildbot status')]
out = []
for (builder_name, builder) in data.iteritems():
if builder_name in ignored:
continue
pending_builds_len = len(builder.get('pending_builds', []))
if pending_builds_len > max_pendings:
out.append('%s has %d build(s) pending' %
(builder_name, pending_builds_len))
if out:
return [output_api.PresubmitPromptWarning(
'Build(s) pending. It is suggested to wait that no more than %d '
'builds are pending.' % max_pendings,
long_text='\n'.join(out))]
return []
| |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
from msrestazure.tools import is_valid_resource_id, resource_id
from knack.prompting import prompt_pass
from azure.cli.core.commands import LongRunningOperation
from azure.cli.core.util import (
sdk_no_wait
)
from azure.mgmt.sqlvirtualmachine.models import (
WsfcDomainProfile,
SqlVirtualMachineGroup,
PrivateIPAddress,
LoadBalancerConfiguration,
AvailabilityGroupListener,
WsfcDomainCredentials,
AutoPatchingSettings,
AutoBackupSettings,
KeyVaultCredentialSettings,
SqlConnectivityUpdateSettings,
SqlWorkloadTypeUpdateSettings,
AdditionalFeaturesServerConfigurations,
ServerConfigurationsManagementSettings,
SqlVirtualMachine
)
def sqlvm_list(
client,
resource_group_name=None):
'''
Lists all SQL virtual machines in a resource group or subscription.
'''
if resource_group_name:
# List all sql vms in the resource group
return client.list_by_resource_group(resource_group_name=resource_group_name)
# List all sql vms in the subscription
return client.list()
def sqlvm_group_list(
client,
resource_group_name=None):
'''
Lists all SQL virtual machine groups in a resource group or subscription.
'''
if resource_group_name:
# List all sql vm groups in the resource group
return client.list_by_resource_group(resource_group_name=resource_group_name)
# List all sql vm groups in the subscription
return client.list()
# pylint: disable= line-too-long, too-many-arguments
def sqlvm_group_create(client, cmd, sql_virtual_machine_group_name, resource_group_name, sql_image_offer,
sql_image_sku, domain_fqdn, cluster_operator_account, sql_service_account,
storage_account_url, storage_account_key=None, location=None, cluster_bootstrap_account=None,
file_share_witness_path=None, ou_path=None, tags=None):
'''
Creates a SQL virtual machine group.
'''
tags = tags or {}
if not storage_account_key:
storage_account_key = prompt_pass('Storage Key: ', confirm=True)
# Create the windows server failover cluster domain profile object.
wsfc_domain_profile_object = WsfcDomainProfile(domain_fqdn=domain_fqdn,
ou_path=ou_path,
cluster_bootstrap_account=cluster_bootstrap_account,
cluster_operator_account=cluster_operator_account,
sql_service_account=sql_service_account,
file_share_witness_path=file_share_witness_path,
storage_account_url=storage_account_url,
storage_account_primary_key=storage_account_key)
sqlvm_group_object = SqlVirtualMachineGroup(sql_image_offer=sql_image_offer,
sql_image_sku=sql_image_sku,
wsfc_domain_profile=wsfc_domain_profile_object,
location=location,
tags=tags)
# Since it's a running operation, we will do the put and then the get to display the instance.
LongRunningOperation(cmd.cli_ctx)(sdk_no_wait(False, client.begin_create_or_update, resource_group_name,
sql_virtual_machine_group_name, sqlvm_group_object))
return client.get(resource_group_name, sql_virtual_machine_group_name)
# pylint: disable=line-too-long, too-many-arguments
def sqlvm_group_update(instance, domain_fqdn=None, cluster_operator_account=None, sql_service_account=None,
storage_account_url=None, storage_account_key=None, cluster_bootstrap_account=None,
file_share_witness_path=None, ou_path=None, tags=None):
'''
Updates a SQL virtual machine group.
'''
if domain_fqdn is not None:
instance.wsfc_domain_profile.domain_fqdn = domain_fqdn
if cluster_operator_account is not None:
instance.wsfc_domain_profile.cluster_operator_account = cluster_operator_account
if cluster_bootstrap_account is not None:
instance.wsfc_domain_profile.cluster_bootstrap_account = cluster_bootstrap_account
if sql_service_account is not None:
instance.wsfc_domain_profile.sql_service_account = sql_service_account
if storage_account_url is not None:
instance.wsfc_domain_profile.storage_account_url = storage_account_url
if storage_account_key is not None:
instance.wsfc_domain_profile.storage_account_primary_key = storage_account_key
if storage_account_url and not storage_account_key:
instance.wsfc_domain_profile.storage_account_primary_key = prompt_pass('Storage Key: ', confirm=True)
if file_share_witness_path is not None:
instance.wsfc_domain_profile.file_share_witness_path = file_share_witness_path
if ou_path is not None:
instance.wsfc_domain_profile.ou_path = ou_path
if tags is not None:
instance.tags = tags
return instance
# pylint: disable=line-too-long, too-many-boolean-expressions, too-many-arguments
def sqlvm_aglistener_create(client, cmd, availability_group_listener_name, sql_virtual_machine_group_name,
resource_group_name, availability_group_name, ip_address, subnet_resource_id,
load_balancer_resource_id, probe_port, sql_virtual_machine_instances, port=1433,
public_ip_address_resource_id=None, vnet_name=None): # pylint: disable=unused-argument
'''
Creates an availability group listener
'''
# Create the private ip address
private_ip_object = PrivateIPAddress(ip_address=ip_address,
subnet_resource_id=subnet_resource_id
if is_valid_resource_id(subnet_resource_id) else None)
# Create the load balancer configurations
load_balancer_object = LoadBalancerConfiguration(private_ip_address=private_ip_object,
public_ip_address_resource_id=public_ip_address_resource_id,
load_balancer_resource_id=load_balancer_resource_id,
probe_port=probe_port,
sql_virtual_machine_instances=sql_virtual_machine_instances)
# Create the availability group listener object
ag_listener_object = AvailabilityGroupListener(availability_group_name=availability_group_name,
load_balancer_configurations=[load_balancer_object],
port=port)
LongRunningOperation(cmd.cli_ctx)(sdk_no_wait(False, client.begin_create_or_update, resource_group_name,
sql_virtual_machine_group_name, availability_group_listener_name,
ag_listener_object))
return client.get(resource_group_name, sql_virtual_machine_group_name, availability_group_listener_name)
def aglistener_update(instance, sql_virtual_machine_instances=None):
'''
Updates an availability group listener
'''
# Get the list of all current machines in the ag listener
if sql_virtual_machine_instances:
instance.load_balancer_configurations[0].sql_virtual_machine_instances = sql_virtual_machine_instances
return instance
# pylint: disable=too-many-arguments, too-many-locals, line-too-long, too-many-boolean-expressions
def sqlvm_create(client, cmd, sql_virtual_machine_name, resource_group_name, sql_server_license_type=None,
location=None, sql_image_sku=None, enable_auto_patching=None, sql_management_mode="LightWeight",
day_of_week=None, maintenance_window_starting_hour=None, maintenance_window_duration=None,
enable_auto_backup=None, enable_encryption=False, retention_period=None, storage_account_url=None,
storage_access_key=None, backup_password=None, backup_system_dbs=False, backup_schedule_type=None,
full_backup_frequency=None, full_backup_start_time=None, full_backup_window_hours=None, log_backup_frequency=None,
enable_key_vault_credential=None, credential_name=None, azure_key_vault_url=None, service_principal_name=None,
service_principal_secret=None, connectivity_type=None, port=None, sql_auth_update_username=None,
sql_auth_update_password=None, sql_workload_type=None, enable_r_services=None, tags=None, sql_image_offer=None):
'''
Creates a SQL virtual machine.
'''
from azure.cli.core.commands.client_factory import get_subscription_id
subscription_id = get_subscription_id(cmd.cli_ctx)
virtual_machine_resource_id = resource_id(
subscription=subscription_id, resource_group=resource_group_name,
namespace='Microsoft.Compute', type='virtualMachines', name=sql_virtual_machine_name)
tags = tags or {}
# If customer has provided any auto_patching settings, enabling plugin should be True
if (day_of_week or maintenance_window_duration or maintenance_window_starting_hour):
enable_auto_patching = True
auto_patching_object = AutoPatchingSettings(enable=enable_auto_patching,
day_of_week=day_of_week,
maintenance_window_starting_hour=maintenance_window_starting_hour,
maintenance_window_duration=maintenance_window_duration)
# If customer has provided any auto_backup settings, enabling plugin should be True
if (enable_encryption or retention_period or storage_account_url or storage_access_key or backup_password or
backup_system_dbs or backup_schedule_type or full_backup_frequency or full_backup_start_time or
full_backup_window_hours or log_backup_frequency):
enable_auto_backup = True
if not storage_access_key:
storage_access_key = prompt_pass('Storage Key: ', confirm=True)
if enable_encryption and not backup_password:
backup_password = prompt_pass('Backup Password: ', confirm=True)
auto_backup_object = AutoBackupSettings(enable=enable_auto_backup,
enable_encryption=enable_encryption if enable_auto_backup else None,
retention_period=retention_period,
storage_account_url=storage_account_url,
storage_access_key=storage_access_key,
password=backup_password,
backup_system_dbs=backup_system_dbs if enable_auto_backup else None,
backup_schedule_type=backup_schedule_type,
full_backup_frequency=full_backup_frequency,
full_backup_start_time=full_backup_start_time,
full_backup_window_hours=full_backup_window_hours,
log_backup_frequency=log_backup_frequency)
# If customer has provided any key_vault_credential settings, enabling plugin should be True
if (credential_name or azure_key_vault_url or service_principal_name or service_principal_secret):
enable_key_vault_credential = True
if not service_principal_secret:
service_principal_secret = prompt_pass('Service Principal Secret: ', confirm=True)
keyvault_object = KeyVaultCredentialSettings(enable=enable_key_vault_credential,
credential_name=credential_name,
azure_key_vault_url=azure_key_vault_url,
service_principal_name=service_principal_name,
service_principal_secret=service_principal_secret)
connectivity_object = SqlConnectivityUpdateSettings(port=port,
connectivity_type=connectivity_type,
sql_auth_update_user_name=sql_auth_update_username,
sql_auth_update_password=sql_auth_update_password)
workload_type_object = SqlWorkloadTypeUpdateSettings(sql_workload_type=sql_workload_type)
additional_features_object = AdditionalFeaturesServerConfigurations(is_rservices_enabled=enable_r_services)
server_configuration_object = ServerConfigurationsManagementSettings(sql_connectivity_update_settings=connectivity_object,
sql_workload_type_update_settings=workload_type_object,
additional_features_server_configurations=additional_features_object)
sqlvm_object = SqlVirtualMachine(location=location,
virtual_machine_resource_id=virtual_machine_resource_id,
sql_server_license_type=sql_server_license_type,
sql_image_sku=sql_image_sku,
sql_management=sql_management_mode,
sql_image_offer=sql_image_offer,
auto_patching_settings=auto_patching_object,
auto_backup_settings=auto_backup_object,
key_vault_credential_settings=keyvault_object,
server_configurations_management_settings=server_configuration_object,
tags=tags)
# Since it's a running operation, we will do the put and then the get to display the instance.
LongRunningOperation(cmd.cli_ctx)(sdk_no_wait(False, client.begin_create_or_update,
resource_group_name, sql_virtual_machine_name, sqlvm_object))
return client.get(resource_group_name, sql_virtual_machine_name)
# pylint: disable=too-many-statements, line-too-long, too-many-boolean-expressions
def sqlvm_update(instance, sql_server_license_type=None, sql_image_sku=None, enable_auto_patching=None,
day_of_week=None, maintenance_window_starting_hour=None, maintenance_window_duration=None,
enable_auto_backup=None, enable_encryption=False, retention_period=None, storage_account_url=None, prompt=True,
storage_access_key=None, backup_password=None, backup_system_dbs=False, backup_schedule_type=None, sql_management_mode=None,
full_backup_frequency=None, full_backup_start_time=None, full_backup_window_hours=None, log_backup_frequency=None,
enable_key_vault_credential=None, credential_name=None, azure_key_vault_url=None, service_principal_name=None,
service_principal_secret=None, connectivity_type=None, port=None, sql_workload_type=None, enable_r_services=None, tags=None):
'''
Updates a SQL virtual machine.
'''
if tags is not None:
instance.tags = tags
if sql_server_license_type is not None:
instance.sql_server_license_type = sql_server_license_type
if sql_image_sku is not None:
instance.sql_image_sku = sql_image_sku
if sql_management_mode is not None and instance.sql_management != "Full":
from knack.prompting import prompt_y_n
if not prompt:
instance.sql_management = sql_management_mode
else:
confirmation = prompt_y_n("Upgrading SQL manageability mode to Full will restart the SQL Server. Proceed?")
if confirmation:
instance.sql_management = sql_management_mode
if (enable_auto_patching is not None or day_of_week is not None or maintenance_window_starting_hour is not None or maintenance_window_duration is not None):
enable_auto_patching = enable_auto_patching if enable_auto_patching is False else True
instance.auto_patching_settings = AutoPatchingSettings(enable=enable_auto_patching,
day_of_week=day_of_week,
maintenance_window_starting_hour=maintenance_window_starting_hour,
maintenance_window_duration=maintenance_window_duration)
if (enable_auto_backup is not None or enable_encryption or retention_period is not None or storage_account_url is not None or
storage_access_key is not None or backup_password is not None or backup_system_dbs or backup_schedule_type is not None or
full_backup_frequency is not None or full_backup_start_time is not None or full_backup_window_hours is not None or
log_backup_frequency is not None):
enable_auto_backup = enable_auto_backup if enable_auto_backup is False else True
if not storage_access_key:
storage_access_key = prompt_pass('Storage Key: ', confirm=True)
if enable_encryption and not backup_password:
backup_password = prompt_pass('Backup Password: ', confirm=True)
instance.auto_backup_settings = AutoBackupSettings(enable=enable_auto_backup,
enable_encryption=enable_encryption if enable_auto_backup else None,
retention_period=retention_period,
storage_account_url=storage_account_url,
storage_access_key=storage_access_key,
password=backup_password,
backup_system_dbs=backup_system_dbs if enable_auto_backup else None,
backup_schedule_type=backup_schedule_type,
full_backup_frequency=full_backup_frequency,
full_backup_start_time=full_backup_start_time,
full_backup_window_hours=full_backup_window_hours,
log_backup_frequency=log_backup_frequency)
if (enable_key_vault_credential is not None or credential_name is not None or azure_key_vault_url is not None or
service_principal_name is not None or service_principal_secret is not None):
enable_key_vault_credential = enable_key_vault_credential if enable_key_vault_credential is False else True
if not service_principal_secret:
service_principal_secret = prompt_pass('Service Principal Secret: ', confirm=True)
instance.key_vault_credential_settings = KeyVaultCredentialSettings(enable=enable_key_vault_credential,
credential_name=credential_name,
service_principal_name=service_principal_name,
service_principal_secret=service_principal_secret,
azure_key_vault_url=azure_key_vault_url)
instance.server_configurations_management_settings = ServerConfigurationsManagementSettings()
if (connectivity_type is not None or port is not None):
instance.server_configurations_management_settings.sql_connectivity_update_settings = SqlConnectivityUpdateSettings(connectivity_type=connectivity_type,
port=port)
if sql_workload_type is not None:
instance.server_configurations_management_settings.sql_workload_type_update_settings = SqlWorkloadTypeUpdateSettings(sql_workload_type=sql_workload_type)
if enable_r_services is not None:
instance.server_configurations_management_settings.additional_features_server_configurations = AdditionalFeaturesServerConfigurations(is_rservices_enabled=enable_r_services)
# If none of the settings was modified, reset server_configurations_management_settings to be null
if (instance.server_configurations_management_settings.sql_connectivity_update_settings is None and
instance.server_configurations_management_settings.sql_workload_type_update_settings is None and
instance.server_configurations_management_settings.sql_storage_update_settings is None and
instance.server_configurations_management_settings.additional_features_server_configurations is None):
instance.server_configurations_management_settings = None
return instance
def sqlvm_add_to_group(client, cmd, sql_virtual_machine_name, resource_group_name,
sql_virtual_machine_group_resource_id, sql_service_account_password=None,
cluster_operator_account_password=None, cluster_bootstrap_account_password=None):
'''
Adds a SQL virtual machine to a group.
'''
sqlvm_object = client.get(resource_group_name, sql_virtual_machine_name)
if not sql_service_account_password:
sql_service_account_password = prompt_pass('SQL Service account password: ', confirm=True)
if not cluster_operator_account_password:
cluster_operator_account_password = prompt_pass('Cluster operator account password: ', confirm=True,
help_string='Password to authenticate with the domain controller.')
sqlvm_object.sql_virtual_machine_group_resource_id = sql_virtual_machine_group_resource_id
sqlvm_object.wsfc_domain_credentials = WsfcDomainCredentials(cluster_bootstrap_account_password=cluster_bootstrap_account_password,
cluster_operator_account_password=cluster_operator_account_password,
sql_service_account_password=sql_service_account_password)
# Since it's a running operation, we will do the put and then the get to display the instance.
LongRunningOperation(cmd.cli_ctx)(sdk_no_wait(False, client.begin_create_or_update,
resource_group_name, sql_virtual_machine_name, sqlvm_object))
return client.get(resource_group_name, sql_virtual_machine_name)
def sqlvm_remove_from_group(client, cmd, sql_virtual_machine_name, resource_group_name):
'''
Removes a SQL virtual machine from a group.
'''
sqlvm_object = client.get(resource_group_name, sql_virtual_machine_name)
sqlvm_object.sql_virtual_machine_group_resource_id = None
sqlvm_object.wsfc_domain_credentials = None
# Since it's a running operation, we will do the put and then the get to display the instance.
LongRunningOperation(cmd.cli_ctx)(sdk_no_wait(False, client.begin_create_or_update,
resource_group_name, sql_virtual_machine_name, sqlvm_object))
return client.get(resource_group_name, sql_virtual_machine_name)
| |
import cherrypy
import demjson
from tickets import *
from mailing import sendMail#, sendNewTicketNotifications, sendEditTicketNotifications, sendNewCommentNotifications, sendDeleteNotifications
from postgres import getConnection
from security import *
from urls import setRoutes
from various import *
from webfaction import createEMail
from mako.template import Template
import md5
import re
from cherrypy.lib.static import serve_file
import mimetypes
import os.path
_curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
class Naphtaline :
""" The one and only class of the Naphtaline projects.
"""
#_cp_config = { 'tools.sessions.on': True }
def __init__(self) :
# parameters of the application
#self.enableManagementByMail = False
pass
def projects(self, project, category, ticketID=None):
""" Main method of the Class.
projects will display the ticket of relative id (ie this is not the real
id of the ticket, but the one that will be displayed, in order to get
consistency through notations) 'idTicket'
"""
# creating connection
con = getConnection()
# getting project lang (used to select templates afterwars)
lang = projectLang(con, project)
# verifications to ensure that the page can be displayed
# this is necessary since values checked here are passed as GET
# and thus easily changed by "curious" users
checkProjectCategoryLogin(con, project, category)
# check that ticketID is a valid ID
if not isTicketIDValid(con, project, category, ticketID):
# go to "new ticket page"
raise cherrypy.HTTPRedirect(url(project, category, 'new'))
# loading details about the selected ticket
# if the idTicket is not OK, then the selectedTicket hash will be empty
selectedTicket = loadSelectedTicket(con, project, category, ticketID)
selectedTicketHTML = self.getTicketHTML(project, lang, category, selectedTicket)
# loading ticket's comments
comments = loadComments(con, project, category, selectedTicket['id'])
commentsHTML = self.getCommentsHTML(project, lang, comments)
# loading all tickets from the selected project in the selected category
# tickets are divided in two lists which are displayed separatly on
# the page
# note that tickets are already sorted
solved = ((selectedTicket['status'] == 1) or (selectedTicket['status'] == 4))
#tickets = loadTickets(con, project, category, solved)
#ticketsList = self.getTicketsListHTML(project, category, solved, lang, tickets, selectedTicket['id'])
ticketsList = self.getTicketsList(project, category, solved, ticketID)
# list of tickets containing modification since last visit
#unread = updatedTickets(con, project, category, idTicket)
# closing connection
con.close()
# generating page through template
mytemplate = Template(filename='templates/'+lang+'/bugs.html',
output_encoding='utf-8',
default_filters=['decode.utf8'],
input_encoding='utf-8')
page = mytemplate.render(
projectWebName = project,
projectName = cherrypy.session.get(str(project)+'_projectName'),
userLevel = cherrypy.session.get(str(project)+'_loginLevel', 1),
category = category,
ticketsList = ticketsList,
selectedTicketRelativeID = selectedTicket['id'],
selectedTicketHTML = selectedTicketHTML,
comments = commentsHTML,
solved = solved
)
return page
def getTicketHTML(self, project, lang, category, ticket):
mytemplate = Template(filename='templates/'+lang+'/ticket.html',
output_encoding='utf-8',
default_filters=['decode.utf8'],
input_encoding='utf-8')
page = mytemplate.render(
projectWebName = project,
category = category,
ticket = ticket,
userID = cherrypy.session.get(str(project)+'_idUser', 1),
userLevel = cherrypy.session.get(str(project)+'_loginLevel', 1))
return page
def search(self, project, search=''):
con = getConnection()
checkProjectLogin(con, project)
lang = projectLang(con, project)
cursor = con.cursor()
query = """
SELECT name FROM Project WHERE webname = %s"""
cursor.execute(query, (project, ))
projectName = cursor.fetchone()[0]
mytemplate = Template(filename='templates/'+lang+'/search.html', output_encoding='utf-8', default_filters=['decode.utf8'], input_encoding='utf-8')
tickets = []
if search is not '':
query = """
SELECT
Ticket.id,
Ticket.name,
Ticket.severity,
Ticket.status,
Ticket.category,
Ticket.relativeID,
ts_rank_cd(
setweight(to_tsvector(%(lang)s, no_accents(coalesce(Ticket.name, ''))), 'A') ||
setweight(to_tsvector(%(lang)s, no_accents(coalesce(Ticket.description, ''))), 'C') ||
setweight(to_tsvector(%(lang)s, no_accents(coalesce(concat_comments(Ticket.id), ''))), 'D'),
plainto_tsquery(%(lang)s,no_accents(%(search)s))) AS rank,
ts_headline(%(lang)s, no_accents(Ticket.name) || ' ' || no_accents(Ticket.description) || ' ' || no_accents(concat_comments(Ticket.id)), plainto_tsquery(%(lang)s, no_accents(%(search)s)))
FROM Ticket
WHERE
project = %(project)s AND
to_tsvector(
%(lang)s,
no_accents(coalesce(Ticket.name, '')) ||
no_accents(coalesce(Ticket.description, '')) ||
no_accents(coalesce(concat_comments(Ticket.id), ''))
) @@ plainto_tsquery(%(lang)s, no_accents(%(search)s))
ORDER BY rank DESC"""
# ADD NEW LANGS HERE
lang_names = {'en': 'english',
'fr': 'french'}
cursor.execute(query,
{'project': cherrypy.session.get(str(project)+'_projectCode'),
'search': search,
'lang': lang_names[lang]})
rows = cursor.fetchall()
tickets = []
for row in rows:
ticket = {'id': int(row[0]),
'name': row[1],
'severity': int(row[2]),
'status': int(row[3]),
'category': int(row[4]),
'relativeID': int(row[5]),
'headline': row[7] }
tickets.append(ticket)
page = mytemplate.render(
projectWebName = project,
projectName = projectName,
userLevel = cherrypy.session.get(str(project)+'_loginLevel', 1),
search = search,
tickets = tickets
)
return page
def saveComment(self, project, category, relativeID, content, files=[]):
""" """
con = getConnection()
checkProjectCategoryLogin(con, project, category)
cursor = con.cursor()
# get ticket ID
query = """
SELECT id
FROM Ticket
WHERE
relativeID = %s
AND project = %s
AND category = %s"""
categoryCode = { 'bug' : 1, 'feature' : 2 }
cursor.execute(query, (relativeID, cherrypy.session.get(str(project)+'_projectCode'), categoryCode[category]) )
row = cursor.fetchone()
ticketID = row[0]
# save comment
query = """
INSERT INTO Comment(author, ticket, content)
VALUES (%s,%s,%s);
SELECT lastval();"""
cursor.execute(query, (cherrypy.session.get(str(project)+'_idUser'), ticketID, formatText(content)) )
commentID = int(cursor.fetchone()[0])
# attaching files to the comment.
query = """
UPDATE File
SET ticket = %s
WHERE id = %s"""
args = []
if type(files) == type('dummy'):
args.append((commentID, files))
elif type(files) == type(['dummy', 'dummy']):
for fileID in files :
args.append( (commentID, fileID) )
cursor.executemany(query, args)
con.commit()
con.close()
return 'ok'
def getTicketsList(self, project, category, solved, selectedTicketRelativeID=0):
"""Retrieve tickets and return html code for the tickets"""
con = getConnection()
checkProjectCategoryLogin(con, project, category)
tickets = loadTickets(con, project, category, solved)
lang = projectLang(con, project)
unread = updatedTickets(con, project, category, selectedTicketRelativeID)
con.close()
ticketsList = self.getTicketsListHTML(project, category, solved, lang, tickets, selectedTicketRelativeID, unread)
return ticketsList
def getTicketsListHTML(self, project, category, solved, lang, tickets, selectedTicketRelativeID=0, unread={'bug':[], 'feature':[]}):
"""Return html for the tickets provided"""
mytemplate = Template(filename='templates/'+lang+'/tickets_list.html', output_encoding='utf-8', default_filters=['decode.utf8'], input_encoding='utf-8')
ticketsList = mytemplate.render(
projectWebName = project,
category = category,
tickets = tickets,
selectedTicketRelativeID = selectedTicketRelativeID,
sortMode = cherrypy.session.get(str(project)+'_sortMode','lastModDown'),
unread = unread[category]
)
return ticketsList
def getCommentsHTML(self, project, lang, comments):
mytemplate = Template(filename='templates/'+lang+'/comments.html', output_encoding='utf-8', default_filters=['decode.utf8'], input_encoding='utf-8')
commentsHTML = mytemplate.render(
projectWebName = project,
comments = comments
)
return commentsHTML
def getCommentsList(self, project, category, ticketRelativeID):
con = getConnection()
checkProjectCategoryLogin(con, project, category)
lang = projectLang(con, project)
comments = loadComments(con, project, category, ticketRelativeID)
commentsHTML = self.getCommentsHTML(project, lang, comments)
return commentsHTML
def ticketForm(self, project, category, status=0, severity=0, name='', description='', files=[], mode='new'):
"""Return formular used for creating and editing tickets"""
con = getConnection()
checkProjectCategoryLogin(con, project, category)
lang = projectLang(con, project)
con.close()
mytemplate = Template(filename='templates/'+lang+'/ticket_form.html', output_encoding='utf-8', default_filters=['decode.utf8'], input_encoding='utf-8')
form = mytemplate.render(
projectWebName = project,
category = category,
status = status,
severity = severity,
name = name,
description = unFormatText(description),
files = files,
userLevel = cherrypy.session.get(str(project)+'_loginLevel', 1),
mode = mode
)
return form
def editTicketForm(self, project, category, ticketRelativeID):
con = getConnection()
checkProjectCategoryLogin(con, project, category)
query = """
SELECT
Ticket.id,
Ticket.name,
Ticket.status,
Ticket.severity,
Ticket.description
FROM Ticket
WHERE
project = %s
AND category = %s
AND relativeID = %s"""
cursor = con.cursor()
categoryCode = {'bug' : 1, 'feature' : 2}
cursor.execute(query, (cherrypy.session.get(str(project)+'_projectCode'), categoryCode[category], ticketRelativeID))
row = cursor.fetchone()
ticketID = row[0]
name = row[1]
status = row[2]
severity = row[3]
description = row[4]
files = []
query = """
SELECT
File.id,
File.name
FROM File
WHERE
File.type = 'ticket'
AND File.ticket = %s"""
cursor.execute(query, ( ticketID, ))
rows = cursor.fetchall()
for row in rows:
files.append({'id': row[0], 'name': row[1]})
page = self.ticketForm(project, category, status, severity, name, description, files, 'edit')
return page
def deleteFile(self, project, id):
"""Delete specified file"""
con = getConnection()
checkProjectLogin(con, project)
cursor = con.cursor()
query="""
SELECT count(*)
FROM File
WHERE id = %s AND project = %s
"""
cursor.execute(query, (id, cherrypy.session.get(str(project)+'_projectCode')))
row = cursor.fetchone()
nb_files = row[0]
if nb_files == 0:
con.close()
return '1' # code for "no such file available"
elif nb_files > 1:
con.close()
return '2' # this should never ever happen, but just in case: "more than one file was found"
else:
# delete file from database
query = """
DELETE FROM File
WHERE id = %s AND project = %s
"""
cursor.execute(query, (id, cherrypy.session.get(str(project)+'_projectCode')))
con.commit()
con.close()
# delete file from HDD
try :
os.remove('files/'+str(id))
except :
pass
# all went well
return '0'
def addFile(self, project, file_type, file, **kwargs):
"""Save uploaded file on HDD and in the database"""
con = getConnection()
checkProjectLogin(con, project)
cursor = con.cursor()
# insert file into database
query = """
INSERT INTO File (project, name, type)
VALUES (%s, %s, %s);
SELECT lastval();
"""
cursor.execute(query, (cherrypy.session.get(str(project)+'_projectCode'), formatFileName(file.filename), file_type))
con.commit()
id = int(cursor.fetchone()[0])
con.close()
# saving the file on the disk
f = open('files/'+str(id), 'w')
f.write(file.value)
f.close()
# we cannot send back a JSON object for ajaxUpload only takes string as input
# since data to send back is made only of the id, a simple string should be enough
return 'ok:'+str(id)
def saveTicket(self, project, category, status, severity, name, description, files=[], **kwargs):
"""Save newly created ticket into the database"""
con = getConnection()
checkProjectCategoryLogin(con, project, category)
cursor = con.cursor()
categoryCode = {'bug' : 1, 'feature' : 2}
# if ticket is created with status "being taken care of" or "solved", then the user is an admin
# he is considered as the one who solved or is taking care of the issue.
idMaintainer = 0
if int(status) == 1 or int(status) == 2 :
idMaintainer = cherrypy.session.get(str(project)+'_idUser')
# saving ticket and getting the id of that ticket
query = """
INSERT INTO Ticket(project, category, name, description, status, severity, creator, maintainer)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s);
SELECT lastval();
"""
cursor.execute(query, (
cherrypy.session.get(str(project)+'_projectCode'),
categoryCode[category],
name,
formatText(description),
status,
severity,
cherrypy.session.get(str(project)+'_idUser'),
idMaintainer)
)
# id of that last ticket created
id = int(cursor.fetchone()[0])
# relativeID of that last ticket
query = """
SELECT relativeID FROM Ticket WHERE id = %s"""
cursor.execute(query, (id, ))
relativeID = int(cursor.fetchone()[0])
# attaching files to the ticket
query = """
UPDATE File
SET ticket = %s
WHERE id = %s"""
args = []
if type(files) == type('dummy'):
args.append((id, files))
elif type(files) == type(['dummy', 'dummy']):
for fileID in files :
args.append( (id, fileID) )
cursor.executemany(query, args)
con.commit()
con.close()
data = {'error_code': 0,
'relativeID': relativeID};
return demjson.encode(data);
def newTicket(self, project, category):
""" newTicket page
This method only returns the new page
"""
con = getConnection()
checkProjectCategoryLogin(con, project, category)
cursor = con.cursor()
#unread = updatedTickets(con, project, category)
lang = projectLang(con, project)
con.close()
mytemplate = Template(filename='templates/'+lang+'/create.html', output_encoding='utf-8', default_filters=['decode.utf8'], input_encoding='utf-8')
page = mytemplate.render(
projectWebName = project,
projectName = cherrypy.session.get(str(project)+'_projectName'),
userLevel = cherrypy.session.get(str(project)+'_loginLevel', 1),
category = category,
ticketForm = self.ticketForm(project, category),
ticketsList = self.getTicketsList(project, category, False)
)
return page
def editTicket(self, project, category, relativeID, status, severity, name, description, files=[]):
""" editTicket page
It works in the same way as newTicket does, but when all arguments are empty, we load values from the DB
"""
con = getConnection()
checkProjectCategoryLogin(con, project, category)
checkSuperUserOrCreator(con, project, category, relativeID)
categoryCode = {'bug' : 1, 'feature' : 2}
cursor = con.cursor()
lang = projectLang(con, project)
# we now have a well defined session
userID = cherrypy.session.get(str(project)+'_id')
level = cherrypy.session.get(str(project)+'_loginLevel', 1)
idMaintainer = cherrypy.session.get(str(project)+'_idUser', 0)
# updating ticket
query = """
UPDATE Ticket
SET
name = %s,
description = %s,
status = %s,
severity = %s,
maintainer = %s,
lastModification = current_timestamp
WHERE
relativeID = %s
AND project = %s
AND category = %s"""
description = formatText(description)
cursor.execute(query, (name, description, status, severity, idMaintainer, relativeID, cherrypy.session.get(str(project)+'_projectCode'), categoryCode[category] ))
# select real id
query = """
SELECT id FROM Ticket
WHERE project = %s AND relativeID = %s AND category = %s
"""
cursor.execute(query, (cherrypy.session.get(str(project)+'_projectCode'), relativeID, categoryCode[category] ))
ticketID = int(cursor.fetchone()[0])
# attaching files to the ticket
query = """
UPDATE File
SET ticket = %s
WHERE id = %s"""
args = []
if type(files) == type('dummy'):
args.append((ticketID, files))
elif type(files) == type(['dummy', 'dummy']):
for fileID in files :
args.append( (ticketID, fileID) )
cursor.executemany(query, args)
con.commit()
con.close()
res = {'relativeID' : relativeID}
return demjson.encode(res)
def deleteTicket(self, project, category, ticketID) :
""" deleteTicket page
Deletes the ticket, all files attached, all comments and all of comments' files.
Then redirects to the home of the category.
"""
con = getConnection()
checkProjectCategoryLogin(con, project, category)
checkSuperUserOrCreator(con, project, category, ticketID)
lang = projectLang(con, project)
categoryCode = {'bug' : 1, 'feature' : 2}
cursor = con.cursor()
# selecting real id
query = """
SELECT id
FROM Ticket
WHERE
relativeID = %s
AND project = %s
AND category = %s"""
categoryCode = { 'bug' : 1, 'feature' : 2 }
cursor.execute(query, (ticketID, cherrypy.session.get(str(project)+'_projectCode'), categoryCode[category]) )
row = cursor.fetchone()
id = row[0]
# delete file
# on the disk
query = """
SELECT id FROM File
WHERE
( type = 'ticket' AND ticket = %s )
OR ( type='comment' AND ticket in (SELECT id FROM Comment WHERE ticket = %s) )
"""
cursor.execute(query, (id, id ) )
rows = cursor.fetchall()
for row in rows :
file = 'files/'+str(row[0])
try :
os.remove(file)
except :
print 'file not found or at least can\'t be deleted'
# on the db
query = """
DELETE FROM File
WHERE
( type = 'ticket' AND ticket = %s )
OR ( type='comment' AND ticket in (SELECT id FROM Comment WHERE ticket = %s) )
"""
cursor.execute(query, (id, id ) )
# delete comments
query = """
DELETE FROM Comment
WHERE ticket = %s"""
cursor.execute(query, (id, ) )
# delete ticket
query = """
DELETE FROM Ticket
WHERE
relativeID = %s
AND project = %s
AND category = %s
"""
cursor.execute(query, (ticketID, cherrypy.session.get(str(project)+'_projectCode'), categoryCode[category]))
con.commit()
con.close()
return 'ok'
# ERROR METHOD
def raiseError(self) :
""" raising the error page
"""
raise cherrypy.HTTPRedirect( url('new') )
# LOGIN METHODS
def logMeIn(self, project=None, category='bug', idTicket=0, login='', password='') :
""" logMeIn form.
"""
con = getConnection()
checkProject(con, project)
lang = projectLang(con, project)
query = "SELECT name FROM project WHERE webname=%s"
cursor = con.cursor()
cursor.execute(query, (project, ))
row = cursor.fetchone()
projectName = row[0]
con.close()
mytemplate = Template(filename='templates/'+lang+'/login.html', output_encoding='utf-8', default_filters=['decode.utf8'], input_encoding='utf-8')
page = mytemplate.render(
projectWebName = project,
projectName = projectName,
login = login,
category = category,
password = password,
idTicket = idTicket,
error = '',
comingFrom = cherrypy.session.get(str(project)+'_previousPage', url(project))
)
return page
def doLogin(self, project, login, password):
con = getConnection()
checkProject(con, project)
cursor = con.cursor()
query = """
SELECT
Client.id,
Client.level
FROM Client
INNER JOIN Project
ON Client.project = Project.id
WHERE
Client.login = %s
AND Client.password = %s
AND Project.webname = %s
AND Client.allowed = True
AND Client.isDeleted = False"""
# encoding password
m = md5.new()
m.update(password)
m.update(project)
m.update(login)
cursor.execute(query, (login, m.hexdigest(), project))
# fetching the results
id = None
level = None
rows = cursor.fetchall()
for row in rows :
id = row[0]
level = row[1]
# is the login ok ?
if id == None or level == None:
con.close()
return 'no'
else:
con.close()
# saving to the session
cherrypy.session[str(project)+'_idUser'] = id
cherrypy.session[str(project)+'_loginLevel'] = level
return 'ok'
def disconnect(self, project) :
""" destroy session
"""
try :
cherrypy.session.delete()
except :
pass
raise cherrypy.HTTPRedirect( url(project) )
def register(self, project):
con = getConnection()
checkProject(con, project)
lang = projectLang(con, project)
mytemplate = Template(filename='templates/'+lang+'/register.html', output_encoding='utf-8', default_filters=['decode.utf8'], input_encoding='utf-8')
page = mytemplate.render(
projectWebName = project,
)
return page
def doRegister(self, projectWebName, login, pwd1, pwd2, email):
con = getConnection()
checkProject(con, projectWebName)
lang = projectLang(con, projectWebName)
# clean data
login = login.strip()
pwd1 = pwd1.strip()
pwd2 = pwd2.strip()
email = email.strip()
# check data
errors = { 'equalPwd': True,
'emptyPwd': (pwd1 == '' or pwd2 == ''),
'emptyLogin': login=='',
'emptyEMail': email=='',
'loginTaken': False,
'ok': False}
# pwd1 and pwd2 are equal
if pwd1 != pwd2 :
errors['equalPwd'] = False
# login is already taken
query = """
SELECT count(*) FROM Client
WHERE project = %s AND login = %s"""
cursor = con.cursor()
cursor.execute(query, (cherrypy.session.get(str(projectWebName)+'_projectCode'), login))
if int(cursor.fetchone()[0]) > 0:
errors['loginTaken'] = True
# return errors
if errors['emptyPwd'] or errors['emptyLogin'] or errors['emptyEMail'] or not errors['equalPwd'] or errors['loginTaken']:
return demjson.encode(errors)
# no error were found, just go on with the normal procedure
query = """
INSERT INTO Client(login, password, project, level, allowed, mail)
VALUES (%s, %s, %s, 1, False, %s)"""
m = md5.new()
m.update(pwd1)
m.update(projectWebName)
m.update(login)
cursor.execute(query, (login, m.hexdigest(), cherrypy.session.get(str(projectWebName)+'_projectCode'), email))
con.commit()
# send emails
# to admins
# get projectName
query = """
SELECT name
FROM Project
WHERE Project.id = %s"""
cursor.execute(query, (cherrypy.session.get(str(projectWebName)+'_projectCode'), ))
projectName = cursor.fetchone()[0]
# send mails to all admins
query = """
SELECT login, mail
FROM Client
WHERE project = %s AND level = 2"""
cursor.execute(query, (cherrypy.session.get(str(projectWebName)+'_projectCode'), ))
rows = cursor.fetchall()
for row in rows :
emailTemplate = Template(filename='templates/'+lang+'/mails/new_user.mail', output_encoding='utf-8', default_filters=['decode.utf8'], input_encoding='utf-8')
emailContent = emailTemplate.render(
to = row[1],
userName = row[0],
projectName = projectName,
projectWebName = projectWebName)
sendMail(row[1], emailContent)
# to new user
emailTemplate = Template(filename='templates/'+lang+'/mails/registration.mail', output_encoding='utf-8', default_filters=['decode.utf8'], input_encoding='utf-8')
emailContent = emailTemplate.render(
to = email,
userName = login,
projectName = projectName,
projectWebName = projectWebName,
password = pwd1)
sendMail(email, emailContent)
errors['ok'] = True
return demjson.encode(errors)
def users(self, project):
con = getConnection()
checkProjectLoginLevel(con, project)
lang = projectLang(con, project)
cursor = con.cursor()
query = """
SELECT name FROM Project WHERE id = %s"""
cursor.execute(query, (cherrypy.session.get(str(project)+'_projectCode'), ))
projectName = cursor.fetchone()[0]
# get users
query = """
SELECT
CLient.id,
Client.login,
Client.mail,
Client.level,
Client.allowed,
Client.isDeleted
FROM Client
WHERE project = %s"""
cursor.execute(query, (cherrypy.session.get(str(project)+'_projectCode'), ))
rows = cursor.fetchall()
users = []
requests = []
deleted = []
for row in rows:
isDeleted = row[5]
isAllowed = row[4]
if isDeleted:
deleted.append({'id': row[0], 'login': row[1], 'mail': row[2], 'level': row[3]})
elif isAllowed:
users.append({'id': row[0], 'login': row[1], 'mail': row[2], 'level': row[3]})
else:
requests.append({'id': row[0], 'login': row[1], 'mail': row[2], 'level': row[3]})
con.close()
mytemplate = Template(filename='templates/'+lang+'/users.html', output_encoding='utf-8', default_filters=['decode.utf8'], input_encoding='utf-8')
page = mytemplate.render(
projectWebName = project,
projectName = projectName,
users = users,
requests = requests,
deletedUsers = deleted
)
return page
def deleteUser(self, project, userID):
con = getConnection()
checkProjectLoginLevel(con, project)
lang = projectLang(con, project)
cursor = con.cursor()
# check that user does exist
query = """
SELECT count(*) FROM Client WHERE project = %s AND id = %s"""
cursor.execute(query, (cherrypy.session.get(str(project)+'_projectCode'), userID))
n = int(cursor.fetchone()[0])
if n == 1:
# check that user is not the project's owner
query = """
SELECT owner FROM Project WHERE id = %s"""
cursor.execute(query, (cherrypy.session.get(str(project)+'_projectCode'), ))
row = cursor.fetchone()
ownerID = row[0]
if int(ownerID) != int(userID) :
# send revocation or rejection email
query = """
SELECT Client.mail, Client.login, Project.webname, Project.name, Client.allowed
FROM Client
INNER JOIN Project
ON Client.project = Project.id
WHERE Client.project = %s AND Client.id = %s"""
cursor.execute(query, (cherrypy.session.get(str(project)+'_projectCode'), userID))
row = cursor.fetchone()
mail = row[0]
userName = row[1]
projectWebName = row[2]
projectName = row[3]
isAllowed = row[4]
if isAllowed:
mailType = 'revocation'
else:
mailType = 'rejection'
emailTemplate = Template(filename='templates/'+lang+'/mails/'+mailType+'.mail', output_encoding='utf-8', default_filters=['decode.utf8'], input_encoding='utf-8')
email = emailTemplate.render(
to = mail,
userName = userName,
projectName = projectName,
projectWebName = projectWebName,
)
sendMail(mail, email)
# delete user
# if the user was already in the project, we don't really delete it
# we just set isDeleted to True so that he can't log in anymore
if isAllowed:
query = """
UPDATE Client
SET isDeleted = True
WHERE project = %s AND id = %s"""
else:
query = """
DELETE FROM Client WHERE project = %s AND id = %s"""
cursor.execute(query, (cherrypy.session.get(str(project)+'_projectCode'), userID))
con.commit()
con.close()
return 'ok'
else:
con.close()
return 'owner'
else:
con.close()
return 'no'
def acceptUser(self, project, userID, level):
con = getConnection()
checkProjectLoginLevel(con, project)
lang = projectLang(con, project)
cursor = con.cursor()
# check that level is a valid value
if int(level) is not 1 and int(level) is not 2:
con.close()
return 'no'
# check that user does exist
query = """
SELECT count(*) FROM Client WHERE project = %s AND id = %s AND allowed = False"""
cursor.execute(query, (cherrypy.session.get(str(project)+'_projectCode'), userID))
n = int(cursor.fetchone()[0])
if n == 1:
# accept user
query = """
UPDATE Client SET allowed = True AND level = %s WHERE project = %s AND id = %s"""
cursor.execute(query, (level, cherrypy.session.get(str(project)+'_projectCode'), userID))
con.commit()
# send him an email to let him know he's in
query = """
SELECT Client.mail, Client.login, Project.webname, Project.name
FROM Client
INNER JOIN Project
ON Client.project = Project.id
WHERE Client.project = %s AND Client.id = %s"""
cursor.execute(query, (cherrypy.session.get(str(project)+'_projectCode'), userID))
row = cursor.fetchone()
mail = row[0]
userName = row[1]
projectWebName = row[2]
projectName = row[3]
emailTemplate = Template(filename='templates/'+lang+'/mails/acceptation.mail', output_encoding='utf-8', default_filters=['decode.utf8'], input_encoding='utf-8')
email = emailTemplate.render(
to = mail,
userName = userName,
projectName = projectName,
projectWebName = projectWebName,
)
sendMail(mail, email)
con.close()
return 'ok'
else:
con.close()
return 'no'
def updateUserLevel(self, project, userID, level):
con = getConnection()
checkProjectLoginLevel(con, project)
lang = projectLang(con, project)
cursor = con.cursor()
# check that level is a valid value
if int(level) is not 1 and int(level) is not 2:
con.close()
return 'no'
# check that user does exist
query = """
SELECT count(*) FROM Client WHERE project = %s AND id = %s"""
cursor.execute(query, (cherrypy.session.get(str(project)+'_projectCode'), userID))
n = int(cursor.fetchone()[0])
if n == 1:
# update user level
query = """
UPDATE Client SET level = %s WHERE project = %s AND id = %s"""
cursor.execute(query, (level, cherrypy.session.get(str(project)+'_projectCode'), userID))
con.commit()
# send him a mail to let him know his new status
query = """
SELECT Client.mail, Client.login, Project.webname, Project.name
FROM Client
INNER JOIN Project
ON Client.project = Project.id
WHERE Client.project = %s AND Client.id = %s"""
cursor.execute(query, (cherrypy.session.get(str(project)+'_projectCode'), userID))
row = cursor.fetchone()
mail = row[0]
userName = row[1]
projectWebName = row[2]
projectName = row[3]
emailTemplate = Template(filename='templates/'+lang+'/mails/modification.mail', output_encoding='utf-8', default_filters=['decode.utf8'], input_encoding='utf-8')
email = emailTemplate.render(
to = mail,
userName = userName,
projectName = projectName,
projectWebName = projectWebName,
level = level
)
sendMail(mail, email)
con.close()
return 'ok'
else:
con.close()
return 'no'
def sendInvitations(self, project, to, msg) :
""" sendInvitations page
This is not a real page. It sends all invitations sent using the form found on the manageUsers page but has not a page on its own.
The page displayed at the end is the manageUsers one, with a message to confirm that mails were sent.
"""
con = getConnection()
checkProjectLoginLevel(con, project)
cursor = con.cursor()
lang = projectLang(con, project)
# getting author name
query = """
SELECT login
FROM Client
WHERE id = %s AND project = %s"""
cursor.execute(query, (cherrypy.session.get(str(project)+'_idUser'), cherrypy.session.get(str(project)+'_projectCode') ) )
rows = cursor.fetchall()
author = 'unknown user'
for row in rows :
author = row[0]
# processing "to" field (ie mail addresses)
mails = to.split(';')
for mail in mails :
mail = mail.strip()
emailTemplate = Template(filename='templates/'+lang+'/mails/invitation.mail', output_encoding='utf-8', default_filters=['decode.utf8'], input_encoding='utf-8')
email = emailTemplate.render(
to = mail,
msg = msg,
author = author,
projectName = cherrypy.session.get(str(project)+'_projectName'),
projectWebName = project
)
sendMail(mail, email)
con.close()
return 'ok'
def newProject(self, lang='en'):
con = getConnection()
con.close()
langs = ['en', 'fr']
if lang not in langs:
lang = 'en'
mytemplate = Template(filename='templates/'+lang+'/new_project.html', output_encoding='utf-8', default_filters=['decode.utf8'], input_encoding='utf-8')
page = mytemplate.render()
return page
def createProject(self, projectName, projectWebName, login, pwd1, pwd2, email, lang):
langs = ['en', 'fr']
if lang not in langs:
lang = 'en'
# clean data
projectName = projectName.strip()
projectWebName = projectWebName.strip().lower()
login = login.strip()
pwd1 = pwd1.strip()
pwd2 = pwd2.strip()
email = email.strip()
# check data
errors = { 'validChars': True,
'equalPwd': True,
'validProjectWebName': True,
'emptyPwd': (pwd1 == '' or pwd2 == ''),
'emptyLogin': login=='',
'emptyProjectWebName': projectWebName=='',
'emptyProjectName': projectName == '',
'emptyEMail': email=='',
'ok': False}
# the webname does not contains special chars
validChars = "0123456789abcdefghijklmnopqrstuvwxyz"
for c in projectWebName :
if c not in validChars :
errors['validChars'] = False
# pwd1 and pwd2 are equal
if pwd1 != pwd2 :
errors['equalPwd'] = False
# checking that a project with the same webname does not already exists
con = getConnection()
cursor = con.cursor()
query = """
SELECT count(*)
FROM Project
WHERE webname = %s"""
cursor.execute(query, (projectWebName, ))
row = cursor.fetchone()
if row[0] >= 1 :
errors['validProjectWebName'] = False
# if there are errors, just send them back to the page
error = errors['emptyPwd'] or errors['emptyLogin'] or errors['emptyProjectWebName'] or errors['emptyProjectName'] or errors['emptyEMail']
error = error or not errors['validChars'] or not errors['equalPwd'] or not errors['validProjectWebName']
if error:
return demjson.encode(errors)
# no error were found, just go on with the normal procedure
# create project
query = """
INSERT INTO Project(name, webname, lang)
VALUES (%s, %s, %s)"""
cursor.execute(query, (projectName, projectWebName, lang))
con.commit()
checkProject(con, projectWebName)
# add superuser for the project
query = """
INSERT INTO Client(login, password, project, level, allowed, mail)
VALUES (%s, %s, %s, 2, True, %s);
SELECT lastval();"""
m = md5.new()
m.update(pwd1)
m.update(projectWebName)
m.update(login)
cursor.execute(query, (login, m.hexdigest(), cherrypy.session.get(str(projectWebName)+'_projectCode'), email))
adminID = int(cursor.fetchone()[0])
# updating project owner :
query = """
UPDATE Project
SET owner = %s
WHERE webname = %s"""
cursor.execute(query, (adminID, projectWebName))
con.commit()
con.close()
# send email
emailTemplate = Template(filename='templates/'+lang+'/mails/new_project.mail', output_encoding='utf-8', default_filters=['decode.utf8'], input_encoding='utf-8')
emailContent = emailTemplate.render(
to = email,
userName = login,
projectName = projectName,
projectWebName = projectWebName,
password = pwd1
)
sendMail(email, emailContent)
errors['ok'] = True
return demjson.encode(errors)
def files(self, project, id):
""" Serves the file defined by the id.
"""
con = getConnection()
checkProjectLogin(con, project)
cursor = con.cursor()
# selecting file name
name = None
query = """
SELECT name from File
WHERE project = %s AND id = %s"""
cursor.execute(query, (cherrypy.session.get(str(project)+'_projectCode'), id))
try :
name = cursor.fetchone()[0]
except :
pass
con.close()
# if the file was found in the database
if(name != None) :
# finding mimetype so that file can be served correcly
ext = ""
i = name.rfind('.')
if i != -1:
ext = name[i:].lower()
mimetypes.init()
mimetypes.types_map['.dwg']='image/x-dwg'
mimetypes.types_map['.ico']='image/x-icon'
content_type = mimetypes.types_map.get(ext, "text/plain")
# serving file
return serve_file(os.path.join(_curdir, './files/%s' % id), content_type = content_type, disposition="attachment", name=name)
# the file was not found
else :
raise cherrypy.NotFound
def setSort(self, project, mode):
con = getConnection()
checkProjectLogin(con, project)
con.close()
# all possible modes
modes = ['lastModDown', 'lastModUp', 'idDown', 'idUp', 'severityDown', 'severityUp', 'statusDown', 'statusUp' ]
if mode not in modes :
return 'error: non valid mode'
# saving value
cherrypy.session[str(project)+'_sortMode'] = mode
return 'mode set'
def profile(self, project):
con = getConnection()
checkProjectLogin(con, project)
lang = projectLang(con, project)
cursor = con.cursor()
query = """
SELECT name FROM Project WHERE id = %s"""
cursor.execute(query, (cherrypy.session.get(str(project)+'_projectCode'), ))
projectName = cursor.fetchone()[0]
query="""
SELECT login, level, mail FROM Client WHERE id = %s"""
cursor.execute(query, (cherrypy.session.get(str(project)+'_idUser'), ))
row = cursor.fetchone()
login = row[0]
level = row[1]
mail = row[2]
mytemplate = Template(filename='templates/'+lang+'/profile.html', output_encoding='utf-8', default_filters=['decode.utf8'], input_encoding='utf-8')
page = mytemplate.render(
projectWebName = project,
projectName = projectName,
userLevel = cherrypy.session.get(str(project)+'_loginLevel', 1),
login = login,
mail = mail
)
return page
def updateEMail(self, project, mail):
con = getConnection()
checkProjectLogin(con, project)
cursor = con.cursor()
query = """UPDATE Client SET mail = %s WHERE id = %s"""
cursor.execute(query, (mail, cherrypy.session.get(str(project)+'_idUser')))
con.commit()
con.close()
return 'ok'
def updatePwd(self, project, pwd1, pwd2):
con = getConnection()
checkProjectLogin(con, project)
if pwd1 != pwd2:
con.close()
return 'no'
cursor = con.cursor()
query = """
SELECT login FROM Client WHERE id = %s"""
cursor.execute(query, (cherrypy.session.get(str(project)+'_idUser'), ))
login = cursor.fetchone()[0]
m = md5.new()
m.update(pwd1)
m.update(project)
m.update(login)
query = """
UPDATE Client
SET password = %s
WHERE id = %s AND project = %s"""
cursor.execute(query, (m.hexdigest(), cherrypy.session.get(str(project)+'_idUser'), cherrypy.session.get(str(project)+'_projectCode')))
con.commit()
con.close()
return 'ok'
def lostPassword(self, project):
con = getConnection()
checkProject(con, project)
lang = projectLang(con, project)
mytemplate = Template(filename='templates/'+lang+'/lost_password.html', output_encoding='utf-8', default_filters=['decode.utf8'], input_encoding='utf-8')
page = mytemplate.render(
projectWebName = project,
)
return page
def doLostPassword(self, projectWebName, login):
con = getConnection()
checkProject(con, projectWebName)
lang = projectLang(con, projectWebName)
cursor = con.cursor()
login = login.strip()
query = """
SELECT id, mail FROM Client
WHERE project = %s AND login = %s AND isDeleted = False"""
cursor.execute(query, (cherrypy.session.get(str(projectWebName)+'_projectCode'), login))
rows = cursor.fetchall()
n = 0
for row in rows:
n = n + 1
userID = int(row[0])
mail = row[1]
if n == 0:
return 'not found'
else:
# update the password
newPassword = randomPwd()
# encrypting the password
m = md5.new()
m.update(newPassword)
m.update(projectWebName)
m.update(login)
query = """
UPDATE Client
SET password = %s
WHERE id = %s AND project = %s"""
cursor.execute(query, (m.hexdigest(), userID, cherrypy.session.get(str(projectWebName)+'_projectCode')) )
con.commit()
# sending email with new password
query = """
SELECT name FROM Project WHERE id = %s"""
cursor.execute(query, (cherrypy.session.get(str(projectWebName)+'_projectCode'), ))
projectName = cursor.fetchone()[0]
emailTemplate = Template(filename='templates/'+lang+'/mails/lost_password.mail', output_encoding='utf-8', default_filters=['decode.utf8'], input_encoding='utf-8')
email = emailTemplate.render(
to = mail,
userName = login,
projectName = projectName,
projectWebName = projectWebName,
newPwd = newPassword
)
sendMail(mail, email)
return 'ok'
| |
# Copyright 2018 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.
"""This script is used to synthesize generated parts of this library."""
import synthtool as s
import synthtool.gcp as gcp
import logging
import re
logging.basicConfig(level=logging.DEBUG)
gapic = gcp.GAPICGenerator()
v1_library = gapic.ruby_library(
'spanner', 'v1',
config_path='/google/spanner/artman_spanner.yaml',
artman_output_name='google-cloud-ruby/google-cloud-spanner'
)
s.copy(v1_library / 'lib/google/cloud/spanner/v1')
s.copy(v1_library / 'lib/google/spanner/v1')
s.copy(v1_library / 'test/google/cloud/spanner/v1')
v1_database_library = gapic.ruby_library(
'spanneradmindatabase', 'v1',
config_path='/google/spanner/admin/database/artman_spanner_admin_database.yaml',
artman_output_name='google-cloud-ruby/google-cloud-spanner_admin_database')
s.copy(v1_database_library / 'lib/google/cloud/spanner/admin/database.rb')
s.copy(v1_database_library / 'lib/google/cloud/spanner/admin/database/v1.rb')
s.copy(v1_database_library / 'lib/google/cloud/spanner/admin/database/v1')
s.copy(v1_database_library / 'lib/google/spanner/admin/database/v1')
s.copy(v1_database_library / 'test/google/cloud/spanner/admin/database/v1')
v1_instance_library = gapic.ruby_library(
'spanneradmininstance', 'v1',
config_path='/google/spanner/admin/instance/artman_spanner_admin_instance.yaml',
artman_output_name='google-cloud-ruby/google-cloud-spanner_admin_instance')
s.copy(v1_instance_library / 'lib/google/cloud/spanner/admin/instance.rb')
s.copy(v1_instance_library / 'lib/google/cloud/spanner/admin/instance/v1.rb')
s.copy(v1_instance_library / 'lib/google/cloud/spanner/admin/instance/v1')
s.copy(v1_instance_library / 'lib/google/spanner/admin/instance/v1')
s.copy(v1_instance_library / 'test/google/cloud/spanner/admin/instance/v1')
# Omitting lib/google/cloud/spanner/v1.rb for now because we are not exposing
# the low-level API.
# PERMANENT: We're combining three APIs into one gem.
s.replace(
[
'lib/google/cloud/spanner/admin/database/v1/database_admin_client.rb',
'lib/google/cloud/spanner/admin/instance/v1/instance_admin_client.rb',
],
"Gem.loaded_specs\\['google-cloud-spanner-admin-\\w+'\\]",
"Gem.loaded_specs['google-cloud-spanner']")
s.replace(
[
'lib/google/cloud/spanner/admin/database.rb',
'lib/google/cloud/spanner/admin/database/v1.rb',
'lib/google/cloud/spanner/admin/instance.rb',
'lib/google/cloud/spanner/admin/instance/v1.rb'
],
'# \\$ gem install google-cloud-spanner-admin-\\w+',
'# $ gem install google-cloud-spanner')
# PERMANENT: Handwritten layer owns Spanner.new so low-level clients need to
# use Spanner::V1.new instead of Spanner.new(version: :v1). Update the
# examples and tests.
s.replace(
[
'lib/google/cloud/spanner/v1/spanner_client.rb',
'test/google/cloud/spanner/v1/spanner_client_test.rb'
],
'require "google/cloud/spanner"',
'require "google/cloud/spanner/v1"')
s.replace(
[
'lib/google/cloud/spanner/v1/spanner_client.rb',
'test/google/cloud/spanner/v1/spanner_client_test.rb'
],
'Google::Cloud::Spanner\\.new\\(version: :v1\\)',
'Google::Cloud::Spanner::V1::SpannerClient.new')
# PERMANENT: API names for admin APIs
s.replace(
[
'lib/google/cloud/spanner/admin/database.rb',
'lib/google/cloud/spanner/admin/database/v1.rb',
'lib/google/cloud/spanner/admin/instance.rb',
'lib/google/cloud/spanner/admin/instance/v1.rb'
],
'/spanner-admin-\\w+\\.googleapis\\.com', '/spanner.googleapis.com')
# Support for service_address
s.replace(
[
'lib/google/cloud/spanner/v*/*_client.rb',
'lib/google/cloud/spanner/admin/*/v*/*_client.rb'
],
'\n(\\s+)#(\\s+)@param exception_transformer',
'\n\\1#\\2@param service_address [String]\n' +
'\\1#\\2 Override for the service hostname, or `nil` to leave as the default.\n' +
'\\1#\\2@param service_port [Integer]\n' +
'\\1#\\2 Override for the service port, or `nil` to leave as the default.\n' +
'\\1#\\2@param exception_transformer'
)
s.replace(
[
'lib/google/cloud/spanner/v*/*_client.rb',
'lib/google/cloud/spanner/admin/*/v*/*_client.rb'
],
'\n(\\s+)metadata: nil,\n\\s+exception_transformer: nil,\n',
'\n\\1metadata: nil,\n\\1service_address: nil,\n\\1service_port: nil,\n\\1exception_transformer: nil,\n'
)
s.replace(
[
'lib/google/cloud/spanner/v*/*_client.rb',
'lib/google/cloud/spanner/admin/*/v*/*_client.rb'
],
'service_path = self\\.class::SERVICE_ADDRESS',
'service_path = service_address || self.class::SERVICE_ADDRESS'
)
s.replace(
[
'lib/google/cloud/spanner/v*/*_client.rb',
'lib/google/cloud/spanner/admin/*/v*/*_client.rb'
],
'port = self\\.class::DEFAULT_SERVICE_PORT',
'port = service_port || self.class::DEFAULT_SERVICE_PORT'
)
# https://github.com/googleapis/gapic-generator/issues/2196
s.replace(
[
'lib/google/cloud/spanner/admin/database.rb',
'lib/google/cloud/spanner/admin/database/v1.rb',
'lib/google/cloud/spanner/admin/instance.rb',
'lib/google/cloud/spanner/admin/instance/v1.rb'
],
'\\[Product Documentation\\]: https://cloud\\.google\\.com/spanner-admin-\\w+\n',
'[Product Documentation]: https://cloud.google.com/spanner\n')
# https://github.com/googleapis/gapic-generator/issues/2232
s.replace(
[
'lib/google/cloud/spanner/admin/database/v1/database_admin_client.rb',
'lib/google/cloud/spanner/admin/instance/v1/instance_admin_client.rb'
],
'\n\n(\\s+)class OperationsClient < Google::Longrunning::OperationsClient',
'\n\n\\1# @private\n\\1class OperationsClient < Google::Longrunning::OperationsClient')
# https://github.com/googleapis/gapic-generator/issues/2242
def escape_braces(match):
expr = re.compile('^([^`]*(`[^`]*`[^`]*)*)([^`#\\$\\\\])\\{([\\w,]+)\\}')
content = match.group(0)
while True:
content, count = expr.subn('\\1\\3\\\\\\\\{\\4}', content)
if count == 0:
return content
s.replace(
[
'lib/google/cloud/spanner/v1/**/*.rb',
'lib/google/cloud/spanner/admin/**/*.rb'
],
'\n(\\s+)#[^\n]*[^\n#\\$\\\\]\\{[\\w,]+\\}',
escape_braces)
# https://github.com/googleapis/gapic-generator/issues/2243
s.replace(
[
'lib/google/cloud/spanner/v1/*_client.rb',
'lib/google/cloud/spanner/admin/*/v1/*_client.rb'
],
'(\n\\s+class \\w+Client\n)(\\s+)(attr_reader :\\w+_stub)',
'\\1\\2# @private\n\\2\\3')
# https://github.com/googleapis/gapic-generator/issues/2279
s.replace(
'lib/**/*.rb',
'\\A(((#[^\n]*)?\n)*# (Copyright \\d+|Generated by the protocol buffer compiler)[^\n]+\n(#[^\n]*\n)*\n)([^\n])',
'\\1\n\\6')
# https://github.com/googleapis/gapic-generator/issues/2323
s.replace(
'lib/**/*.rb',
'https://github\\.com/GoogleCloudPlatform/google-cloud-ruby',
'https://github.com/googleapis/google-cloud-ruby'
)
s.replace(
'lib/**/*.rb',
'https://googlecloudplatform\\.github\\.io/google-cloud-ruby',
'https://googleapis.github.io/google-cloud-ruby'
)
# https://github.com/googleapis/google-cloud-ruby/issues/3058
s.replace(
'lib/google/cloud/spanner/admin/database/v1/*_admin_client.rb',
'(require \".*credentials\"\n)\n',
'\\1require "google/cloud/spanner/version"\n\n'
)
s.replace(
'lib/google/cloud/spanner/admin/database/v1/*_admin_client.rb',
'Gem.loaded_specs\[.*\]\.version\.version',
'Google::Cloud::Spanner::VERSION'
)
s.replace(
'lib/google/cloud/spanner/admin/instance/v1/*_admin_client.rb',
'(require \".*credentials\"\n)\n',
'\\1require "google/cloud/spanner/version"\n\n'
)
s.replace(
'lib/google/cloud/spanner/admin/instance/v1/*_admin_client.rb',
'Gem.loaded_specs\[.*\]\.version\.version',
'Google::Cloud::Spanner::VERSION'
)
s.replace(
'lib/google/cloud/spanner/v1/spanner_client.rb',
'(require \".*credentials\"\n)\n',
'\\1require "google/cloud/spanner/version"\n\n'
)
s.replace(
'lib/google/cloud/spanner/v1/spanner_client.rb',
'Gem.loaded_specs\[.*\]\.version\.version',
'Google::Cloud::Spanner::VERSION'
)
# Fix links for devsite migration
s.replace(
'lib/**/*.rb',
'https://googleapis.github.io/google-cloud-ruby/#/docs/google-cloud-logging/latest/google/cloud/logging/logger',
'https://googleapis.dev/ruby/google-cloud-logging/latest'
)
s.replace(
'lib/**/*.rb',
'https://googleapis.github.io/google-cloud-ruby/#/docs/.*/authentication',
'https://googleapis.dev/ruby/google-cloud-spanner/latest/file.AUTHENTICATION.html'
)
| |
# LoPy (MicroPython on ESP32) access to 64-bit timer
import uctypes
# Peripheral map:
# highaddr 4k device
# 3ff0_0 1 dport
# 3ff0_1 1 aes
# 3ff0_2 1 rsa
# 3ff0_3 1 sha
# 3ff0_4 1 secure boot
# 3ff1_0 4 cache mmu table
# 3ff1_f 1 PID controller (per CPU)
# 3ff4_0 1 uart0
# 3ff4_2 1 spi1
# 3ff4_3 1 spi0
# 3ff4_4 1 gpio
# 3ff4_8 1 rtc (also has two blocks of 8k ram)
# 3ff4_9 1 io mux
# 3ff4_b 1 sdio slave (1/3 parts)
# 3ff4_c 1 udma1
# 3ff4_f 1 i2s0
# 3ff5_0 1 uart1
# 3ff5_3 1 i2c0
# 3ff5_4 1 udma0
# 3ff5_5 1 sdio slave (2nd of 3 parts)
# 3ff5_6 1 RMT
# 3ff5_7 1 PCNT
# 3ff5_8 1 sdio slave (3rd of 3 parts)
# 3ff5_9 1 LED PWM
# 3ff5_a 1 Efuse controller
# 3ff5_b 1 flash encryption
# 3ff5_e 1 PWM0
# 3ff5_f 1 TIMG0 (dual 64-bit general timer, tested)
# 3ff6_0 1 TIMG1 (tested)
# 3ff6_4 1 spi2
# 3ff6_5 1 spi3
# 3ff6_6 1 syscon
# 3ff6_7 1 i2c1
# 3ff6_8 1 SD/MMC (Note: only 1-bit wired on expansion board)
# 3ff6_9 2 EMAC
# 3ff6_c 1 pwm1
# 3ff6_d 1 i2s1
# 3ff6_e 1 uart2
# 3ff6_f 1 pwm2
# 3ff7_0 1 pwm3
# 3ff7_5 1 RNG
TIMG0T0_addr = 0x3ff5f000
TIMG0T1_addr = 0x3ff5f024
TIMG1T0_addr = 0x3ff60000
TIMG1T1_addr = 0x3ff60024
TIMG_regs = {
'config': uctypes.UINT32 | 0x00,
# config register layout: bit 31 enable, 30 up (direction),
# bit 29 autoreload at alarm, 13:28 divider
# 12 alarm edge interrupt, 11 alarm level interrupt, 10 alarm enable
'enable': uctypes.BFUINT32 | 0x00 | 31<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'increase': uctypes.BFUINT32 | 0x00 | 30<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
# counts up if increase=1 (default), otherwise down
'autoreload': uctypes.BFUINT32 | 0x00 | 29<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
# reloads value from loadhi:loadlo when timer reaches alarmhi:alarmlo if autoreload=1 (default)
'divider': uctypes.BFUINT32 | 0x00 | 13<<uctypes.BF_POS | (29-13)<<uctypes.BF_LEN,
# divides APB clock (default 80MHz); only change when timer disabled
# default is 1, which produces 2; 0 means 0x10000, others are verbatim.
'edge_int_en': uctypes.BFUINT32 | 0x00 | 12<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'level_int_en': uctypes.BFUINT32 | 0x00 | 12<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'alarm_en': uctypes.BFUINT32 | 0x00 | 12<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
# alarm and interrupts are disabled by default (continous counting)
'lo': uctypes.UINT32 | 0x04,
'hi': uctypes.UINT32 | 0x08,
'update': uctypes.UINT32 | 0x0c, # write to trigger {hi,lo} := current_timer
'alarmlo': uctypes.UINT32 | 0x10,
'alarmhi': uctypes.UINT32 | 0x14,
'loadlo': uctypes.UINT32 | 0x18,
'loadhi': uctypes.UINT32 | 0x1c, # NOTE: Missing in ESP32 TRM 1.1 register summary
'load': uctypes.UINT32 | 0x20, # write to trigger load (current_timer := {loadhi,loadlo})
}
class Timer:
"Crude wrapper class to access 64-bit timer"
def __init__(self, addr):
self.regs = uctypes.struct(addr, TIMG_regs)
def __call__(self, value=None):
# Note: probably not interrupt safe, uses big ints
if value is None:
self.regs.update = 0
return self.regs.hi<<32 | self.regs.lo
else:
self.regs.loadhi = value>>32
self.regs.loadlo = value & 0xffffffff
self.regs.load = 0
def alarm(self, value=None):
if value is None:
return self.regs.alarmhi<<32 | self.regs.alarmlo
else:
self.regs.alarmhi = value>>32
self.regs.alarmlo = value & 0xffffffff
timer = [Timer(addr) for addr in (TIMG0T0_addr, TIMG0T1_addr, TIMG1T0_addr, TIMG1T1_addr)]
# Let's not touch the watchdog and interrupts for now.
# Example:
# timer[0].regs.enable = 1
# timer[0]() # reads timer count
# AES block
AES_addr = 0x3ff01000
AES_128 = 0
AES_192 = 1
AES_256 = 2
AES_enc = 0
AES_dec = 4
# mode = AES_256 | AES_enc
# Endian: FIXME unsure of true orders. they're specified, I just haven't deciphered fully.
# Bit 0 = key ascending byte order within word
# Bit 1 = key ascending word order
# Bit 2 = input text ascending byte order within word
# Bit 3 = input text ascending word order
# Bit 2 = output text ascending byte order within word
# Bit 3 = output text ascending word order
AES_regs = {
'mode': uctypes.UINT32 | 0x008,
'endian': uctypes.UINT32 | 0x040,
'key_0': uctypes.UINT32 | 0x010,
'key_1': uctypes.UINT32 | 0x014,
'key_2': uctypes.UINT32 | 0x018,
'key_3': uctypes.UINT32 | 0x01c,
'key_4': uctypes.UINT32 | 0x020,
'key_5': uctypes.UINT32 | 0x024,
'key_6': uctypes.UINT32 | 0x028,
'key_7': uctypes.UINT32 | 0x02c,
'text_0': uctypes.UINT32 | 0x030,
'text_1': uctypes.UINT32 | 0x034,
'text_2': uctypes.UINT32 | 0x038,
'text_3': uctypes.UINT32 | 0x03c,
'start': uctypes.UINT32 | 0x000, # write 1 to start
'idle': uctypes.UINT32 | 0x004, # 0 while busy, 1 otherwise
}
AES = uctypes.struct(AES_addr, AES_regs)
# Note: AES accelerator doesn't seem to have interrupts. Poll idle.
# It finishes fast anyway (11-15 cycles encrypt, 21-22 decrypt).
# Probably any Python access needn't touch idle.
# GPIO registers (shouldn't be needed, there's machine.Pin)
# TRM summary tables for these are messed up
# w1t[sc] = write 1 to set/clear extras for atomic ops
GPIO_regs = {name: nr*4 | uctypes.UINT32
for (nr, name) in enumerate("""
- out out_w1ts out_w1tc
out1 out1_w1ts out1_w1tc -
enable enable_w1ts enable_w1tc enable1
enable1_w1ts enable1_w1tc strap in_
in1 status status_w1ts status_w1tc
status1 status1_w1ts status1_w1tc
acpu_int acpu_nmi_int pcpu_int pcpu_nmi_int
- acpi_int1 acpi_nmi_int1 pcpu_int1
pcpu_nmi_int1
""".split()) if name!="-"}
# Note: arrays cause allocation, not interrupt safe.
GPIO_regs['pin'] = (uctypes.ARRAY | 0x88, 40, {
# 1 for open drain output
'pad_driver': uctypes.BFUINT32 | 0x00 | 2<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
# disabled rising falling any low high - -
'int_type': uctypes.BFUINT32 | 0x00 | 7<<uctypes.BF_POS | 3<<uctypes.BF_LEN,
'wakeup_enable': uctypes.BFUINT32 | 0x00 | 10<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'int_ena_app': uctypes.BFUINT32 | 0x00 | 13+0<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'int_ena_app_nmi': uctypes.BFUINT32 | 0x00 | 13+1<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'int_ena_pro': uctypes.BFUINT32 | 0x00 | 13+3<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'int_ena_pro_nmi': uctypes.BFUINT32 | 0x00 | 13+4<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
})
# Function block input selection (per function)
GPIO_IN_TIE1 = 0x38
GPIO_IN_TIE0 = 0x30
GPIO_regs['func_in_sel_cfg'] = (uctypes.ARRAY | 0x130, 256, {
# 0=gpio matrix, 1=bypass. reg name: GPIO_SIGm_IN_SEL
'bypass': uctypes.BFUINT32 | 0x00 | 7<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
# invert input value into function block
'func_inv': uctypes.BFUINT32 | 0x00 | 6<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
# selects which gpio matrix input (0-39) or 0x38=high 0x30=low
'gpio': uctypes.BFUINT32 | 0x00 | 0<<uctypes.BF_POS | 6<<uctypes.BF_LEN,
})
# Function block output selection (per pin)
GPIO_OUT_FUNC_GPIO = 0x100
GPIO_regs['func_out_sel_cfg'] = (uctypes.ARRAY | 0x530, 40, {
'oen_inv': uctypes.BFUINT32 | 0x00 | 11<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'func_oen': uctypes.BFUINT32 | 0x00 | 10<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'out_inv': uctypes.BFUINT32 | 0x00 | 11<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
# 0..255=peripheral output, 256=GPIO_DATA_REG
'func': uctypes.BFUINT32 | 0x00 | 0<<uctypes.BF_POS | 9<<uctypes.BF_LEN,
})
GPIO = uctypes.struct(0x3ff44000, GPIO_regs)
# Note: IOmux order is weird, not by GPIO pin number.
IOmux_order = [None if name=='-' else name for name in
"""- GPIO36 GPIO37 GPIO38 GPIO39 GPIO34 GPIO35 GPIO32 GPIO33
GPIO25 GPIO26 GPIO27 MTMS MTDI MTCK MTDO GPIO2 GPIO0 GPIO4
GPIO16 GPIO17 SD_DATA2 SD_DATA3 SD_CMD SD_CLK SD_DATA0 SD_DATA1
GPIO5 GPIO18 GPIO19 GPIO20 GPIO21 GPIO22 U0RXD U0TXD GPIO23
GPIO24""".split()]
IOmux = uctypes.struct(0x3ff53000, (uctypes.ARRAY | 0x10, 40, {
'mcu_sel': uctypes.BFUINT32 | 0 | 12<<uctypes.BF_POS | 3<<uctypes.BF_LEN,
'func_drv': uctypes.BFUINT32 | 0 | 10<<uctypes.BF_POS | 2<<uctypes.BF_LEN,
'func_ie': uctypes.BFUINT32 | 0 | 9<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'func_wpu': uctypes.BFUINT32 | 0 | 8<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'func_wpd': uctypes.BFUINT32 | 0 | 7<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
# mcu prefix applies during sleep mode
'mcu_drv': uctypes.BFUINT32 | 0 | 5<<uctypes.BF_POS | 2<<uctypes.BF_LEN,
'mcu_ie': uctypes.BFUINT32 | 0 | 4<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'mcu_wpu': uctypes.BFUINT32 | 0 | 3<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'mcu_wpd': uctypes.BFUINT32 | 0 | 2<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
# sleep select puts pad in sleep mode
'slp_sel': uctypes.BFUINT32 | 0 | 1<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'mcu_oe': uctypes.BFUINT32 | 0 | 0<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
}))
# Experiments have shown that expboard LED = G16 = P9 = GPIO 12.
# P9 is pin on LoPy, GPIO 12 is in ESP32, perhaps G16 is GPIO on WiPy 1.0.
# The G numbers do match the funny order on WiPy 1.0, which uses CC3200,
# which in turn does have the odd gaps (GPIO 16, 17, 22, 28).
# Could map the P numbers by testing which bits they set as I did for P9.
# Only actually matters if we need to enable peripherals for which MicroPython doesn't work.
# Example of lighting LED on expansion board:
# from machine import Pin
# led = Pin("G16", mode=Pin.OUT) # sets up output enable etc
# led(1) # turns it off
# GPIO.out_w1tc = 1<<12 # turns it on (as led(0))
# GPIO.enable_w1tc = 1<<12 # turns off the output (returns to dim light)
# TODO: why is input dim light? Is there a pulldown?
# LED PWM function block
LEDC_regs = {
'conf': uctypes.UINT32 | 0x190,
'apb_clk_sel': uctypes.BFUINT32 | 0x190 | 0<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'hsch': (uctypes.ARRAY | 0x000, 8, {
# Note: struct is 0x14, per summary table, not register reference
'conf0': uctypes.UINT32 | 0x00, # bitfield:
'timer_sel': uctypes.BFUINT32 | 0x00 | 0<<uctypes.BF_POS | 2<<uctypes.BF_LEN,
'sig_out_en': uctypes.BFUINT32 | 0x00 | 2<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'idle_lv': uctypes.BFUINT32 | 0x00 | 3<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'hpoint': uctypes.UINT32 | 0x04, # 20 bit
'duty': uctypes.UINT32 | 0x08, # 25 bit
'conf1': uctypes.UINT32 | 0x0c,
'duty_scale': uctypes.BFUINT32 | 0x0c | 0<<uctypes.BF_POS | 10<<uctypes.BF_LEN,
'duty_cycle': uctypes.BFUINT32 | 0x0c | 10<<uctypes.BF_POS | 10<<uctypes.BF_LEN, # amount to change duty cycle per cycle
'duty_num': uctypes.BFUINT32 | 0x0c | 20<<uctypes.BF_POS | 10<<uctypes.BF_LEN, # number of times to change it
'duty_inc': uctypes.BFUINT32 | 0x0c | 30<<uctypes.BF_POS | 1<<uctypes.BF_LEN, # increase or decrease
'duty_start': uctypes.BFUINT32 | 0x0c | 31<<uctypes.BF_POS | 1<<uctypes.BF_LEN, # write 1 to make these fields take effect
'duty_r': uctypes.UINT32 | 0x10,
}),
'lsch': (uctypes.ARRAY | 0x0a0, 8, {
# Note: struct is 0x14, per summary table, not register reference
'conf0': uctypes.UINT32 | 0x00, # bitfield:
'timer_sel': uctypes.BFUINT32 | 0x00 | 0<<uctypes.BF_POS | 2<<uctypes.BF_LEN,
'sig_out_en': uctypes.BFUINT32 | 0x00 | 2<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'idle_lv': uctypes.BFUINT32 | 0x00 | 3<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'para_up': uctypes.BFUINT32 | 0x00 | 4<<uctypes.BF_POS | 1<<uctypes.BF_LEN, # updates hpoint and duty
'hpoint': uctypes.UINT32 | 0x04, # 20 bit
'duty': uctypes.UINT32 | 0x08, # 25 bit
'conf1': uctypes.UINT32 | 0x0c,
'duty_scale': uctypes.BFUINT32 | 0x0c | 0<<uctypes.BF_POS | 10<<uctypes.BF_LEN,
'duty_cycle': uctypes.BFUINT32 | 0x0c | 10<<uctypes.BF_POS | 10<<uctypes.BF_LEN, # amount to change duty cycle per cycle
'duty_num': uctypes.BFUINT32 | 0x0c | 20<<uctypes.BF_POS | 10<<uctypes.BF_LEN, # number of times to change it
'duty_inc': uctypes.BFUINT32 | 0x0c | 30<<uctypes.BF_POS | 1<<uctypes.BF_LEN, # increase or decrease
'duty_start': uctypes.BFUINT32 | 0x0c | 31<<uctypes.BF_POS | 1<<uctypes.BF_LEN, # write 1 to make these fields take effect
'duty_r': uctypes.UINT32 | 0x10,
}),
'hstimer': (uctypes.ARRAY | 0x140, 4, {
# bitfield conf
# lim: count goes in range(0,2**lim), max 20
'lim': uctypes.BFUINT32 | 0x0 | 0<<uctypes.BF_POS | 5<<uctypes.BF_LEN,
'div_num': uctypes.BFUINT32 | 0x0 | 5<<uctypes.BF_POS | 18<<uctypes.BF_LEN, # 10.8 fixed point divider
'pause': uctypes.BFUINT32 | 0x0 | 23<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'rst': uctypes.BFUINT32 | 0x0 | 24<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'tick_sel': uctypes.BFUINT32 | 0x0 | 25<<uctypes.BF_POS | 1<<uctypes.BF_LEN, # 1: apb_clk, 0: ref_clk
'cnt': uctypes.UINT32 | 0x4, # 20 bit
}),
'lstimer': (uctypes.ARRAY | 0x160, 4, {
# bitfield conf
# lim: count goes in range(0,2**lim), max 20
'lim': uctypes.BFUINT32 | 0x0 | 0<<uctypes.BF_POS | 5<<uctypes.BF_LEN,
'div_num': uctypes.BFUINT32 | 0x0 | 5<<uctypes.BF_POS | 18<<uctypes.BF_LEN, # 10.8 fixed point divider
'pause': uctypes.BFUINT32 | 0x0 | 23<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'rst': uctypes.BFUINT32 | 0x0 | 24<<uctypes.BF_POS | 1<<uctypes.BF_LEN,
'tick_sel': uctypes.BFUINT32 | 0x0 | 25<<uctypes.BF_POS | 1<<uctypes.BF_LEN, # 1: apb_clk, 0: ref_clk
'para_up': uctypes.BFUINT32 | 0x0 | 4<<uctypes.BF_POS | 1<<uctypes.BF_LEN, # set to update
'cnt': uctypes.UINT32 | 0x4, # 20 bit
}),
# interrupt bitmasks
# order from lsb: hstimer 0-3 overflow, lstimer 0-3 overflow, duty change end hs 0-7 ls 0-7
'int_raw': uctypes.UINT32 | 0x180, # raw interrupt status bits
'int_st': uctypes.UINT32 | 0x184, # masked interrupt status
'int_ena': uctypes.UINT32 | 0x188, # enables
'int_clr': uctypes.UINT32 | 0x18c, # clear
}
LEDC_addr = 0x3ff59000
LEDC = uctypes.struct(LEDC_addr, LEDC_regs)
# RTC has some special functions also. Finding those registers...
RTCIO_regs = {
# RTC registers are mapped weirdly. Looks like it expects word address,
# yet is mapped to the least significant bits.
'gpio_out': uctypes.BFUINT32 | 0 | 14<<uctypes.BF_POS | 18<<uctypes.BF_LEN,
'gpio_out_w1ts': uctypes.BFUINT32 | 1 | 14<<uctypes.BF_POS | 18<<uctypes.BF_LEN,
'gpio_out_w1tc': uctypes.BFUINT32 | 2 | 14<<uctypes.BF_POS | 18<<uctypes.BF_LEN,
'gpio_enable': uctypes.BFUINT32 | 3 | 14<<uctypes.BF_POS | 18<<uctypes.BF_LEN,
'gpio_enable_w1ts': uctypes.BFUINT32 | 4 | 14<<uctypes.BF_POS | 18<<uctypes.BF_LEN,
'gpio_enable_w1tc': uctypes.BFUINT32 | 5 | 14<<uctypes.BF_POS | 18<<uctypes.BF_LEN,
'gpio_status': uctypes.BFUINT32 | 6 | 14<<uctypes.BF_POS | 18<<uctypes.BF_LEN,
'gpio_status_w1ts': uctypes.BFUINT32 | 7 | 14<<uctypes.BF_POS | 18<<uctypes.BF_LEN,
'gpio_status_w1tc': uctypes.BFUINT32 | 8 | 14<<uctypes.BF_POS | 18<<uctypes.BF_LEN,
'gpio_in': uctypes.BFUINT32 | 9 | 14<<uctypes.BF_POS | 18<<uctypes.BF_LEN,
'gpio_pin': (uctypes.ARRAY | 0x0a, 18, {
'pad_driver': uctypes.BFUINT32 | 0 | 2<<uctypes.PF_POS | 1<<uctypes.BF_LEN,
'int_type': uctypes.BFUINT32 | 0 | 7<<uctypes.PF_POS | 3<<uctypes.BF_LEN,
'wakeup_enable': uctypes.BFUINT32 | 0 | 10<<uctypes.PF_POS | 1<<uctypes.BF_LEN,
}),
'dig_pad_hold': uctypes.UINT32 | 0x1d,
'hall_sens': uctypes.UINT32 | 0x1e,
'sensor_pads': uctypes.UINT32 | 0x1f,
'adc_pad': uctypes.UINT32 | 0x20,
'pad_dac1': uctypes.UINT32 | 0x21,
'pad_dac2': uctypes.UINT32 | 0x22,
'xtal_32k_pad': uctypes.UINT32 | 0x23,
'touch_cfg': uctypes.UINT32 | 0x24,
# Erm.. I don't think uctypes will like an array of 10 overlapping words.
#'touch_pad': (uctypes.ARRAY | 0x25, uctypes.UINT32 | 0x24,
'ext_wakeup0': uctypes.UINT32 | 0x2f,
'xtl_ext_ctr': uctypes.UINT32 | 0x30,
'sar_i2c_io': uctypes.UINT32 | 0x31,
}
RTCIO = uctypes.struct(0x3ff48000, RTCIO_regs)
# module control!
DPORT = uctypes.struct(0x3ff00000, {
'perip_clk_en': (0x0c0, {'rmt': uctypes.BFUINT32 | 0 | 9<<uctypes.BF_POS | 1<<uctypes.BF_LEN}),
'perip_rst_en': (0x0c4, {'rmt': uctypes.BFUINT32 | 0 | 9<<uctypes.BF_POS | 1<<uctypes.BF_LEN}),
})
# Bit 9 is the RMT
| |
import numpy as np
import pyflux as pf
import pandas as pd
data = pd.read_csv('http://www.pyflux.com/notebooks/eastmidlandsderby.csv')
total_goals = pd.DataFrame(data['Forest'] + data['Derby'])
data = total_goals.values.T[0]
def test_poisson_couple_terms():
"""
Tests latent variable list length is correct, and that the estimated
latent variables are not nan
"""
model = pf.GASLLT(data=data, family=pf.Poisson())
x = model.fit()
assert(len(model.latent_variables.z_list) == 2)
lvs = np.array([i.value for i in model.latent_variables.z_list])
assert(len(lvs[np.isnan(lvs)]) == 0)
def test_poisson_bbvi():
"""
Tests an GAS model estimated with BBVI and that the length of the latent variable
list is correct, and that the estimated latent variables are not nan
"""
"""
model = pf.GASLLT(data=data, family=pf.Poisson())
x = model.fit('BBVI',iterations=100)
assert(len(model.latent_variables.z_list) == 2)
lvs = np.array([i.value for i in model.latent_variables.z_list])
assert(len(lvs[np.isnan(lvs)]) == 0)
"""
def test_poisson_bbvi_mini_batch():
"""
Tests an ARIMA model estimated with BBVI and that the length of the latent variable
list is correct, and that the estimated latent variables are not nan
"""
"""
model = pf.GASLLT(data=data, family=pf.Poisson())
x = model.fit('BBVI',iterations=300, mini_batch=32, map_start=False)
assert(len(model.latent_variables.z_list) == 2)
lvs = np.array([i.value for i in model.latent_variables.z_list])
assert(len(lvs[np.isnan(lvs)]) == 0)
"""
def test_poisson_bbvi_elbo():
"""
Tests that the ELBO increases
"""
"""
model = pf.GASLLT(data=data, family=pf.Poisson())
x = model.fit('BBVI',iterations=300, record_elbo=True, map_start=False)
assert(x.elbo_records[-1]>x.elbo_records[0])
"""
def test_poisson_bbvi_mini_batch_elbo():
"""
Tests that the ELBO increases
"""
"""
model = pf.GASLLT(data=data, family=pf.Poisson())
x = model.fit('BBVI',iterations=200, mini_batch=32, record_elbo=True, map_start=False)
assert(x.elbo_records[-1]>x.elbo_records[0])
"""
def test_poisson_mh():
"""
Tests an GAS model estimated with Metropolis-Hastings and that the length of the
latent variable list is correct, and that the estimated latent variables are not nan
"""
model = pf.GASLLT(data=data, family=pf.Poisson())
x = model.fit('PML')
x = model.fit('M-H', nsims=300)
assert(len(model.latent_variables.z_list) == 2)
lvs = np.array([i.value for i in model.latent_variables.z_list])
assert(len(lvs[np.isnan(lvs)]) == 0)
def test_poisson_laplace():
"""
Tests an GAS model estimated with Laplace approximation and that the length of the
latent variable list is correct, and that the estimated latent variables are not nan
"""
model = pf.GASLLT(data=data, family=pf.Poisson())
x = model.fit('Laplace')
assert(len(model.latent_variables.z_list) == 2)
lvs = np.array([i.value for i in model.latent_variables.z_list])
assert(len(lvs[np.isnan(lvs)]) == 0)
def test_poisson_pml():
"""
Tests a PML model estimated with Laplace approximation and that the length of the
latent variable list is correct, and that the estimated latent variables are not nan
"""
model = pf.GASLLT(data=data, family=pf.Poisson())
x = model.fit('PML')
assert(len(model.latent_variables.z_list) == 2)
lvs = np.array([i.value for i in model.latent_variables.z_list])
assert(len(lvs[np.isnan(lvs)]) == 0)
def test_poisson_predict_length():
"""
Tests that the prediction dataframe length is equal to the number of steps h
"""
model = pf.GASLLT(data=data, family=pf.Poisson())
x = model.fit()
x.summary()
assert(model.predict(h=5).shape[0] == 5)
def test_poisson_predict_is_length():
"""
Tests that the prediction IS dataframe length is equal to the number of steps h
"""
model = pf.GASLLT(data=data, family=pf.Poisson())
x = model.fit()
assert(model.predict_is(h=5).shape[0] == 5)
def test_poisson_predict_nans():
"""
Tests that the predictions are not nans
"""
model = pf.GASLLT(data=data, family=pf.Poisson())
x = model.fit()
x.summary()
assert(len(model.predict(h=5).values[np.isnan(model.predict(h=5).values)]) == 0)
def test_poisson_predict_is_nans():
"""
Tests that the in-sample predictions are not nans
"""
model = pf.GASLLT(data=data, family=pf.Poisson())
x = model.fit()
x.summary()
assert(len(model.predict_is(h=5).values[np.isnan(model.predict_is(h=5).values)]) == 0)
def test_poisson_predict_intervals():
"""
Tests prediction intervals are ordered correctly
"""
model = pf.GASLLT(data=data, family=pf.Poisson())
x = model.fit()
predictions = model.predict(h=10, intervals=True)
assert(np.all(predictions['99% Prediction Interval'].values >= predictions['95% Prediction Interval'].values))
assert(np.all(predictions['95% Prediction Interval'].values >= predictions['5% Prediction Interval'].values))
assert(np.all(predictions['5% Prediction Interval'].values >= predictions['1% Prediction Interval'].values))
def test_poisson_predict_is_intervals():
"""
Tests prediction intervals are ordered correctly
"""
model = pf.GASLLT(data=data, family=pf.Poisson())
x = model.fit()
predictions = model.predict_is(h=10, intervals=True)
assert(np.all(predictions['99% Prediction Interval'].values >= predictions['95% Prediction Interval'].values))
assert(np.all(predictions['95% Prediction Interval'].values >= predictions['5% Prediction Interval'].values))
assert(np.all(predictions['5% Prediction Interval'].values >= predictions['1% Prediction Interval'].values))
def test_poisson_predict_intervals_bbvi():
"""
Tests prediction intervals are ordered correctly
"""
"""
model = pf.GASLLT(data=data, family=pf.Poisson())
x = model.fit('BBVI', iterations=100)
predictions = model.predict(h=10, intervals=True)
assert(np.all(predictions['99% Prediction Interval'].values >= predictions['95% Prediction Interval'].values))
assert(np.all(predictions['95% Prediction Interval'].values >= predictions['5% Prediction Interval'].values))
assert(np.all(predictions['5% Prediction Interval'].values >= predictions['1% Prediction Interval'].values))
"""
def test_poisson_predict_is_intervals_bbvi():
"""
Tests prediction intervals are ordered correctly
"""
"""
model = pf.GASLLT(data=data, family=pf.Poisson())
x = model.fit('BBVI', iterations=100)
predictions = model.predict_is(h=10, intervals=True)
assert(np.all(predictions['99% Prediction Interval'].values >= predictions['95% Prediction Interval'].values))
assert(np.all(predictions['95% Prediction Interval'].values >= predictions['5% Prediction Interval'].values))
assert(np.all(predictions['5% Prediction Interval'].values >= predictions['1% Prediction Interval'].values))
"""
def test_poisson_predict_intervals_mh():
"""
Tests prediction intervals are ordered correctly
"""
"""
model = pf.GASLLT(data=data, family=pf.Poisson())
x = model.fit('PML')
x = model.fit('M-H', nsims=400)
predictions = model.predict(h=10, intervals=True)
assert(np.all(predictions['99% Prediction Interval'].values >= predictions['95% Prediction Interval'].values))
assert(np.all(predictions['95% Prediction Interval'].values >= predictions['5% Prediction Interval'].values))
assert(np.all(predictions['5% Prediction Interval'].values >= predictions['1% Prediction Interval'].values))
"""
def test_poisson_predict_is_intervals_mh():
"""
Tests prediction intervals are ordered correctly
"""
"""
model = pf.GASLLT(data=data, family=pf.Poisson())
x = model.fit('PML')
x = model.fit('M-H', nsims=400)
predictions = model.predict_is(h=2, intervals=True)
assert(np.all(predictions['99% Prediction Interval'].values >= predictions['95% Prediction Interval'].values))
assert(np.all(predictions['95% Prediction Interval'].values >= predictions['5% Prediction Interval'].values))
assert(np.all(predictions['5% Prediction Interval'].values >= predictions['1% Prediction Interval'].values))
"""
def test_poisson_sample_model():
"""
Tests sampling function
"""
"""
model = pf.GASLLT(data=data, family=pf.Poisson())
x = model.fit('BBVI', iterations=100)
sample = model.sample(nsims=100)
assert(sample.shape[0]==100)
assert(sample.shape[1]==len(data)-1)
"""
def test_poisson_ppc():
"""
Tests PPC value
"""
"""
model = pf.GASLLT(data=data, family=pf.Poisson())
x = model.fit('BBVI', iterations=100)
p_value = model.ppc()
assert(0.0 <= p_value <= 1.0)
"""
| |
# Copyright (c) 2016 Clinton Knight
# 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 collections
import copy
import ddt
import mock
from cinder import exception
from cinder import test
from cinder.tests.unit.volume.drivers.netapp.dataontap.client import (
fakes as fake_client)
import cinder.tests.unit.volume.drivers.netapp.dataontap.utils.fakes as fake
import cinder.tests.unit.volume.drivers.netapp.fakes as na_fakes
from cinder.volume.drivers.netapp.dataontap.utils import capabilities
@ddt.ddt
class CapabilitiesLibraryTestCase(test.TestCase):
def setUp(self):
super(CapabilitiesLibraryTestCase, self).setUp()
self.zapi_client = mock.Mock()
self.configuration = self.get_config_cmode()
self.ssc_library = capabilities.CapabilitiesLibrary(
'iSCSI', fake.SSC_VSERVER, self.zapi_client, self.configuration)
self.ssc_library.ssc = fake.SSC
def get_config_cmode(self):
config = na_fakes.create_configuration_cmode()
config.volume_backend_name = 'fake_backend'
return config
def test_check_api_permissions(self):
mock_log = self.mock_object(capabilities.LOG, 'warning')
self.ssc_library.check_api_permissions()
self.zapi_client.check_cluster_api.assert_has_calls(
[mock.call(*key) for key in capabilities.SSC_API_MAP.keys()])
self.assertEqual(0, mock_log.call_count)
def test_check_api_permissions_failed_ssc_apis(self):
def check_cluster_api(object_name, operation_name, api):
if api != 'volume-get-iter':
return False
return True
self.zapi_client.check_cluster_api.side_effect = check_cluster_api
mock_log = self.mock_object(capabilities.LOG, 'warning')
self.ssc_library.check_api_permissions()
self.assertEqual(1, mock_log.call_count)
def test_check_api_permissions_failed_volume_api(self):
def check_cluster_api(object_name, operation_name, api):
if api == 'volume-get-iter':
return False
return True
self.zapi_client.check_cluster_api.side_effect = check_cluster_api
mock_log = self.mock_object(capabilities.LOG, 'warning')
self.assertRaises(exception.VolumeBackendAPIException,
self.ssc_library.check_api_permissions)
self.assertEqual(0, mock_log.call_count)
def test_get_ssc(self):
result = self.ssc_library.get_ssc()
self.assertEqual(fake.SSC, result)
self.assertIsNot(fake.SSC, result)
def test_get_ssc_for_flexvol(self):
result = self.ssc_library.get_ssc_for_flexvol(fake.SSC_VOLUMES[0])
self.assertEqual(fake.SSC.get(fake.SSC_VOLUMES[0]), result)
self.assertIsNot(fake.SSC.get(fake.SSC_VOLUMES[0]), result)
def test_get_ssc_for_flexvol_not_found(self):
result = self.ssc_library.get_ssc_for_flexvol('invalid')
self.assertEqual({}, result)
def test_get_ssc_aggregates(self):
result = self.ssc_library.get_ssc_aggregates()
self.assertEqual(list(fake.SSC_AGGREGATES), result)
def test_update_ssc(self):
mock_get_ssc_flexvol_info = self.mock_object(
self.ssc_library, '_get_ssc_flexvol_info',
mock.Mock(side_effect=[
fake.SSC_FLEXVOL_INFO['volume1'],
fake.SSC_FLEXVOL_INFO['volume2']
]))
mock_get_ssc_dedupe_info = self.mock_object(
self.ssc_library, '_get_ssc_dedupe_info',
mock.Mock(side_effect=[
fake.SSC_DEDUPE_INFO['volume1'],
fake.SSC_DEDUPE_INFO['volume2']
]))
mock_get_ssc_mirror_info = self.mock_object(
self.ssc_library, '_get_ssc_mirror_info',
mock.Mock(side_effect=[
fake.SSC_MIRROR_INFO['volume1'],
fake.SSC_MIRROR_INFO['volume2']
]))
mock_get_ssc_aggregate_info = self.mock_object(
self.ssc_library, '_get_ssc_aggregate_info',
mock.Mock(side_effect=[
fake.SSC_AGGREGATE_INFO['volume1'],
fake.SSC_AGGREGATE_INFO['volume2']
]))
ordered_ssc = collections.OrderedDict()
ordered_ssc['volume1'] = fake.SSC_VOLUME_MAP['volume1']
ordered_ssc['volume2'] = fake.SSC_VOLUME_MAP['volume2']
result = self.ssc_library.update_ssc(ordered_ssc)
self.assertIsNone(result)
self.assertEqual(fake.SSC, self.ssc_library.ssc)
mock_get_ssc_flexvol_info.assert_has_calls([
mock.call('volume1'), mock.call('volume2')])
mock_get_ssc_dedupe_info.assert_has_calls([
mock.call('volume1'), mock.call('volume2')])
mock_get_ssc_mirror_info.assert_has_calls([
mock.call('volume1'), mock.call('volume2')])
mock_get_ssc_aggregate_info.assert_has_calls([
mock.call('aggr1'), mock.call('aggr2')])
def test__update_for_failover(self):
self.mock_object(self.ssc_library, 'update_ssc')
flexvol_map = {'volume1': fake.SSC_VOLUME_MAP['volume1']}
mock_client = mock.Mock(name='FAKE_ZAPI_CLIENT')
self.ssc_library._update_for_failover(mock_client, flexvol_map)
self.assertEqual(mock_client, self.ssc_library.zapi_client)
self.ssc_library.update_ssc.assert_called_once_with(flexvol_map)
@ddt.data({'lun_space_guarantee': True},
{'lun_space_guarantee': False})
@ddt.unpack
def test_get_ssc_flexvol_info_thin_block(self, lun_space_guarantee):
self.ssc_library.configuration.netapp_lun_space_reservation = \
'enabled' if lun_space_guarantee else 'disabled'
self.mock_object(self.ssc_library.zapi_client,
'get_flexvol',
mock.Mock(return_value=fake_client.VOLUME_INFO_SSC))
result = self.ssc_library._get_ssc_flexvol_info(
fake_client.VOLUME_NAMES[0])
expected = {
'netapp_thin_provisioned': 'true',
'thick_provisioning_support': False,
'thin_provisioning_support': True,
'netapp_aggregate': 'fake_aggr1',
}
self.assertEqual(expected, result)
self.zapi_client.get_flexvol.assert_called_once_with(
flexvol_name=fake_client.VOLUME_NAMES[0])
@ddt.data({'vol_space_guarantee': 'file', 'lun_space_guarantee': True},
{'vol_space_guarantee': 'volume', 'lun_space_guarantee': True})
@ddt.unpack
def test_get_ssc_flexvol_info_thick_block(self, vol_space_guarantee,
lun_space_guarantee):
self.ssc_library.configuration.netapp_lun_space_reservation = \
'enabled' if lun_space_guarantee else 'disabled'
fake_volume_info_ssc = copy.deepcopy(fake_client.VOLUME_INFO_SSC)
fake_volume_info_ssc['space-guarantee'] = vol_space_guarantee
self.mock_object(self.ssc_library.zapi_client,
'get_flexvol',
mock.Mock(return_value=fake_volume_info_ssc))
result = self.ssc_library._get_ssc_flexvol_info(
fake_client.VOLUME_NAMES[0])
expected = {
'netapp_thin_provisioned': 'false',
'thick_provisioning_support': lun_space_guarantee,
'thin_provisioning_support': not lun_space_guarantee,
'netapp_aggregate': 'fake_aggr1',
}
self.assertEqual(expected, result)
self.zapi_client.get_flexvol.assert_called_once_with(
flexvol_name=fake_client.VOLUME_NAMES[0])
@ddt.data({'nfs_sparsed_volumes': True},
{'nfs_sparsed_volumes': False})
@ddt.unpack
def test_get_ssc_flexvol_info_thin_file(self, nfs_sparsed_volumes):
self.ssc_library.protocol = 'nfs'
self.ssc_library.configuration.nfs_sparsed_volumes = \
nfs_sparsed_volumes
self.mock_object(self.ssc_library.zapi_client,
'get_flexvol',
mock.Mock(return_value=fake_client.VOLUME_INFO_SSC))
result = self.ssc_library._get_ssc_flexvol_info(
fake_client.VOLUME_NAMES[0])
expected = {
'netapp_thin_provisioned': 'true',
'thick_provisioning_support': False,
'thin_provisioning_support': True,
'netapp_aggregate': 'fake_aggr1',
}
self.assertEqual(expected, result)
self.zapi_client.get_flexvol.assert_called_once_with(
flexvol_name=fake_client.VOLUME_NAMES[0])
@ddt.data({'vol_space_guarantee': 'file', 'nfs_sparsed_volumes': True},
{'vol_space_guarantee': 'volume', 'nfs_sparsed_volumes': False})
@ddt.unpack
def test_get_ssc_flexvol_info_thick_file(self, vol_space_guarantee,
nfs_sparsed_volumes):
self.ssc_library.protocol = 'nfs'
self.ssc_library.configuration.nfs_sparsed_volumes = \
nfs_sparsed_volumes
fake_volume_info_ssc = copy.deepcopy(fake_client.VOLUME_INFO_SSC)
fake_volume_info_ssc['space-guarantee'] = vol_space_guarantee
self.mock_object(self.ssc_library.zapi_client,
'get_flexvol',
mock.Mock(return_value=fake_volume_info_ssc))
result = self.ssc_library._get_ssc_flexvol_info(
fake_client.VOLUME_NAMES[0])
expected = {
'netapp_thin_provisioned': 'false',
'thick_provisioning_support': not nfs_sparsed_volumes,
'thin_provisioning_support': nfs_sparsed_volumes,
'netapp_aggregate': 'fake_aggr1',
}
self.assertEqual(expected, result)
self.zapi_client.get_flexvol.assert_called_once_with(
flexvol_name=fake_client.VOLUME_NAMES[0])
def test_get_ssc_dedupe_info(self):
self.mock_object(
self.ssc_library.zapi_client, 'get_flexvol_dedupe_info',
mock.Mock(return_value=fake_client.VOLUME_DEDUPE_INFO_SSC))
result = self.ssc_library._get_ssc_dedupe_info(
fake_client.VOLUME_NAMES[0])
expected = {
'netapp_dedup': 'true',
'netapp_compression': 'false',
}
self.assertEqual(expected, result)
self.zapi_client.get_flexvol_dedupe_info.assert_called_once_with(
fake_client.VOLUME_NAMES[0])
@ddt.data(True, False)
def test_get_ssc_mirror_info(self, mirrored):
self.mock_object(
self.ssc_library.zapi_client, 'is_flexvol_mirrored',
mock.Mock(return_value=mirrored))
result = self.ssc_library._get_ssc_mirror_info(
fake_client.VOLUME_NAMES[0])
expected = {'netapp_mirrored': 'true' if mirrored else 'false'}
self.assertEqual(expected, result)
self.zapi_client.is_flexvol_mirrored.assert_called_once_with(
fake_client.VOLUME_NAMES[0], fake.SSC_VSERVER)
def test_get_ssc_aggregate_info(self):
self.mock_object(
self.ssc_library.zapi_client, 'get_aggregate',
mock.Mock(return_value=fake_client.AGGR_INFO_SSC))
self.mock_object(
self.ssc_library.zapi_client, 'get_aggregate_disk_types',
mock.Mock(return_value=fake_client.AGGREGATE_DISK_TYPES))
result = self.ssc_library._get_ssc_aggregate_info(
fake_client.VOLUME_AGGREGATE_NAME)
expected = {
'netapp_disk_type': fake_client.AGGREGATE_DISK_TYPES,
'netapp_raid_type': fake_client.AGGREGATE_RAID_TYPE,
'netapp_hybrid_aggregate': 'true',
}
self.assertEqual(expected, result)
self.zapi_client.get_aggregate.assert_called_once_with(
fake_client.VOLUME_AGGREGATE_NAME)
self.zapi_client.get_aggregate_disk_types.assert_called_once_with(
fake_client.VOLUME_AGGREGATE_NAME)
def test_get_ssc_aggregate_info_not_found(self):
self.mock_object(
self.ssc_library.zapi_client, 'get_aggregate',
mock.Mock(return_value={}))
self.mock_object(
self.ssc_library.zapi_client, 'get_aggregate_disk_types',
mock.Mock(return_value=None))
result = self.ssc_library._get_ssc_aggregate_info(
fake_client.VOLUME_AGGREGATE_NAME)
expected = {
'netapp_disk_type': None,
'netapp_raid_type': None,
'netapp_hybrid_aggregate': None,
}
self.assertEqual(expected, result)
def test_get_matching_flexvols_for_extra_specs(self):
specs = {
'thick_provisioning_support': '<is> False',
'netapp_compression': 'true',
'netapp_dedup': 'true',
'netapp_mirrored': 'true',
'netapp_raid_type': 'raid_dp',
'netapp_disk_type': 'FCAL',
}
result = self.ssc_library.get_matching_flexvols_for_extra_specs(specs)
self.assertEqual(['volume2'], result)
def test_modify_extra_specs_for_comparison(self):
specs = {
'thick_provisioning_support': '<is> False',
'thin_provisioning_support': '<is> true',
'netapp_compression': 'true',
}
result = self.ssc_library._modify_extra_specs_for_comparison(specs)
expected = {
'thick_provisioning_support': False,
'thin_provisioning_support': True,
'netapp_compression': 'true',
}
self.assertEqual(expected, result)
| |
from basic import *
import parse_tsv
from collections import Counter
from itertools import chain
import sys
def show(tcr):
"For debugging"
if type( tcr[0] ) is str:
return ' '.join(tcr[:3])
else:
return ' '.join( show(x) for x in tcr )
# yes, this is very silly, should just add pandas dependency
def parse_csv_file( csvfile ):
header = None
all_info = []
for line in open(csvfile,'rU'):
l = parse_tsv.safely_split_csv_line( line[:-1] )
if header is None:
header = l
else:
all_info.append( dict( zip( header,l ) ) )
return header, all_info
def read_tcr_data(
organism,
contig_annotations_csvfile,
consensus_annotations_csvfile,
include_gammadelta = False,
allow_unknown_genes = False,
verbose = False
):
""" Parse tcr data, only taking 'productive' tcrs
Returns:
clonotype2tcrs, clonotype2barcodes
"""
from all_genes import all_genes
expected_gene_names = all_genes[organism].keys()
#from cdr3s_human import all_align_fasta
gene_suffix = '*01' # may not be used
# read the contig annotations-- map from clonotypes to barcodes
# barcode,is_cell,contig_id,high_confidence,length,chain,v_gene,d_gene,j_gene,c_gene,full_length,productive,cdr3,cdr3_nt,reads,umis,raw_clonotype_id,raw_consensus_id
# AAAGATGGTCTTCTCG-1,True,AAAGATGGTCTTCTCG-1_contig_1,True,695,TRB,TRBV5-1*01,TRBD2*02,TRBJ2-3*01,TRBC2*01,True,True,CASSPLAGYAADTQYF,TGCGCCAGCAGCCCCCTAGCGGGATACGCAGCAGATACGCAGTATTTT,9427,9,clonotype14,clonotype14_consensus_1
assert exists( contig_annotations_csvfile )
_, lines = parse_csv_file(contig_annotations_csvfile)
clonotype2barcodes = {}
clonotype2tcrs_backup = {} ## in case we dont have a consensus_annotations_csvfile
for l in lines:
bc = l['barcode']
clonotype = l['raw_clonotype_id']
if clonotype =='None':
if l['productive'] not in [ 'None','False' ]:
assert l['productive'] == 'True'
#print 'clonotype==None: unproductive?',l['productive']
continue
if clonotype not in clonotype2barcodes:
clonotype2barcodes[clonotype] = []
if bc in clonotype2barcodes[clonotype]:
pass
#print 'repeat barcode'
else:
clonotype2barcodes[clonotype].append( bc )
if not clonotype:
print 'empty clonotype id:', l
continue
assert clonotype
## experimenting here ########################################3
if l['productive'].lower() != 'true':
continue
if l['cdr3'].lower() == 'none' or l['cdr3_nt'].lower() == 'none':
continue
chain = l['chain']
if chain not in ['TRA','TRB']:
continue
ab = chain[2]
if clonotype not in clonotype2tcrs_backup:
clonotype2tcrs_backup[ clonotype ] = {'A':Counter(), 'B':Counter() }
# stolen from below
vg = l['v_gene']
if '*' not in vg:
vg += gene_suffix
if 'DV' in vg and vg not in expected_gene_names:
#print 'DV?',vg
vg = vg[:vg.index('DV')]+'/'+vg[vg.index('DV'):]
jg = l['j_gene']
if '*' not in jg:
jg += gene_suffix
if vg not in expected_gene_names:
print 'unrecognized V gene:', organism, vg
if not allow_unknown_genes:
continue
if jg not in expected_gene_names:
print 'unrecognized J gene:', organism, jg
if not allow_unknown_genes:
continue
#assert vg in all_align_fasta[organism]
#assert jg in all_align_fasta[organism]
tcr_chain = ( vg, jg, l['cdr3'], l['cdr3_nt'].lower() )
clonotype2tcrs_backup[clonotype][ab][tcr_chain] += int(l['umis'])
for id in clonotype2tcrs_backup:
for ab in 'AB':
for t1,count1 in clonotype2tcrs_backup[id][ab].iteritems():
for t2, count2 in clonotype2tcrs_backup[id][ab].iteritems():
if t2<=t1:continue
if t1[3] == t2[3]:
print 'repeat??', count1, count2, t1, t2
if consensus_annotations_csvfile is None:
clonotype2tcrs = clonotype2tcrs_backup
else:
## now read details on the individual chains for each clonotype
# ==> tcr/human/JCC176_TX2_TCR_consensus_annotations.csv <==
# clonotype_id,consensus_id,length,chain,v_gene,d_gene,j_gene,c_gene,full_length,productive,cdr3,cdr3_nt,reads,umis
# clonotype100,clonotype100_consensus_1,550,TRB,TRBV24-1*01,TRBD1*01,TRBJ2-7*01,TRBC2*01,True,True,CATSDPGQGGYEQYF,TGTGCCACCAGTGACCCCGGACAGGGAGGATACGAGCAGTACTTC,8957,9
assert exists(consensus_annotations_csvfile)
_, lines = parse_csv_file( consensus_annotations_csvfile )
## first get clonotypes with one alpha and one beta
clonotype2tcrs = {}
for l in lines:
if l['productive'] == 'True':
id = l['clonotype_id']
if id not in clonotype2tcrs:
# dictionaries mapping from tcr to umi-count
clonotype2tcrs[id] = { 'A':Counter(), 'B':Counter() } #, 'G':[], 'D': [] }
assert id in clonotype2barcodes
ch = l['chain']
if not ch.startswith('TR'):
print 'skipline:', consensus_annotations_csvfile, ch, l['v_gene'], l['j_gene']
continue
ab = ch[2]
if ab not in 'AB':
print 'skipline:', consensus_annotations_csvfile, ch, l['v_gene'], l['j_gene']
continue
vg = l['v_gene']
if '*' not in vg:
vg += gene_suffix
if 'DV' in vg and vg not in expected_gene_names:
#print 'DV?',vg
vg = vg[:vg.index('DV')]+'/'+vg[vg.index('DV'):]
jg = l['j_gene']
if '*' not in jg:
jg += gene_suffix
# if vg in tcr_gene_remap[organism]:
# vg = tcr_gene_remap[organism][vg]
# if jg in tcr_gene_remap[organism]:
# jg = tcr_gene_remap[organism][jg]
if vg not in expected_gene_names:
print 'unrecognized V gene:', organism, vg
if not allow_unknown_genes:
continue
if jg not in expected_gene_names:
print 'unrecognized J gene:', organism, jg
if not allow_unknown_genes:
continue
#assert vg in all_align_fasta[organism]
#assert jg in all_align_fasta[organism]
tcr_chain = ( vg, jg, l['cdr3'], l['cdr3_nt'].lower() )
if tcr_chain not in clonotype2tcrs[id][ab]:
umis = int( l['umis'] )
clonotype2tcrs[id][ab][ tcr_chain ] = umis
old_umis = clonotype2tcrs_backup[id][ab][tcr_chain]
if umis != old_umis:
print 'diff_umis:',umis, old_umis, id,ab,tcr_chain
else:
print 'repeat?',id,ab,tcr_chain
else:
if l['productive'] not in [ 'None','False' ]:
print 'unproductive?',l['productive']
if verbose:
idl1 = sorted( clonotype2tcrs_backup.keys())
idl2 = sorted( clonotype2tcrs.keys())
print 'same ids:', len(idl1), len(idl2), idl1==idl2
for id in clonotype2tcrs_backup:
if id in clonotype2tcrs:
for ab in 'AB':
tl1 = sorted(clonotype2tcrs_backup[id][ab].keys())
tl2 = sorted(clonotype2tcrs[id][ab].keys())
if tl1 != tl2:
print 'diffids:',id,ab,tl1,tl2
return clonotype2tcrs, clonotype2barcodes
def make_clones_file( organism, outfile, clonotype2tcrs, clonotype2barcodes ):
''' Make a clones file with information parsed from the 10X csv files
organism is one of ['mouse','human']
outfile is the name of the clones file to be created
'''
tmpfile = outfile+'.tmp' # a temporary intermediate file
bc_mapfile = outfile+'.barcode_mapping.tsv'
outmap = open(bc_mapfile,'w')
outmap.write('clone_id\tbarcodes\n')
outfields = 'clone_id subject clone_size va_gene ja_gene vb_gene jb_gene cdr3a cdr3a_nucseq cdr3b cdr3b_nucseq'\
.split()
extra_fields = 'alpha_umi beta_umi num_alphas num_betas'.split()
outfields += extra_fields
out = open(tmpfile,'w')
out.write('\t'.join( outfields )+'\n' )
for clonotype in sorted(clonotype2tcrs.keys()):
tcrs = clonotype2tcrs[clonotype]
if len(tcrs['A']) >= 1 and len(tcrs['B']) >= 1:
atcrs = tcrs['A'].most_common()
btcrs = tcrs['B'].most_common()
if len(atcrs)>1:
print 'multiple alphas, picking top umi:',' '.join( str(x) for _,x in atcrs )
if len(btcrs)>1:
print 'multiple betas, picking top umi:',' '.join( str(x) for _,x in btcrs )
atcr, atcr_umi = atcrs[0]
btcr, btcr_umi = btcrs[0]
outl = {}
outl['clone_id'] = clonotype
outl['subject'] = 'UNK_S'
outl['clone_size'] = len(clonotype2barcodes[clonotype])
outl['va_gene'] = atcr[0]
outl['ja_gene'] = atcr[1]
outl['cdr3a'] = atcr[2]
outl['cdr3a_nucseq'] = atcr[3]
outl['alpha_umi'] = str(atcr_umi)
outl['num_alphas'] = str(len(atcrs))
outl['vb_gene'] = btcr[0]
outl['jb_gene'] = btcr[1]
outl['cdr3b'] = btcr[2]
outl['cdr3b_nucseq'] = btcr[3]
outl['beta_umi'] = str(btcr_umi)
outl['num_betas'] = str(len(btcrs))
out.write( make_tsv_line(outl,outfields)+'\n' )
outmap.write('{}\t{}\n'.format(clonotype,','.join(clonotype2barcodes[clonotype])))
out.close()
outmap.close()
python_exe = sys.executable
cmd = '{} {}/file_converter.py --input_format clones --output_format clones --input_file {} --output_file {} --organism {} --clobber --epitope UNK_E --extra_fields {} '\
.format( python_exe, paths.path_to_scripts, tmpfile, outfile, organism, ' '.join(extra_fields) )
print cmd
system(cmd)
def setup_filtered_clonotype_dicts( clonotype2tcrs, clonotype2barcodes, min_repeat_count_fraction = 0.33):
''' returns new_clonotype2tcrs, new_clonotype2barcodes
'''
# get count of how many cells support each pairing
#
pairing_counts = Counter()
for cid, tcrs in clonotype2tcrs.iteritems():
size = len(clonotype2barcodes[cid])
for t1 in tcrs['A']:
for t2 in tcrs['B']:
pairing_counts[ (t1,t2) ] += size
# this is no longer going to be a bijection!
chain_partner = {}
valid_ab_pairings = set()
for ( (t1,t2), count ) in list(pairing_counts.most_common()): # make a copy for sanity
if t1 in chain_partner or t2 in chain_partner:
t1_p2 = chain_partner.get(t1,None)
t2_p2 = chain_partner.get(t2,None)
oldcount1 = pairing_counts[ (t1,t1_p2) ]
oldcount2 = pairing_counts[ (t2_p2,t2) ]
#print 'repeat:', count, oldcount1, oldcount2,\
# t1, t2, t1_p2, t2_p2
if count >= min_repeat_count_fraction * max(oldcount1,oldcount2):
# take it anyway -- second alpha or genuinely shared alpha?
print 'take_rep_partners:', count, oldcount1, oldcount2, t1, t2, t1_p2, t2_p2
# dont overwrite the old pairing... might not do either of these!
if t1 not in chain_partner:
chain_partner[t1] = t2
if t2 not in chain_partner:
chain_partner[t2] = t1
valid_ab_pairings.add( (t1, t2 ) )
else:
print 'skip_rep_partners:', count, oldcount1, oldcount2, t1, t2, t1_p2, t2_p2
else: # neither chain already in chain_partner
#
# NOTE: removed the code checking for TIES!!!!!!!!!!!
print 'norep_partners:', count, t1, t2
chain_partner[t1] = t2
chain_partner[t2] = t1
valid_ab_pairings.add( ( t1, t2 ) )
# now let's revisit the clonotypes
pairs_tuple2clonotypes = {}
ab_counts = Counter() # for diagnostics
for (clone_size, cid) in reversed( sorted( (len(y), x) for x,y in clonotype2barcodes.iteritems() ) ):
if cid not in clonotype2tcrs:
print 'WHOAH missing tcrs for clonotype', clone_size, cid, clonotype2barcodes[cid]
continue
tcrs = clonotype2tcrs[cid]
was_good_clone = len(tcrs['A']) >= 1 and len(tcrs['B']) >= 1
pairs = []
for atcr in tcrs['A']:
for btcr in tcrs['B']:
if ( atcr,btcr ) in valid_ab_pairings:
pairs.append( (atcr,btcr) )
if pairs:
pairs_tuple = None
if len(pairs)>1:
alphas = set( x[0] for x in pairs )
betas = set( x[1] for x in pairs )
ab_counts[ (len(alphas),len(betas) ) ] += clone_size
if len(alphas) == 2 and len(betas) == 1: ## only allow double-alphas
assert len(pairs) == 2
pairs_tuple = tuple(x[1] for x in reversed(sorted( [ (pairing_counts[x],x) for x in pairs ] )))
assert len( pairs_tuple)==2
# confirm ordered by counts
assert pairing_counts[pairs_tuple[0]] >= pairing_counts[pairs_tuple[1]]
else:
ab_counts[ (1,1) ] += clone_size
pairs_tuple = tuple(pairs)
assert len(pairs_tuple) == 1
if pairs_tuple:
pairs_tuple2clonotypes.setdefault( pairs_tuple, [] ).append( cid )
else:
print 'SKIPCLONE:', was_good_clone, cid, clone_size, pairs, 'bad_pairs'
else:
print 'SKIPCLONE:', was_good_clone, cid, clone_size, 'no_valid_pairs'
## reorder pairs_tuples in the case of ties, using umis
reorder = []
for pt, clonotypes in pairs_tuple2clonotypes.iteritems():
assert len(pt) in [1,2]
if len(pt) == 2:
assert pt[0][1] == pt[1][1] # same beta chain
at1, bt = pt[0]
at2, _ = pt[1]
count1, count2 = pairing_counts[(at1,bt)], pairing_counts[(at2,bt)]
assert count1 >= count2
if count1 == count2:
# no way to figure out which is the primary alpha!
# look at umis?
c1 = sum( clonotype2tcrs[x]['A'][at1] for x in clonotypes )
c2 = sum( clonotype2tcrs[x]['A'][at2] for x in clonotypes )
print 'alphatie:', count1, count2, c1, c2, show(at1), show(at2), show(bt)
if c2 > c1:
reorder.append( pt )
for pt in reorder:
print 'reorder:', show(pt)
assert len(pt) == 2
rpt = (pt[1], pt[0])
assert pt in pairs_tuple2clonotypes and rpt not in pairs_tuple2clonotypes
pairs_tuple2clonotypes[rpt] = pairs_tuple2clonotypes[pt][:]
del pairs_tuple2clonotypes[pt]
## look for len1 pairs_tuples that overlap with two different len2 pairs_tuples
merge_into_pairs = []
for pt1 in pairs_tuple2clonotypes:
if len(pt1) == 1:
overlaps = []
for pt2 in pairs_tuple2clonotypes:
if len(pt2) == 2 and pt2[0] == pt1[0]:
overlaps.append( pt2 )
if len(overlaps)>1:
print 'badoverlaps:', len(overlaps), show(pt1), show(overlaps)
elif len(overlaps)==1:
pt2 = overlaps[0]
merge_into_pairs.append( (pt1,pt2) )
for pt1, pt2 in merge_into_pairs:
print 'mergeinto:', show(pt1), show(pt2)
pairs_tuple2clonotypes[pt2].extend( pairs_tuple2clonotypes[pt1] )
del pairs_tuple2clonotypes[pt1]
## look for pairs_tuples that will give the same clones file line
for pt1, clonotypes in pairs_tuple2clonotypes.iteritems():
for pt2 in pairs_tuple2clonotypes:
if pt1 < pt2 and pt1[0] == pt2[0]:
print 'overlap:', len(pt1), len(pt2), pt1, pt2
## now setup new clonotype2tcrs, clonotype2barcodes mappings
new_clonotype2tcrs = {}
new_clonotype2barcodes = {}
for pairs_tuple, clonotypes in pairs_tuple2clonotypes.iteritems():
c0 = clonotypes[0]
if len(clonotypes)>1:
print 'merging:', ' '.join(clonotypes)
tcrs = {'A':Counter(), 'B':Counter()}
for (atcr,btcr) in pairs_tuple:
tcrs['A'][atcr] += pairing_counts[(atcr, btcr)]
tcrs['B'][btcr] += pairing_counts[(atcr, btcr)]
if len(pairs_tuple)==2:
a1, a2 = pairs_tuple[0][0], pairs_tuple[1][0]
if tcrs['A'][a1] == tcrs['A'][a2]:
tcrs['A'][a1] += 1 # ensure the desired order
else:
assert tcrs['A'][a1] > tcrs['A'][a2]
assert len(tcrs['A']) in [1,2]
assert len(tcrs['B']) == 1
assert c0 not in new_clonotype2tcrs
new_clonotype2tcrs[c0] = tcrs
new_clonotype2barcodes[c0] = list(chain( *(clonotype2barcodes[x] for x in clonotypes)))
# print 'new:', new_clonotype2barcodes[c0]
# for c in clonotypes:
# print 'old:', clonotype2barcodes[c]
# print len(new_clonotype2barcodes[c0]), sum( len(clonotype2barcodes[x]) for x in clonotypes)
assert len(new_clonotype2barcodes[c0]) == sum( len(clonotype2barcodes[x]) for x in clonotypes)
print 'ab_counts:', ab_counts.most_common()
old_good_clonotypes = [ x for x,y in clonotype2tcrs.iteritems() if len(y['A']) >= 1 and len(y['B']) >= 1 ]
old_num_barcodes = sum( len(clonotype2barcodes[x]) for x in old_good_clonotypes )
new_num_barcodes = sum( len(x) for x in new_clonotype2barcodes.values() )
print 'old_num_barcodes:', old_num_barcodes, 'new_num_barcodes:', new_num_barcodes
return new_clonotype2tcrs, new_clonotype2barcodes
#######################################################################################################
#######################################################################################################
#######################################################################################################
#######################################################################################################
#######################################################################################################
#######################################################################################################
#######################################################################################################
if __name__ == '__main__':
with Parser(locals()) as p:
p.str('filtered_contig_annotations_csvfile').shorthand('f').required()
p.str('consensus_annotations_csvfile').shorthand('c')
p.str('clones_file').shorthand('o').required()
p.str('organism').required()
p.flag('clobber')
p.flag('stringent')
if exists(clones_file) and not clobber:
print 'ERROR -- clones_file {} already exists; use --clobber to overwrite'
exit(1)
assert organism in ['human','mouse']
clonotype2tcrs, clonotype2barcodes = read_tcr_data( organism, filtered_contig_annotations_csvfile,
consensus_annotations_csvfile )
if stringent:
clonotype2tcrs, clonotype2barcodes = setup_filtered_clonotype_dicts( clonotype2tcrs, clonotype2barcodes )
make_clones_file( organism, clones_file, clonotype2tcrs, clonotype2barcodes )
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.